route-engine-js 1.25.0 → 1.26.0

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 Ui=Object.defineProperty;var Bi=(e,t)=>{for(var r in t)Ui(e,r,{get:t[r],enumerable:!0})};var Ln=Symbol.for("immer-nothing"),Cn=Symbol.for("immer-draftable"),se=Symbol.for("immer-state");function he(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Ge=Object.getPrototypeOf;function ae(e){return!!e&&!!e[se]}function De(e){return e?$n(e)||Array.isArray(e)||!!e[Cn]||!!e.constructor?.[Cn]||Ot(e)||Lt(e):!1}var zi=Object.prototype.constructor.toString();function $n(e){if(!e||typeof e!="object")return!1;let t=Ge(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===zi}function Ct(e,t){Rt(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function Rt(e){let t=e[se];return t?t.type_:Array.isArray(e)?1:Ot(e)?2:Lt(e)?3:0}function ar(e,t){return Rt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function kn(e,t,r){let n=Rt(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function Wi(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Ot(e){return e instanceof Map}function Lt(e){return e instanceof Set}function Te(e){return e.copy_||e.base_}function cr(e,t){if(Ot(e))return new Map(e);if(Lt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=$n(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[se];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],c=n[s];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(n[s]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[s]})}return Object.create(Ge(e),n)}else{let n=Ge(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function pr(e,t=!1){return $t(e)||ae(e)||!De(e)||(Rt(e)>1&&(e.set=e.add=e.clear=e.delete=qi),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>pr(n,!0))),e}function qi(){he(2)}function $t(e){return Object.isFrozen(e)}var Hi={};function Pe(e){let t=Hi[e];return t||he(0,e),t}var ot;function Tn(){return ot}function Yi(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Sn(e,t){t&&(Pe("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function lr(e){ur(e),e.drafts_.forEach(Ki),e.drafts_=null}function ur(e){e===ot&&(ot=e.parent_)}function _n(e){return ot=Yi(ot,e)}function Ki(e){let t=e[se];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Rn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[se].modified_&&(lr(t),he(4)),De(e)&&(e=St(t,e),t.parent_||_t(t,e)),t.patches_&&Pe("Patches").generateReplacementPatches_(r[se].base_,e,t.patches_,t.inversePatches_)):e=St(t,r,[]),lr(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Ln?e:void 0}function St(e,t,r){if($t(t))return t;let n=t[se];if(!n)return Ct(t,(o,i)=>On(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return _t(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let o=n.copy_,i=o,s=!1;n.type_===3&&(i=new Set(o),o.clear(),s=!0),Ct(i,(c,a)=>On(e,n,o,c,a,r,s)),_t(e,o,!1),r&&e.patches_&&Pe("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function On(e,t,r,n,o,i,s){if(ae(o)){let c=i&&t&&t.type_!==3&&!ar(t.assigned_,n)?i.concat(n):void 0,a=St(e,o,c);if(kn(r,n,a),ae(a))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(De(o)&&!$t(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;St(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&_t(e,o)}}function _t(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&pr(t,r)}function Gi(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:Tn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=hr;r&&(o=[n],i=it);let{revoke:s,proxy:c}=Proxy.revocable(o,i);return n.draft_=c,n.revoke_=s,c}var hr={get(e,t){if(t===se)return e;let r=Te(e);if(!ar(r,t))return Ji(e,r,t);let n=r[t];return e.finalized_||!De(n)?n:n===ir(e.base_,t)?(sr(e),e.copy_[t]=fr(n,e)):n},has(e,t){return t in Te(e)},ownKeys(e){return Reflect.ownKeys(Te(e))},set(e,t,r){let n=Dn(Te(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=ir(Te(e),t),i=o?.[se];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(Wi(r,o)&&(r!==void 0||ar(e.base_,t)))return!0;sr(e),dr(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return ir(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,sr(e),dr(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Te(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){he(11)},getPrototypeOf(e){return Ge(e.base_)},setPrototypeOf(){he(12)}},it={};Ct(hr,(e,t)=>{it[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});it.deleteProperty=function(e,t){return it.set.call(this,e,t,void 0)};it.set=function(e,t,r){return hr.set.call(this,e[0],t,r,e[0])};function ir(e,t){let r=e[se];return(r?Te(r):e)[t]}function Ji(e,t,r){let n=Dn(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function Dn(e,t){if(!(t in e))return;let r=Ge(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=Ge(r)}}function dr(e){e.modified_||(e.modified_=!0,e.parent_&&dr(e.parent_))}function sr(e){e.copy_||(e.copy_=cr(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Xi=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,n)=>{if(typeof t=="function"&&typeof r!="function"){let i=r;r=t;let s=this;return function(a=i,...l){return s.produce(a,d=>r.call(this,d,...l))}}typeof r!="function"&&he(6),n!==void 0&&typeof n!="function"&&he(7);let o;if(De(t)){let i=_n(this),s=fr(t,void 0),c=!0;try{o=r(s),c=!1}finally{c?lr(i):ur(i)}return Sn(i,n),Rn(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===Ln&&(o=void 0),this.autoFreeze_&&pr(o,!0),n){let i=[],s=[];Pe("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else he(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...c)=>this.produceWithPatches(s,a=>t(a,...c));let n,o;return[this.produce(t,r,(s,c)=>{n=s,o=c}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){De(e)||he(8),ae(e)&&(e=Ne(e));let t=_n(this),r=fr(e,void 0);return r[se].isManual_=!0,ur(t),r}finishDraft(e,t){let r=e&&e[se];(!r||!r.isManual_)&&he(9);let{scope_:n}=r;return Sn(n,t),Rn(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let o=t[r];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}r>-1&&(t=t.slice(r+1));let n=Pe("Patches").applyPatches_;return ae(e)?n(e,t):this.produce(e,o=>n(o,t))}};function fr(e,t){let r=Ot(e)?Pe("MapSet").proxyMap_(e,t):Lt(e)?Pe("MapSet").proxySet_(e,t):Gi(e,t);return(t?t.scope_:Tn()).drafts_.push(r),r}function Ne(e){return ae(e)||he(10,e),Pn(e)}function Pn(e){if(!De(e)||$t(e))return e;let t=e[se],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=cr(e,t.scope_.immer_.useStrictShallowCopy_)}else r=cr(e,!0);return Ct(r,(n,o)=>{kn(r,n,Pn(o))}),t&&(t.finalized_=!1),r}var ce=new Xi,mr=ce.produce,Od=ce.produceWithPatches.bind(ce),Ld=ce.setAutoFreeze.bind(ce),$d=ce.setUseStrictShallowCopy.bind(ce),kd=ce.applyPatches.bind(ce),Td=ce.createDraft.bind(ce),Dd=ce.finishDraft.bind(ce);var m={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},L={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},Je={NOT:0};var E=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},oe=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var gr=e=>{if(!e||e.trim()==="")throw new E("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new E(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${r}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let r of t)if(e.trim().endsWith(r))throw new E(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Nn=e=>{if(e.trim().endsWith(" in"))throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new E(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);let n=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of n){if(!o)throw new E(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new E(`Invalid loop syntax (got: '$for ${e}')`)}};var Vn=(e,t,r=!1)=>{if(t===null)return new oe(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new oe(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new oe(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new oe(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},jn=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new oe(`Unknown function '${e}' (${r})`)};var Qi=(e,t,r={})=>{let n={},o={};r&&typeof r=="object"&&(r.functions!==void 0||r.partials!==void 0?(n=r.functions||{},o=r.partials||{}):typeof r=="object"&&(n=r));let s=$(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},$=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return K(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return K(e.path,r,n);if(e.type===m.INTERPOLATION)return es(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return Fn(e,t,r,n);case m.BINARY:return Un(e,t,r,n);case m.UNARY:return Bn(e,t,r,n);case m.CONDITIONAL:return rs(e,t,r,n);case m.LOOP:return as(e,t,r,n);case m.OBJECT:return ls(e,t,r,n);case m.ARRAY:return us(e,t,r,n);case m.PARTIAL:return ds(e,t,r,n);case m.PATH_REFERENCE:return fs(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Mn=new Map,Zi=e=>{let t=[],r="",n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")r&&(t.push({type:"property",value:r}),r=""),n=!0;else if(i==="]"){if(n&&r){let s=r.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let c=s.slice(1,-1);t.push({type:"property",value:c})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},K=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=Mn.get(e);if(!n){let i=[],s="",c=0;for(let a=0;a<e.length;a++){let l=e[a];l==="["?(c++,s+=l):l==="]"?(c--,s+=l):l==="."&&c===0?s&&(i.push(s),s=""):s+=l}s&&i.push(s),n=[];for(let a of i){let l=Zi(a.trim());n.push(...l)}Mn.set(e,n)}let o=t;for(let i=0;i<n.length;i++){let s=n[i];if(s.type==="property"&&s.value in r){o=r[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},es=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=$(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},Fn=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw jn(e.name,o);let s=e.args.map(c=>$(c,t,r,n));return i(...s)},_e=(e,t,r,n)=>{if(e.var&&!e.type)return K(e.var,r,n);switch(e.type){case m.VARIABLE:return K(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return Un(e,t,r,n);case m.UNARY:return Bn(e,t,r,n);case m.FUNCTION:return Fn(e,t,r,n);default:return $(e,t,r,n)}},Un=(e,t,r,n)=>{if(e.op===L.AND||e.op===L.OR){let s=_e(e.left,t,r,n),c=_e(e.right,t,r,n);switch(e.op){case L.AND:return s&&c;case L.OR:return s||c}}let o=$(e.left,t,r,n),i=$(e.right,t,r,n);switch(e.op){case L.EQ:return o==i;case L.NEQ:return o!=i;case L.GT:return o>i;case L.LT:return o<i;case L.GTE:return o>=i;case L.LTE:return o<=i;case L.IN:return Array.isArray(i)?i.includes(o):!1;case L.ADD:if(typeof o!="number"||typeof i!="number")throw new oe(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case L.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new oe(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Bn=(e,t,r,n)=>{let o=e.op===Je.NOT?_e(e.operand,t,r,n):$(e.operand,t,r,n);if(e.op===Je.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},ts=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(K(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let c={};for(let a of s.properties){let l=a.parsedKey?$(a.parsedKey,t,r,n):a.key,d=a.value;if(d.type===m.LITERAL)c[l]=d.value;else if(d.type===m.VARIABLE)c[l]=K(d.path,r,n);else if(d.type===m.INTERPOLATION){let u=[];for(let f of d.parts)if(typeof f=="string")u.push(f);else if(f.type===m.VARIABLE){let p=K(f.path,r,n);u.push(p!=null?String(p):"")}else{let p=$(f,t,r,n);u.push(p!=null?String(p):"")}c[l]=u.join("")}else c[l]=$(d,t,r,n)}return c}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let c={};for(let a of s.properties){let l=a.parsedKey?$(a.parsedKey,t,r,n):a.key,d=a.value;if(d.type===m.LITERAL)c[l]=d.value;else if(d.type===m.VARIABLE)c[l]=K(d.path,r,n);else if(d.type===m.INTERPOLATION){let u=[];for(let f of d.parts)if(typeof f=="string")u.push(f);else if(f.type===m.VARIABLE){let p=K(f.path,r,n);u.push(p!=null?String(p):"")}else{let p=$(f,t,r,n);u.push(p!=null?String(p):"")}c[l]=u.join("")}else c[l]=$(d,t,r,n)}return c}}}return null},rs=(e,t,r,n)=>{let o=ts(e,t,r,n);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||_e(s,t,r,n))return $(e.bodies[i],t,r,n)}return zn},ns=(e,t)=>{let r=e.body,n=e.itemVar;if(r.type===m.CONDITIONAL&&r.conditions.length===1&&r.conditions[0].type===m.VARIABLE){let o=r.conditions[0].path,i=r.bodies[0];if(o.startsWith(n+".")){let s=o.substring(n.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let a of i.properties)if(a.parsedKey)return null;let c=[];for(let a=0;a<t.length;a++){let l=t[a];if(l[s]){let d={};for(let u of i.properties){let f=u.key,p=u.value;if(p.type===m.LITERAL)d[f]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)d[f]=l;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);d[f]=l[g]}else return null}else if(p.type===m.INTERPOLATION){let h=[],g=!0;for(let y of p.parts)if(typeof y=="string")h.push(y);else if(y.type===m.VARIABLE){let b=y.path;if(b===n)h.push(l!=null?String(l):"");else if(b.startsWith(n+".")){let A=b.substring(n.length+1),v=l[A];h.push(v!=null?String(v):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;d[f]=h.join("")}else return null}c.push(d)}}return c}}}return null},os=(e,t)=>{let r=e.body,n=e.itemVar,o=ns(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let c of r.properties)if(c.parsedKey)return null;let i=[],s=!0;for(let c of r.properties){let a=c.key,l=c.value;if(l.type===m.LITERAL)i.push({key:a,type:"literal",value:l.value});else if(l.type===m.VARIABLE){let d=l.path;if(d===n)i.push({key:a,type:"item"});else if(d.startsWith(n+".")){let u=d.substring(n.length+1);if(!u.includes(".")&&!u.includes("["))i.push({key:a,type:"prop",prop:u});else{s=!1;break}}else{s=!1;break}}else if(l.type===m.INTERPOLATION&&l.parts.length===1){let d=l.parts[0];if(d.type===m.VARIABLE){let u=d.path;if(u===n)i.push({key:a,type:"item_string"});else if(u.startsWith(n+".")){let f=u.substring(n.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:a,type:"prop_string",prop:f});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let c=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let a=0;a<t.length;a++){let l=t[a];c[a]={id:l.id,title:l.title!=null?String(l.title):"",completed:l.completed}}else for(let a=0;a<t.length;a++){let l=t[a],d={};for(let u of i)if(u.type==="literal")d[u.key]=u.value;else if(u.type==="item")d[u.key]=l;else if(u.type==="prop")d[u.key]=l[u.prop];else if(u.type==="item_string")d[u.key]=l!=null?String(l):"";else if(u.type==="prop_string"){let f=l[u.prop];d[u.key]=f!=null?String(f):""}c[a]=d}return c}}return null},is=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let c=e.itemVar,a=e.indexVar;for(let l=0;l<o.length;l++){let d=o[l],u={},f={...n,[c]:d,...a&&{[a]:l}};f.__paths__||(f.__paths__=n.__paths__||{});let p=e.iterable.path||"";if(n&&n.__paths__&&p){let h=p.split("."),g=h[0];g in n.__paths__&&(p=n.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}f.__paths__={...f.__paths__,[c]:`${p}[${l}]`,...a&&{[a]:l}};for(let h of s.properties){let g=h.parsedKey?$(h.parsedKey,t,r,f):h.key,y=h.value;if(y.type===m.LITERAL)u[g]=y.value;else if(y.type===m.VARIABLE){let b=y.path;if(b===c)u[g]=d;else if(b===a)u[g]=l;else if(b.startsWith(c+".")){let A=b.substring(c.length+1);!A.includes(".")&&!A.includes("[")?u[g]=d[A]:u[g]=K(b,r,{...n,[c]:d,...a&&{[a]:l}})}else u[g]=K(b,r,{...n,[c]:d,...a&&{[a]:l}})}else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let v=A.path,_;if(v===c)_=d;else if(v===a)_=l;else if(v.startsWith(c+".")){let P=v.substring(c.length+1);!P.includes(".")&&!P.includes("[")?_=d[P]:_=K(v,r,{...n,[c]:d,...a&&{[a]:l}})}else _=K(v,r,{...n,[c]:d,...a&&{[a]:l}});b.push(_!=null?String(_):"")}else{let v={...n,[c]:d,...a&&{[a]:l}},_=$(A,t,r,v);b.push(_!=null?String(_):"")}u[g]=b.join("")}else{let b={...n,[c]:d,...a&&{[a]:l}};u[g]=$(y,t,r,b)}}i.push(u)}return i}return null},ss=(e,t,r)=>{let n=e.body;if(n.type===m.OBJECT&&n.properties.length===1&&n.properties[0].key==="$if item.visible"){let i=n.properties[0].value;if(i.type===m.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===m.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===m.OBJECT&&s.properties.length===2){let c=s.properties[0],a=s.properties[1];if(c.key==="id"&&c.value.type===m.VARIABLE&&c.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===m.CONDITIONAL){let l=[];for(let d=0;d<t.length;d++){let u=t[d];if(u.visible){let f={id:u.id};u.highlighted?(f.highlight=!0,f.message=`This item is highlighted: ${u.name}`):(f.highlight=!1,f.message=u.name),l.push(f)}}return l}}}}return null},as=(e,t,r,n)=>{let o=$(e.iterable,t,r,n);if(!Array.isArray(o)){let l,d=!1;if(e.iterable.type===m.FUNCTION){d=!0;let f=e.iterable.args.map(p=>p.type===m.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===m.VARIABLE?p.path:p.type===m.FUNCTION?`${p.name}(...)`:"?").join(", ");l=`${e.iterable.name}(${f})`}else l=e.iterable.path||"undefined";let u=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw Vn(u,o,d)}if(!e.indexVar){let l=ss(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=os(e,o);if(l!==null)return l}let i=is(e,t,r,n,o);if(i!==null)return i;let s=[],c=e.iterable.path||"";if(n&&n.__paths__&&c){let l=c.split("."),d=l[0];d in n.__paths__&&(c=n.__paths__[d],l.length>1&&(c+="."+l.slice(1).join(".")))}let a=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(l=>l.type===m.OBJECT&&l.properties.some(d=>d.key.startsWith("$if ")||d.key.startsWith("$when "))));for(let l=0;l<o.length;l++){let d=e.indexVar?{...n,[e.itemVar]:o[l],[e.indexVar]:l}:{...n,[e.itemVar]:o[l]};d.__paths__||(d.__paths__=n.__paths__||{}),d.__paths__={...d.__paths__,[e.itemVar]:`${c}[${l}]`},e.indexVar&&(d.__paths__[e.indexVar]=l);let u=$(e.body,t,r,d);if(Array.isArray(u)&&u.length===1&&!a){let f=u[0];s.push(f===void 0?{}:f)}else s.push(u===void 0?{}:u)}return s},cs=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?$(o.parsedKey,t,r,n):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let c={},a={},l=!0;for(let d of s.properties){let u=d.parsedKey?$(d.parsedKey,t,r,n):d.key,f=d.value;if(f.type===m.LITERAL)a[u]=f.value;else if(f.type===m.VARIABLE)a[u]=K(f.path,r,n);else if(f.type===m.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=K(h.path,r,n);p.push(g!=null?String(g):"")}else{l=!1;break}if(!l)break;a[u]=p.join("")}else if(f.type===m.OBJECT&&f.properties.length<=5){let p={};for(let h of f.properties){let g=h.key,y=h.value;if(y.type===m.LITERAL)p[g]=y.value;else if(y.type===m.VARIABLE)p[g]=K(y.path,r,n);else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let v=K(A.path,r,n);b.push(v!=null?String(v):"")}else{l=!1;break}if(!l)break;p[g]=b.join("")}else{l=!1;break}}if(!l)break;a[u]=p}else{l=!1;break}}if(l)return c[i]=a,c}}return null},ls=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!_e(e.whenCondition,o,r,n))return;let i=cs(e,t,r,n);if(i!==null)return i;if(e.fast){let l={};for(let d of e.properties){let u=d.parsedKey?$(d.parsedKey,t,r,n):d.key,f=d.value;if(f.type===m.LITERAL)l[u]=f.value;else if(f.type===m.VARIABLE)l[u]=K(f.path,r,n);else if(f.type===m.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=K(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=$(h,t,r,n);p.push(g!=null?String(g):"")}l[u]=p.join("")}else l[u]=$(f,t,r,n)}return l}let s={},c=null,a=!1;for(let l of e.properties)if(!l.key.startsWith("$if ")&&!l.key.match(/^\$if\s+\w+.*:?$/)&&!l.key.startsWith("$elif")&&!l.key.startsWith("$else")&&!l.key.startsWith("$for ")){a=!0;break}for(let l of e.properties)if(l.key.startsWith("$if ")||l.key.match(/^\$if\s+\w+.*:?$/)){let d=$(l.value,t,r,n);if(!a&&d!==null&&d!==void 0)return Array.isArray(d)&&d.length===1?d[0]:d;typeof d=="object"&&d!==null&&!Array.isArray(d)&&Object.assign(s,d)}else if(l.key.startsWith("$for ")){if(e.properties.length===1)return $(l.value,t,r,n)}else{let d=l.value;if(d&&d.type===m.OBJECT&&d.properties){let u=d.properties.find(f=>f.key.startsWith("$for "));if(u){let f=$(u.value,t,r,n);f!==void 0&&(s[l.key]=f)}else{let f=$(l.value,t,r,n);f!==void 0&&(s[l.key]=f)}}else{let u=l.parsedKey?$(l.parsedKey,t,r,n):l.key,f=$(l.value,t,r,n);f!==void 0&&(s[u]=f)}}return s},zn={},us=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=$(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=$(i,t,r,n);s!==zn&&s!==void 0&&o.push(s)}return o},ds=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,c=t.partials||{},a=t.functions||t;if(s&&!_e(s,a,r,n))return;if(!c[o])throw new oe(`Partial '${o}' is not defined`);let l=n._partialStack||[];if(l.includes(o))throw new oe(`Circular partial reference detected: ${o}`);let d=c[o],u=r,f={...n,_partialStack:[...l,o]};if(n){u={...r};for(let p of Object.keys(n))p.startsWith("_")||(u[p]=n[p])}if(i){let p=$(i,t,r,n);u={...u,...p}}return $(d,t,u,f)},fs=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],c=i.slice(1);if(!n||!(s in n))throw new oe(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(n.__paths__||(n.__paths__={}),!(s in n.__paths__))throw new oe(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=n.__paths__[s];if(typeof a=="number"){if(c.length>0)throw new oe(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return c.length>0&&(a+="."+c.join(".")),a};var yr=Qi;var ps=/\$\{([^}]*)\}/g,hs=/#\{([^}]*)\}/g,qn=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=ms(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},ms=(e,t={})=>e.trim()?gs(e).map(n=>ys(n.trim(),t)):[],gs=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let c=e[s],a=s>0?e[s-1]:"";!o&&(c==='"'||c==="'")?(o=!0,i=c,r+=c):o&&c===i&&a!=="\\"?(o=!1,i="",r+=c):!o&&c==="("?(n++,r+=c):!o&&c===")"?(n--,r+=c):!o&&c===","&&n===0?(t.push(r),r=""):r+=c}return r&&t.push(r),t},ys=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:m.LITERAL,value:parseFloat(e)};if(e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};let r=qn(e,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};let n=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:c,type:a}of o){let l=0;for(;l<n.length;){let d=Ve(n.substring(l),c);if(d===-1)break;let u=l+d;u>i&&(i=u,s={op:c,type:a}),l=u+c.length}}if(i!==-1)try{return X(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},Hn=/^\w+\(.*\)$/,bs=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Is=e=>{if(!(!e||e.trim()===""||Hn.test(e))&&bs.test(e))throw e.includes("?")&&e.includes(":")?new E(`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 E(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new E(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Wn=e=>{let t=e.trim();if(Hn.test(t))throw new E(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new E(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new E(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new E(`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 E(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:m.PATH_REFERENCE,path:t}},st=(e,t={})=>{let r=e.trim();Is(r);let n=qn(r,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};if(r.includes("[")&&!/[\s+\-*/%|&?:]/.test(r)){let o=0;for(let i of r)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:r}},br=(e,t={})=>{let r=e,n=[];(e.includes("\\${")||e.includes("\\#{"))&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),r=r.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(l,d)=>{let u=`__ESCAPED_${n.length}__`;return n.push(d),u}),r=r.replace(/\\(#\{[^}]*\})/g,(l,d)=>{let u=`__ESCAPED_${n.length}__`;return n.push(d),u}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(ps)],i=[...r.matchAll(hs)],s=[...o.map(l=>({match:l,type:"variable"})),...i.map(l=>({match:l,type:"pathref"}))].sort((l,d)=>l.match.index-d.match.index);if(s.length===0){let l=r;for(let d=0;d<n.length;d++)l=l.replace(`__ESCAPED_${d}__`,n[d]);return{type:m.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:l,type:d}=s[0];try{return d==="variable"?st(l[1],t):Wn(l[1])}catch(u){if(u.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw u}}let c=[],a=0;for(let{match:l,type:d}of s){let[u,f]=l,p=l.index;if(p>a){let h=r.substring(a,p);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&c.push(h)}try{let h;d==="variable"?h=st(f.trim(),t):h=Wn(f.trim()),c.push(h)}catch(h){if(h.message==="Invalid array index syntax")c.push(u);else throw h}a=p+u.length}if(a<r.length){let l=r.substring(a);for(let d=0;d<n.length;d++)l=l.replace(`__ESCAPED_${d}__`,n[d]);l&&c.push(l)}return{type:m.INTERPOLATION,parts:c}};var wr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Gn=e=>Object.keys(e),re=e=>e.join("."),Re=(e,t,r)=>{let n=Gn(e).filter(o=>!t.has(o));if(n.length>0)throw new E(`Unexpected key '${n[0]}' in condition JSON at '${re(r)}'`)},Oe=(e,t)=>typeof e=="string"?br(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?ws(e,t):Es(e,t):{type:m.LITERAL,value:e},As=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new E("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new E("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new E("Empty $each body not allowed");if(r.$partial!==void 0)throw new E("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${n}`]:r}},ws=(e,t)=>{let r=[],n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let a=As(i),l=Object.keys(a);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let d=Kn(l[0],a[l[0]],t,!0);r.push(d),n=!0;continue}}catch(a){throw a instanceof E?a:new E(a.message)}let c=Object.keys(i);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let a=Kn(c[0],i[c[0]],t);r.push(a),n=!0;continue}}let s=Oe(i,t);r.push(s),(s.type===m.FUNCTION||s.type===m.CONDITIONAL||s.type===m.LOOP||s.type===m.PARTIAL||s.type===m.OBJECT&&!s.fast||s.type===m.ARRAY&&!s.fast)&&(n=!0)}return{type:m.ARRAY,items:r,fast:!n}},Es=(e,t)=>{let r=[],n=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new E("$partial value must be a string");if(e.$partial.trim()==="")throw new E("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],l=[];for(let[b]of i)for(let A of a)if(b===A||b.startsWith(A+" ")||b.startsWith(A+"#")){l.push(A);break}if(l.length>0)throw new E(`Cannot use $partial with ${l.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:d,$when:u,...f}=e,p={},h=!1;for(let[b,A]of Object.entries(f)){let v=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(v=b.slice(1)),p[v]=A,h=!0}let g=null;if(h&&(g=Oe(p,t),g.type===m.OBJECT)){let b=!1;for(let A of g.properties)if(A.value.type===m.VARIABLE||A.value.type===m.INTERPOLATION||A.value.type===m.FUNCTION||A.value.type===m.CONDITIONAL||A.value.type===m.OBJECT&&!A.value.fast||A.value.type===m.ARRAY&&!A.value.fast){b=!0;break}b&&(g.fast=!1)}let y={type:m.PARTIAL,name:d,data:g};return u!==void 0&&(y.whenCondition=Yn(u,t)),y}for(let[a,l]of i)if(a==="$when"){if(o!==null)throw new E("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new E("Missing condition expression after '$when'");o=Yn(l,t),n=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new E("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[a,l]=i[s];if(a==="$when"){s++;continue}if(a==="$each")throw new E("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let d=vs(i,s,t);r.push({key:a,value:d.node}),n=!0,s=d.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let d=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",u=d?`:${d}`:"";throw new E(`$for loops must be inside arrays - use '- $for${u} item in items:' instead of '$for${u} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(a.startsWith("$elif ")||a.startsWith("$else"))throw new E(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new E("Missing condition expression after '$if'");{let d=Oe(l,t);(d.type===m.FUNCTION||d.type===m.CONDITIONAL||d.type===m.PARTIAL||d.type===m.OBJECT&&!d.fast||d.type===m.ARRAY&&!d.fast)&&(n=!0);let u=br(a,t),f={key:a,value:d};(u.type!==m.LITERAL||u.value!==a)&&(f.parsedKey=u),r.push(f),s++}}}let c={type:m.OBJECT,properties:r,fast:!n};return o&&(c.whenCondition=o),c},vs=(e,t,r={})=>{let n=[],o=[],i=t,[s,c]=e[i],a=null,l;if(s.startsWith("$if#")){let u=s.match(/^\$if#(\w+)\s+(.+)$/);if(u)a=u[1],l=u[2];else throw new E(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());gr(l);let d=X(l,r);for(n.push(d),o.push(Oe(c,r)),i++;i<e.length;){let[u,f]=e[i],p=!1,h;if(a?u.startsWith(`$elif#${a} `)?(h=u.substring(`$elif#${a} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(u===`$else#${a}`||u===`$else#${a}:`)&&(p=!0,h=null):u.startsWith("$elif ")?(h=u.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(u==="$else"||u==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{gr(h);let g=X(h,r);n.push(g)}if(o.push(Oe(f,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:a},nextIndex:i}},Ir={eq:L.EQ,neq:L.NEQ,gt:L.GT,gte:L.GTE,lt:L.LT,lte:L.LTE,in:L.IN,add:L.ADD,sub:L.SUBTRACT},Ar={all:L.AND,any:L.OR},xs=new Set(["var","literal","call","not",...Object.keys(Ir),...Object.keys(Ar)]),Cs=(e,t,r)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${re(r)}' requires an array`);if(e.length!==2)throw new E(`Condition JSON operator '${t}' at '${re(r)}' requires exactly 2 operands`);return e},Ss=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${re(o)}' requires an array`);if(e.length===0)throw new E(`Condition JSON operator '${t}' at '${re(o)}' requires at least 1 condition`);return e.map((s,c)=>Ie(s,n,[...o,c])).reduce((s,c)=>({type:m.BINARY,op:r,left:s,right:c}))},_s=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],Re(e,new Set(["call","args"]),r);else if(wr(e.call))n=e.call.name,o=e.call.args??[],Re(e,new Set(["call"]),r),Re(e.call,new Set(["name","args"]),[...r,"call"]);else throw new E(`Condition JSON call at '${re(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new E(`Condition JSON call at '${re(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new E(`Invalid condition JSON function name '${n}' at '${re(r)}'`);if(!Array.isArray(o))throw new E(`Condition JSON call '${n}' at '${re(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>Ie(i,t,[...r,"args",s]))}},Ie=(e,t={},r=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:m.LITERAL,value:e};if(Array.isArray(e))throw new E(`Condition JSON array at '${re(r)}' must be wrapped in an operator or { literal: [...] }`);if(!wr(e))throw new E(`Invalid condition JSON value at '${re(r)}'`);let n=Gn(e);if(n.length===0)throw new E(`Condition JSON object at '${re(r)}' must contain an operator`);let o=n.filter(s=>xs.has(s));if(o.length===0)throw new E(`Unknown condition JSON operator '${n[0]}' at '${re(r)}'`);if(o.length>1)throw new E(`Condition JSON at '${re(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(Re(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new E(`Condition JSON var at '${re(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return Re(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return _s(e,t,r);if(i==="not")return Re(e,new Set(["not"]),r),{type:m.UNARY,op:Je.NOT,operand:Ie(e.not,t,[...r,"not"])};if(i in Ar)return Re(e,new Set([i]),r),Ss(e[i],i,Ar[i],t,[...r,i]);if(i in Ir){Re(e,new Set([i]),r);let s=Cs(e[i],i,[...r,i]);return{type:m.BINARY,op:Ir[i],left:Ie(s[0],t,[...r,i,0]),right:Ie(s[1],t,[...r,i,1])}}throw new E(`Unknown condition JSON operator '${i}' at '${re(r)}'`)},Yn=(e,t={})=>{if(e==null)throw new E("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression after '$when'");return X(e,t)}return wr(e)||Array.isArray(e)?Ie(e,t):{type:m.LITERAL,value:e}},X=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let l=e.slice(1,-1),d=0,u=!0;for(let f=0;f<l.length;f++)if(l[f]==="("?d++:l[f]===")"&&d--,d<0){u=!1;break}if(u&&d===0)return X(l,t)}let r=Ve(e,"||");if(r!==-1)return{type:m.BINARY,op:L.OR,left:X(e.substring(0,r).trim(),t),right:X(e.substring(r+2).trim(),t)};let n=Ve(e,"&&");if(n!==-1)return{type:m.BINARY,op:L.AND,left:X(e.substring(0,n).trim(),t),right:X(e.substring(n+2).trim(),t)};let o=[{op:">=",type:L.GTE},{op:"<=",type:L.LTE},{op:"==",type:L.EQ},{op:"!=",type:L.NEQ},{op:">",type:L.GT},{op:"<",type:L.LT},{op:" in ",type:L.IN}];for(let{op:l,type:d}of o){let u=Ve(e,l);if(u!==-1)return{type:m.BINARY,op:d,left:X(e.substring(0,u).trim(),t),right:X(e.substring(u+l.length).trim(),t)}}let i=-1,s=null,c=[{op:" + ",type:L.ADD},{op:" - ",type:L.SUBTRACT}];for(let{op:l,type:d}of c){let u=0;for(;u<e.length;){let f=Ve(e.substring(u),l);if(f===-1)break;let p=u+f;p>i&&(i=p,s={op:l,type:d}),u=p+l.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:X(e.substring(0,i).trim(),t),right:X(e.substring(i+s.op.length).trim(),t)};let a=[" * "," / "," % "];for(let l of a)if(Ve(e,l)!==-1)throw new E(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:m.UNARY,op:Je.NOT,operand:X(e.substring(1).trim(),t)}:Jn(e,t)},Ve=(e,t)=>{let r=0,n=0;for(;n<=e.length-t.length;){if(e[n]==="(")r++;else if(e[n]===")")r--;else if(r===0&&e.substring(n,n+t.length)===t)return n;n++}return-1},Rs=e=>{if(e=e.trim(),e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:m.LITERAL,value:""};if(e==="{}")return{type:m.LITERAL,value:{}};if(e==="[]")return{type:m.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:m.LITERAL,value:t}:{type:m.VARIABLE,path:e}},Jn=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return st(r,t);let o=Rs(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return st(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Os=(e,t=!1)=>{let r=t?"$each":"$for";try{Nn(e)}catch(n){if(n instanceof E&&t){let o=n.message.replace(/\$for/g,"$each");throw new E(o.replace("Parse Error: ",""))}throw n}},Kn=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new E(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],c=i[2].trim();Os(c,n);let a=c.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let y=n?"$each":"$for";throw new E(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${c}')`)}let l=a[1].trim(),d=a[2].trim(),u,f=null;if(l.includes(",")){let y=l.split(",").map(b=>b.trim());if(y.length!==2)throw new E(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);u=y[0],f=y[1]}else u=l;let p=["this","undefined","null","true","false"];if(p.includes(u))throw new E(`Reserved variable name: ${u}`);if(f&&p.includes(f))throw new E(`Reserved variable name: ${f}`);let h=Jn(d,r),g=Oe(t,r);return{type:m.LOOP,itemVar:u,indexVar:f,iterable:h,body:g,flatten:s!=="nested"}};var Ls=(e,t={})=>{let{functions:r={}}=t;return Oe(e,r)},kt=Ls;var at={};Bi(at,{now:()=>$s});var $s=()=>Date.now();var ks=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...at,...n},s=kt(e,{functions:i}),c={};for(let[a,l]of Object.entries(o))c[a]=kt(l,{functions:i});return yr(s,t,{functions:i,partials:c})},ie=ks;var Ts=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Ds=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Ps=(e,t)=>{if(Ts(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression");return X(e,t)}return Ie(e,t)},Ns=(e,t={},r={})=>{let n=Ds(r),o={...at,...n},i=Ps(e,o);return!!_e(i,{functions:o,partials:{}},t,{})},Er=Ns;var lt=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return Er(e,t)},ro=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=a=>a,transformActionFirstArgument:c=a=>a}=r;for(let[a,l]of Object.entries(t))a!=="createInitialState"&&(a.startsWith("select")?o[a]=(...d)=>l(s(n),...d):i[a]=(...d)=>{let u;return n=mr(n,p=>{let h=l(c(p),...d);u=h!==void 0&&!ae(h)?h:void 0}),u});return{...o,...i}},Pt=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return mr(n,i=>{o.forEach(s=>{t.forEach(c=>{c(i,s)})})})};var Vs=(e,t)=>{if(e.default!==void 0)return e.default;let r=["number","boolean","string","object"];if(!r.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${r.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},de=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),ct=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),no=e=>{let t=ae(e)?Ne(e):e;return structuredClone(t)},js=({characterId:e,resourceCharacter:t,variables:r={}}={})=>{if(!de(t,"nameVariableId"))return;let n=t.nameVariableId,o=r?.[n];if(typeof o!="string")throw new Error(`Character "${e}" nameVariableId "${n}" must resolve to a string variable`);return o},Nt=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0;if(t?.name!==void 0)return t.name;if(r!==void 0)return r;let s=js({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},Le=e=>de(e,"computed"),Xe=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Le(t[r]))),Ms=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),vr=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},Fs=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=Ms(e),[n,o,...i]=r;if(n==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return vr(s,i)}return n==="runtime"?vr(t.runtime,r.slice(1)):vr(t,r)},Us=(e,t,r)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(r!==void 0&&t.length!==r)throw new Error(`Computed expression operator "${e}" requires ${r} operand(s)`)},Xn=(e,t)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(t.length===0)throw new Error(`Computed expression operator "${e}" requires at least one operand`)},Bs=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},me=(e,t,r,n)=>(Us(e,t,n),t.map(o=>Dt(o,r))),ue=(e,t,r,n)=>{let o=me(e,t,r,n);return o.forEach(i=>Bs(e,i)),o},zs=(e,t,r)=>{switch(e){case"var":return Fs(t,r);case"add":{let[n,o]=ue(e,t,r,2);return n+o}case"sub":{let[n,o]=ue(e,t,r,2);return n-o}case"mul":{let[n,o]=ue(e,t,r,2);return n*o}case"div":{let[n,o]=ue(e,t,r,2);return n/o}case"mod":{let[n,o]=ue(e,t,r,2);return n%o}case"neg":{let[n]=ue(e,t,r,1);return-n}case"round":{let[n]=ue(e,t,r,1);return Math.round(n)}case"floor":{let[n]=ue(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=ue(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=ue(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=ue(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=ue(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=me(e,t,r,2);return n==o}case"neq":{let[n,o]=me(e,t,r,2);return n!=o}case"gt":{let[n,o]=me(e,t,r,2);return n>o}case"gte":{let[n,o]=me(e,t,r,2);return n>=o}case"lt":{let[n,o]=me(e,t,r,2);return n<o}case"lte":{let[n,o]=me(e,t,r,2);return n<=o}case"in":{let[n,o]=me(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return Xn(e,t),t.every(n=>!!Dt(n,r));case"or":case"any":return Xn(e,t),t.some(n=>!!Dt(n,r));case"not":{let[n]=me(e,t,r,1);return!n}case"length":{let[n]=me(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:ct(n)?Object.keys(n).length:0}case"includes":{let[n,o]=me(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return no(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},Dt=(e,t={})=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let r=Object.entries(e);if(r.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[n,o]]=r;return zs(n,o,t)},Ws=(e,t={})=>lt(e,{variables:t.variables,runtime:t.runtime}),qs=(e,t)=>{if(!ct(e))throw new Error(`${t} must be an object`);let r=de(e,"expr"),n=de(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},xr=(e,t,r)=>(qs(e,t),de(e,"value")?no(e.value):Dt(e.expr,r)),Hs=(e,t={},r="unknown")=>{if(!ct(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=de(e,"expr"),o=de(e,"value");if(de(e,"branches")){if(n||o)throw new Error(`Computed variable "${r}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${r}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${r}" branches must not be empty`);if(!ct(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let c=e.branches[s];if(!ct(c))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!de(c,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(Ws(c.when,t))return xr(c,`Computed variable "${r}" branch ${s}`,t)}return xr(e.default,`Computed variable "${r}" default`,t)}if(n===o)throw new Error(`Computed variable "${r}" must contain exactly one of expr, value, or branches`);return xr(e,`Computed variable "${r}"`,t)},Ys=(e,t,r)=>{switch(t){case"number":if(typeof r!="number"||!Number.isFinite(r))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(r)?"array":typeof r}`);return;case"boolean":if(typeof r!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(r)?"array":typeof r}`);return;case"string":if(typeof r!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(r)?"array":typeof r}`);return;case"object":if(r===null||typeof r!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof r}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},ut=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=Xe(e,r),i=Object.entries(r).filter(([,u])=>Le(u)).map(([u])=>u),s={},c=[],a=u=>{if(de(s,u))return s[u];let f=r[u];if(!Le(f))return o[u];let p=c.indexOf(u);if(p>=0){let h=[...c.slice(p),u].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}c.push(u);try{let h=Hs(f.computed,d,u);return Ys(u,f.type,h),s[u]=h,h}finally{c.pop()}},l=new Proxy({},{get:(u,f)=>{if(typeof f=="string")return a(f)},has:(u,f)=>typeof f=="string"&&(de(o,f)||i.includes(f)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(u,f)=>{if(!(typeof f!="string"||!de(o,f)&&!i.includes(f)))return{enumerable:!0,configurable:!0}}}),d={variables:l,runtime:t,resolveVariable:a};return n?(i.forEach(u=>{a(u)}),{...o,...s}):l},Ks=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>ut({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),Vt=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(Le(o))return;let i=Vs(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},jt=(e,t)=>{let r=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!r.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${r.join(", ")}`)},Mt=(e,t,r)=>{let n={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=n[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${r}`);if(!Object.values(n).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${r}" of type "${e}". Valid operations: ${o.join(", ")}`)},Gs=2,Qn=12,oo=(e=Gs)=>{if(!Number.isInteger(e)||e<0||e>Qn)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${Qn}.`);return e},Js=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},Tt=e=>typeof e=="number"&&Number.isFinite(e),_r=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!Tt(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!Tt(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!Tt(r))throw new Error(`Operation "divide" requires value to be a number for variable "${n}".`);if(t==="divide"){if(r===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${n}".`);oo(o.roundTo)}}},Ft=(e,t,r,n={})=>{let o=(s,c,a)=>{let l=s??c;if(!Tt(l))throw new Error(`Operation "${t}" requires ${a} to be a number.`);return l},i=s=>{let c=o(s,void 0,"value");if(c===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return c};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return Js(o(e,0,"current value")/i(r),oo(n.roundTo));case"increment":return o(e,0,"current value")+o(r,1,"value");case"decrement":return o(e,0,"current value")-o(r,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var io=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let r=new Date(e),n=o=>String(o).padStart(2,"0");return t.replace("DD",n(r.getDate())).replace("MM",n(r.getMonth()+1)).replace("YYYY",r.getFullYear()).replace("YY",String(r.getFullYear()).slice(-2)).replace("HH",n(r.getHours())).replace("mm",n(r.getMinutes())).replace("ss",n(r.getSeconds()))},Xs=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let c=i.character?.sprite;return c&&Object.keys(c).length>0&&(s.sprite=c),Object.keys(s).length>0?s:void 0},n=r(e),o=r(t);return JSON.stringify(n)===JSON.stringify(o)?null:n&&!o?{changeType:"delete",data:e}:o&&!n?{changeType:"add",data:t}:o&&n?{changeType:"update",data:t}:null},Zn=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};e.transformId!==void 0&&(t.transformId=e.transformId);for(let r of["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"])e[r]!==void 0&&(t[r]=e[r]);return e.loop!==void 0&&(t.loop=e.loop),t},eo=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},to=(e,t)=>t&&!e?{changeType:"add",data:t}:e&&!t?{changeType:"delete",data:e}:e&&t&&JSON.stringify(e)!==JSON.stringify(t)?{changeType:"update",data:t}:null,Qs=(e,t)=>{let r={},n=to(Zn(e),Zn(t)),o=to(eo(e),eo(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},Rr=(e={},t={})=>{let r={},n=["sfx","voice"],o=c=>{let a=e[c],l=t[c];l&&!a?r[c]={changeType:"add",data:l}:a&&!l?n.includes(c)||(r[c]={changeType:"delete",data:a}):a&&l&&JSON.stringify(a)!==JSON.stringify(l)&&(r[c]={changeType:"update",data:l})},i=Qs(e.background,t.background);i&&(r.background=i),o("screen"),o("bgm"),o("voice");let s=Xs(e.dialogue,t.dialogue);return s&&(r.dialogue=s),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),r},Or=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,!t.background.resourceId&&!t.background.colorId&&delete t.background);let r=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};r("layout"),r("choice"),r("form"),r("screen"),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),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let n=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(c=>{let a={...c};return delete a.animations,i(a)?a:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return n("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),n("visual",o=>o.resourceId||o.transformId),t},Zs=(e,t)=>{if(!e||!t)return;let r=e;for(let n of t.split(".")){if(r==null||!(n in Object(r)))return;r=r[n]}return r},ea=(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 r=e.slice(7),n=Zs(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},ta={conditional:new Set(["branches"]),updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"]),form:new Set(["submitActions","cancelActions"]),submitForm:new Set(["actions"]),cancelForm:new Set(["actions"])},so=(e,t)=>{let r=e[e.length-1];return r?ta[r]?.has(t)===!0:!1},Cr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Cr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,so(r,n)?o:Cr(o,t,[...r,n])])):ea(e,t),Sr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Sr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,so(r,n)?o:Sr(o,t,[...r,n])])):typeof e=="string"?ie(e,t):e,Lr=(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 r=Cr(e,t._event);return Sr(r,t)};var Q=e=>structuredClone(ae(e)?Ne(e):e),W=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),ao=e=>e?.animations?.playback?.continuity==="persistent",N=(e,t)=>W(e??{},t)&&e[t]!==void 0,dt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:Q(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},ra=e=>N(e,"opacity")||N(e,"blur"),uo=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],fo=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],na=e=>uo.some(t=>N(e,t)),po=e=>e?.text&&N(e.text,"content")&&N(e.text,"textStyleId"),ho=e=>N(e,"text"),oa=(e,t)=>e.resourceId?!0:po(e)?!t?.text:!1,ia=(e,t)=>{let r={...Q(e),...t};return t.text&&e.text&&(r.text={...Q(e.text),...Q(t.text)}),r},sa=(e,t)=>{if(ho(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!po(e)&&!t?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},co=e=>fo.some(t=>N(e,t)),aa=(e,t,{hasAuthoredTransformId:r=!1}={})=>{if(!t)return e;for(let n of fo)!r&&!N(e,n)&&N(t,n)&&(e[n]=t[n]),W(e,n)&&e[n]===void 0&&delete e[n];return e},mo=(e,t,r)=>{let n=e[r];return n?.id===t?.id?n:e.find(o=>o.id===t?.id)},ca=(e,t)=>{if(!t)return e;for(let r of uo)!N(e,r)&&N(t,r)&&(e[r]=t[r]),W(e,r)&&e[r]===void 0&&delete e[r];return e},la=(e,t)=>(t&&(!N(e,"opacity")&&N(t,"opacity")&&(e.opacity=t.opacity),!N(e,"blur")&&N(t,"blur")&&(e.blur=Q(t.blur)),W(e,"opacity")&&e.opacity===void 0&&delete e.opacity,W(e,"blur")&&e.blur===void 0&&delete e.blur),e),go=(e,t,r=[],{hasPatchFn:n=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,c)=>{let a=mo(r,s,c),l=t(s,a),d=ra(s),u=na(s),f=n(s),p=W(s,"animations"),h=Q(s);return!l&&(d||u||f)&&a&&(h=o?o(a,h):{...Q(a),...h},p||delete h.animations),la(ca(h,a),a)}).filter(s=>t(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},ua=e=>{if(e){if(e.character&&W(e.character,"name"))return e.character.name;if(W(e,"characterName"))return e.characterName}},yo=e=>!!e?.character&&W(e.character,"sprite"),da=e=>{let t={},r=!1,n=ua(e);return n!==void 0&&(t.name=n,r=!0),yo(e)&&(t.sprite=Q(e.character.sprite),r=!0),r?t:void 0},lo=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},fa=({dialogueState:e,content:t,append:r=!1})=>{if(!r||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let n=Array.isArray(e.content)?e.content:[];n.length>0?e.initialRevealedContent=n.map(o=>Q(o)):delete e.initialRevealedContent,e.content=[...n,...t]},pa=()=>({}),ha=(e,t)=>{if(!t.screen)return;let r=N(t.screen,"opacity"),n=N(t.screen,"blur"),o=W(t.screen,"animations");if(!r&&!n){o||delete e.screen;return}let i=e.screen,s={};if(r?s.opacity=t.screen.opacity:N(i,"opacity")&&(s.opacity=i.opacity),n?s.blur=Q(t.screen.blur):N(i,"blur")&&(s.blur=Q(i.blur)),W(s,"opacity")&&s.opacity===void 0&&delete s.opacity,W(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},ma=(e,t)=>{if(t.background){let r=N(t.background,"resourceId"),n=N(t.background,"colorId"),o=N(t.background,"opacity"),i=N(t.background,"blur"),s=N(t.background,"transformId"),c=co(t.background),{animationsOnly:a,state:l}=dt(t.background,f=>N(f,"resourceId")||N(f,"colorId")||N(f,"opacity")||N(f,"blur")||N(f,"transformId")||co(f));if(a){e.background=e.background?{...Q(e.background),...l}:l;return}if(!r&&!n&&!o&&!i&&!s&&!c){delete e.background;return}let d=e.background,u=Q(t.background);if(!r&&d?.resourceId&&(u.resourceId=d.resourceId,!W(u,"transformId")&&d.transformId&&(u.transformId=d.transformId)),aa(u,d,{hasAuthoredTransformId:s}),!n&&d?.colorId&&(u.colorId=d.colorId),!o&&N(d,"opacity")&&(u.opacity=d.opacity),!i&&N(d,"blur")&&(u.blur=Q(d.blur)),W(u,"resourceId")&&u.resourceId===void 0&&delete u.resourceId,W(u,"colorId")&&u.colorId===void 0&&delete u.colorId,W(u,"animations")&&u.animations===void 0&&delete u.animations,W(u,"transformId")&&u.transformId===void 0&&delete u.transformId,W(u,"opacity")&&u.opacity===void 0&&delete u.opacity,W(u,"blur")&&u.blur===void 0&&delete u.blur,!u.resourceId&&!u.colorId){delete e.background;return}d?.resourceId===u.resourceId&&d?.transformId===u.transformId&&!W(u,"animations")&&ao(d)&&(u.animations=Q(d.animations)),e.background=u}else e.background?.animations&&!ao(e.background)&&(e.background.animations={})},ga=(e,t)=>{if(!t.dialogue){e.dialogue&&(lo(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let r=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:l,state:d}=dt(t.dialogue.ui,u=>!!u.resourceId);l?e.dialogue.ui={...e.dialogue.ui,...d}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});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");let n=t.dialogue.append===!0&&r!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&fa({dialogueState:e.dialogue,content:t.dialogue.content,append:n});let o=W(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=W(t.dialogue,"characterId"),s=da(t.dialogue),c=s!==void 0,a=yo(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,c?e.dialogue.character=!i&&o&&e.dialogue.character?{...Q(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,a||lo(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let l={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(l.character=Q(e.dialogue.character)),e.dialogue.lines.push(l)}},ya=(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},ba=(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}}},Ia=(e,t)=>{if(t.visual){let r=e.visual?.items||[];t.visual.items?.forEach((i,s)=>{sa(i,mo(r,i,s))});let{hasValidItems:n,processedItems:o}=go(t.visual.items,oa,r,{hasPatchFn:ho,mergeItemFn:ia});n?e.visual={items:o}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(r=>r.animations?{...r,animations:{}}:r))},Aa=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:r,processedItems:n}=go(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);r?e.character={items:n}:delete e.character},wa=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Ea=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=dt(t.layout,o=>!!o.resourceId);if(r){e.layout=n;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},va=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=dt(t.choice,o=>!!o.resourceId);if(r){e.choice={...e.choice,...n};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},xa=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=dt(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=Q(t.form)}else e.form&&delete e.form},Ca=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},Sa=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},_a=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},je=e=>Pt(pa,[_a,ha,ma,ya,ba,Ia,ga,Aa,wa,Ea,va,xa,Ca,Sa])(e);var Ra=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},skipUnseenText:{source:"global.skipUnseenText"},skipTransitionsAndAnimations:{source:"global.skipTransitionsAndAnimations"},soundVolume:{source:"global.soundVolume"},musicVolume:{source:"global.musicVolume"},muteAll:{source:"global.muteAll"},saveLoadPagination:{source:"context.runtime.saveLoadPagination"},menuPage:{source:"context.runtime.menuPage"},menuEntryPoint:{source:"context.runtime.menuEntryPoint"},autoMode:{source:"global.autoMode"},skipMode:{source:"global.skipMode"},dialogueUIHidden:{source:"global.dialogueUIHidden"},isLineCompleted:{source:"global.isLineCompleted"}}),Me=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),ft=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),bo=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",skipUnseenText:"boolean",skipTransitionsAndAnimations:"boolean",soundVolume:"number",musicVolume:"number",muteAll:"boolean",saveLoadPagination:"number",menuPage:"string",menuEntryPoint:"string",autoMode:"boolean",skipMode:"boolean",dialogueUIHidden:"boolean",isLineCompleted:"boolean"}),$r=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),kr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Oa=(e,t)=>{if(t.startsWith("global.")){let r=t.slice(7);return e?.global?.[r]}if(t.startsWith("context.runtime.")){let r=t.slice(16),n=Array.isArray(e?.contexts)?e.contexts:[];return n[n.length-1]?.runtime?.[r]}},Fe=e=>Object.fromEntries(Object.entries(Ra).map(([t,r])=>{let n=Oa(e,r.source),o=n!==void 0?n:Me[t]??ft[t];return[t,o]})),Ee=(e,t)=>Fe(e)[t],Io=(e={})=>Object.fromEntries($r.map(t=>[t,e[t]??Me[t]]));var Qe=Object.freeze({VISUAL_BEHIND_BACKGROUND:10,BACKGROUND:20,VISUAL_BEHIND_CHARACTER:30,CHARACTER:40,VISUAL_BEHIND_DIALOGUE:50,DIALOGUE:60,VISUAL_BEHIND_CHOICE:70,CHOICE:80,VISUAL_FOREGROUND:90}),ve=Object.freeze({BEHIND_BACKGROUND:Qe.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:Qe.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:Qe.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:Qe.VISUAL_BEHIND_CHOICE,FOREGROUND:Qe.VISUAL_FOREGROUND}),Tr=ve.BEHIND_DIALOGUE,Dr=Object.freeze(Object.values(ve).sort((e,t)=>e-t));var xe={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:io},La=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,$a=(e,t)=>{let r=String(t||"").trim();if(!r)return;let n=r.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of n){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},zt=(e,t,r)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),c=La.exec(s);if(c){let[,a,l,d]=c,u=$a(t,d);if(!Array.isArray(u))continue;let f=Array.isArray(i[s])?i[s]:[];u.forEach((p,h)=>{let g={...t,[a]:p};l&&(g[l]=h),f.forEach(y=>{let b=zt(y,g,r),A=ie(b,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(zt(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=zt(i,t,r)}),n},Xr=({animationType:e,animationId:t,animationPath:r})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${r}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},ka=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);if(Xr({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n!==void 0){let s=Na(n,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},Ta=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Xr({animationType:e.type,animationId:t,animationPath:r}),e.type},Da=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Pa=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Na=(e,t="animation.playback")=>{if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`[${t}] playback must be an object.`);if(e.continuity!==void 0&&e.continuity!=="render"&&e.continuity!=="persistent")throw new Error(`[${t}] playback.continuity must be "render" or "persistent".`);if(e.speed!==void 0&&(typeof e.speed!="number"||!Number.isFinite(e.speed)||e.speed<=0))throw new Error(`[${t}] playback.speed must be a finite number greater than 0.`);let r={};return e.continuity!==void 0&&(r.continuity=e.continuity),e.speed!==void 0&&e.speed!==1&&(r.speed=e.speed),Object.keys(r).length>0?r:void 0},Va=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},Ue=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),To=e=>e?.playback?.continuity==="persistent",Fr=e=>Array.isArray(e)?e.map(Fr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=Fr(e[r]),t),{}),Wt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return t.playback&&(delete t.playback.continuity,t.playback.speed===1&&delete t.playback.speed,Object.keys(t.playback).length===0&&delete t.playback),JSON.stringify(Fr(t))},Do=(e=[])=>e.filter(t=>To(t)).map(t=>structuredClone(t)),Po=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,r)=>{let n=typeof r?.duration=="number"&&Number.isFinite(r.duration)?r.duration:0;return t+n},0):0,Pr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,Po(r)),0),No=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(Pr(e.tween),Pr(e.prev?.tween),Pr(e.next?.tween),Po(e.mask?.progress))/Va(e),Ao=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let r=new Set(t.map(Wt).filter(Boolean));return e.some(n=>{if(!To(n))return!1;let o=Wt(n);return o?r.has(o):!1})},ge=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||Ao({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:Ao({animationInstances:e,activePersistentAnimations:o}),ja=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Ma=(e,t)=>{if(ja(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},Fa=({resources:e,animationId:t,playback:r,instanceId:n,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?ka({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},Ua=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Xr({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},Qr=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(Ua(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Ur=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=ie(e,t);return r&&typeof r=="object"?e:r},Br=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(r=>r===null||typeof r!="object"||Array.isArray(r)))throw new Error(`${t} must be an array of objects`);return e},Ba=({content:e,path:t,variables:r})=>Br(e,t).reduce((n,o)=>{let i=Ur(o.text,{variables:r});return n+`${i??""}`.length},0),wo=(e=[])=>{let t=new Map;for(let r of e)r?.id&&t.set(r.id,(t.get(r.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,r])=>r>1).map(([r])=>r))},Ut=(e,t=0,r=new Set)=>{if(!r.has(e?.id))return`character-container-${e.id}`;let n=e?.sprites?.map(({resourceId:o})=>o)||[];return n.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${n.join("-")}`},Bt=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return r},za=(e,t={})=>{if(!t?.transformId)return;let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for background`);return r},Wa=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],qa=(e={})=>Wa.some(t=>Ue(e,t)),Ha=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},zr=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Ya=(e={})=>e.textStyles||{},Ka=(e={})=>e.images||{},Ga=.5,Ja=(e={},t,r)=>{if(t){if(!e.animations?.[t])throw new Error(`Animation '${t}' not found in spritesheet resource '${r}'`);return t}return Object.keys(e.animations??{})[0]},Xa=({id:e,resourceId:t,spritesheet:r,animationName:n,animationSpeed:o,loop:i,transform:s={}}={})=>{let c=Ja(r,n,t),a=c?r.animations?.[c]:void 0;if(!a){console.warn(`Spritesheet animation not found: ${t}`);return}return{id:e,type:"spritesheet-animation",...s,width:r.width,height:r.height,src:r.fileId,atlas:r.jsonData,playback:{frames:a.frames,animationSpeed:o??a.animationSpeed??Ga,loop:i??a.loop??!0}}},Vo=({id:e,item:t,resources:r={}}={})=>{let n=r.images?.[t.resourceId];if(n)return{type:"sprite",id:e,src:n.fileId,width:n.width,height:n.height,x:0,y:0};let o=r.spritesheets?.[t.resourceId];if(o)return Xa({id:e,resourceId:t.resourceId,spritesheet:o,animationName:t.animationName,animationSpeed:t.animationSpeed,loop:t.loop,transform:{x:0,y:0}});console.warn(`Character sprite resource not found: ${t.resourceId}`)},Qa=(e={})=>e.colors||{},Za=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,ht=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,et=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},Eo=(e,t,r)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);return e},Zr=(e,t)=>{if(typeof e!="string"||!Za.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(r=>r.repeat(2)).join("")}`:e},vo=(e,t,r)=>{let n=Zr(e,r);if(t===1)return n;let o=Number.parseInt(n.slice(1,3),16),i=Number.parseInt(n.slice(3,5),16),s=Number.parseInt(n.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},ec=(e={},t)=>{let r=Ya(e)?.[t];if(!r)throw new Error(`Text style "${t}" not found`);let n=e.fonts?.[r.fontId];if(!n)throw new Error(`Font "${r.fontId}" not found for text style "${t}"`);let o=e.colors?.[r.colorId];if(!o)throw new Error(`Color "${r.colorId}" not found for text style "${t}"`);let i=Eo(r.colorAlpha,"colorAlpha",t),s={fontFamily:n.fileId,fontSize:r.fontSize??16,fontWeight:r.fontWeight??"400",fontStyle:r.fontStyle??"normal",lineHeight:r.lineHeight??1.2,fill:vo(o.hex,i,`Color "${r.colorId}" for text style "${t}"`)};if(r.align!==void 0&&(s.align=r.align),r.wordWrap!==void 0&&(s.wordWrap=r.wordWrap),r.breakWords!==void 0&&(s.breakWords=r.breakWords),r.wordWrapWidth!==void 0&&(s.wordWrapWidth=r.wordWrapWidth),r.strokeColorId){let c=e.colors?.[r.strokeColorId];if(!c)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let a=Eo(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=vo(c.hex,a,`Stroke color "${r.strokeColorId}" for text style "${t}"`)}else if(r.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return r.strokeWidth!==void 0&&(s.strokeWidth=r.strokeWidth),s},Wr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Wr(o,t,`${r}[${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 "${r}". Use textStyleId instead`);let n={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(n[o]=Wr(i,t,ht(r,o)));return e.textStyleId!==void 0&&(et(e.textStyleId,r,"textStyleId"),n.textStyle=ec(t,e.textStyleId)),n},en=(e={},t)=>{let r=Qa(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return Zr(r.hex,`Color "${t}"`)},jo=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Nr=(e,t,r)=>{let n=e?.[t];if(!(!n||typeof n!="object"||Array.isArray(n))&&Object.prototype.hasOwnProperty.call(n,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${r}". Use ${jo(`${t}.fill`)} instead`)},tc=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>mt(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;let n={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(n[o]=mt(i,t,ht(r,o)));return e.colorId!==void 0&&(et(e.colorId,r,"colorId"),n.fill=en(t,e.colorId)),n},mt=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>mt(o,t,`${r}[${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 "${r}". Use ${jo("fill")} instead`);Nr(e,"hover",r),Nr(e,"click",r),Nr(e,"rightClick",r)}let n={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){n[o]=tc(i,t,ht(r,o));continue}n[o]=mt(i,t,ht(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(et(e.colorId,r,"colorId"),n.fill=en(t,e.colorId)),n},Vr=(e={},t)=>{let r=Ka(e)?.[t];return r||null},Mo=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",xo=(e,t,r,n)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,n))throw new Error(`Inline ${t}.${n} is not allowed in sprite layout elements at "${r}". Use ${Mo(`${t}.${n}`)} instead`)},Co=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},qr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>qr(o,t,`${r}[${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 "${r}". Use ${Mo(o)} instead`);xo(e,"hover",r,"src"),xo(e,"click",r,"src")}let n={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(n[o]=qr(i,t,ht(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){et(e.imageId,r,"imageId");let o=Vr(t,e.imageId),i=o?.fileId??e.imageId;n.src=i,n.width===void 0&&o?.width!==void 0&&(n.width=o.width),n.height===void 0&&o?.height!==void 0&&(n.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(et(e.hoverImageId,r,"hoverImageId"),Co(n,"hover",Vr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(et(e.clickImageId,r,"clickImageId"),Co(n,"click",Vr(t,e.clickImageId)?.fileId??e.clickImageId)),n},tn=(e,t={},r="root")=>qr(mt(Wr(e,t,r),t,r),t,r),Ce=tn,Be=(e=[])=>e.find(t=>t.id==="story"),rc="#000000",Hr="bg-cg-background-color",nc=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?Zr(r?.backgroundColor??rc,"screen.backgroundColor"):en(e,t.colorId),Fo=(e={})=>{if(Ue(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},oc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},So=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=Fo(e),n=oc(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},ic=(e={})=>{if(Ue(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},sc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Uo=(e={})=>{let t=ic(e),r=sc(e),n={};return t!==void 0&&(n.alpha=t),r&&(n.blur=r),n},pt=(e={})=>Uo(e),$e=(e={},t={})=>{let r={x:t.x??e.x,y:t.y??e.y,anchorX:t.anchorX??e.anchorX,anchorY:t.anchorY??e.anchorY,rotation:t.rotation??e.rotation,scaleX:t.scaleX??e.scaleX,scaleY:t.scaleY??e.scaleY},n=t.originX??e.originX,o=t.originY??e.originY;return n!==void 0&&(r.originX=n),o!==void 0&&(r.originY=o),r},ac=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],rn=(e={})=>e.text&&Ue(e.text,"content")&&Ue(e.text,"textStyleId"),_o=(e={})=>{if(e.resourceId)return e.resourceId;if(rn(e))return"text"},cc=e=>{if(e.text){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!rn(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let t of ac)if(Ue(e.text,t))throw new Error(`Visual item "${e.id}" text.${t} is reserved for the visual item`)}},lc=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:Hr,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:nc({resources:e,background:t,screen:r})};if(n){let i=Fo(t);i!==void 0&&(o.alpha=i)}return o},uc=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.layouts?.[t]):!1,Ro=({resources:e={},resourceId:t,colorId:r})=>{let n=Ha(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:zr({resourceId:t,kind:n})}:r!==void 0?{resourceId:Hr,targetId:Hr}:{resourceId:void 0,targetId:void 0}},Bo=100,Ht=Bo,zo=(e,t)=>e*t/Bo,dc=(e={},t=Ht)=>e?.muteAll?0:zo(t,e?.soundVolume??Me.soundVolume),fc=(e={},t=Ht)=>e?.muteAll?0:zo(t,e?.musicVolume??Me.musicVolume),pc=({item:e,index:t}={})=>`sfx:${t}:${e?.resourceId}`,ye=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,confirmDialog:u,form:f,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:b}={})=>{let A={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??c??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},v=bc({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e}),_={variables:e,runtime:A,saveSlots:r,isChoiceVisible:a,isFormVisible:l,canRollback:d,confirmDialog:u,form:f,historyDialogue:p,characters:h};return v&&(_.dialogue=v,_.dialogueLines=v.lines),_},Oo=100,qt=(e,t)=>{if(Array.isArray(e))return e.map(n=>qt(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=qt(r[n],t)}),r.type==="text-revealing"?t(r):r},hc=e=>qt(e,t=>({...t,revealEffect:"none"})),mc=e=>qt(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,Oo):Oo;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),ke=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?hc(e):r?mc(e):e,Wo=({id:e,screen:t={width:1920,height:1080}})=>({id:e,type:"rect",fill:"transparent",width:t.width,height:t.height,x:0,y:0,click:{payload:{actions:{}}}}),Yr=e=>{if(Array.isArray(e))return e.map(Yr);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Yr(s);let r=t.click?.payload;if(!r||typeof r!="object"||Array.isArray(r))return t;let n=r.actions,o=n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"nextLine")?{...n.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...r,bypassChoice:!0,...o?{actions:{...n,nextLine:o}}:{}}}}},gc=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),Lo="submit",jr=(e,t,r={})=>{let n=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},o=n.actions&&typeof n.actions=="object"?n.actions:{},i=r.replaceActions===!0?t:{...o,...t};return{...e||{},payload:{...n,actions:i}}},Kr=(e,t,r={})=>{if(Array.isArray(e))return e.map(l=>Kr(l,t,r));if(!e||typeof e!="object")return e;let n=typeof e.type=="string",o=n&&e.formRole===Lo,i=n&&r.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},c={};for(let[l,d]of Object.entries(e))c[l]=Kr(d,t,l==="children"?s:{});let a=c;if(a.type==="input"&&typeof a.field=="string"){let l=t?.fields?.[a.field];if(l){let d={updateFormField:{formKey:t.key,field:l.id,value:"_event.value"}};a={...a,value:l.value,placeholder:a.placeholder===void 0?l.placeholder:a.placeholder,multiline:a.multiline===void 0?l.multiline:a.multiline,...a.maxLength===void 0&&l.maxLength!==void 0?{maxLength:l.maxLength}:{},change:jr(a.change,d),submit:jr(a.submit,t.submitActions)}}}return a.formRole===Lo||i?{...a,click:jr(a.click,t.submitActions,{replaceActions:!0})}:a},Gr=(e,t)=>{if(Array.isArray(e))return e.map(n=>Gr(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Gr(o,t);for(let n of gc){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form"}})}return r},Jr=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0,s=Nt({characterId:e,character:t,characterName:r,characters:n,variables:o});return{...i||{},...t||{},name:s}},qo=(e=[],t={},r={})=>e.map(n=>{let o=Jr({characterId:n.characterId,character:n.character,characterName:n.characterName,characters:t,variables:r}),i=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(s=>s?.text??"").join(""):"";return{...n,text:i,character:o,characterName:o.name}}),yc=e=>!(!e||e.mode==="adv"&&e.content===void 0),bc=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n}={})=>{if(!t&&!yc(e))return;let o=e.content===void 0?[{text:""}]:Br(e.content,"dialogue.content"),i=e.content===void 0?0:Ba({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),s=(e.lines||[]).map((a,l)=>{let d=Br(a.content,`dialogue.lines[${l}].content`),u=Jr({characterId:a.characterId,character:a.character,characterName:a.characterName,characters:r,variables:n});return{...a,content:d.map(f=>({...f,text:Ur(f.text,{variables:n})})),character:u,characterName:u.name}}),c=Jr({characterId:e.characterId,character:e.character,characters:r,variables:n});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:c,content:o.map(a=>({...a,text:Ur(a.text,{variables:n})})),initialRevealedCharacters:i,lines:s}},Ho=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=ie(e,r,{functions:xe});return Ce(ke(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},Mr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),$o=({renderStateKeyboard:e,keyboard:t,phase:r})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([n,o])=>{let i=e[n]??{},s=r==="keydown"?o?.keydown:o?.keyup;if(r==="keydown"&&s&&typeof s=="object"){e[n]={...i,keydown:{payload:Mr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:Mr(o.keyup)});return}e[n]={...i,[r]:{payload:Mr(o)}}})},Ic=(e={},t={})=>{let r={};return $o({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),$o({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},Se=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:c})=>{if(!e)return[];let a=[],l=({instanceId:b,targetId:A})=>{let v=Fa({resources:t,animationId:p,playback:h,instanceId:b,targetId:A,animationPath:s});v&&a.push(v)},d=r!=null&&r!==!1,u=n!=null&&n!==!1,f=o&&i&&o===i;Ma(e,s);let p=Da(e),h=Pa(e),g=t?.animations?.[p],y=Ta(g,{animationId:p,animationPath:s});if(y==="update")return u&&i?l({instanceId:`${c}-animation-update`,targetId:i}):d&&o&&l({instanceId:`${c}-animation-update`,targetId:o}),a;if(y==="transition"){let b=`${c}-animation-transition`,A=h?.continuity==="persistent"?b:`${c}-animation-in`;if(d&&u&&f)return l({instanceId:b,targetId:i}),a;d&&l({instanceId:`${c}-animation-out`,targetId:o}),u&&l({instanceId:A,targetId:i})}return a},Ac=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),wc=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:c,variables:a,runtime:l,activePersistentAnimations:d,restoredPersistentAnimations:u,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,saveSlots:A=[]})=>{let{elements:v,animations:_}=e;if(t.background){let P=n===void 0?!0:Ue(n?.background??{},"animations"),k=v.find(x=>x.id==="story");if(!k)return e;let w=za(o,t.background),M=w||qa(t.background),F=r?.background?.resourceId,Z=r?.background?.colorId,V=t.background.resourceId??(t.background.animations?F:void 0),q=t.background.colorId??(t.background.animations?Z:void 0),Y=uc(o,V),te={...t.background,colorId:q};if((q!==void 0||Y)&&k.children.push(lc({resources:o,background:te,screen:i,includeOpacity:!Y})),V){let{images:x={},videos:C={}}=o,R=x[V]||C[V];if(R){let B=C[V]!==void 0,J={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...w},U={id:zr({resourceId:V,kind:B?"video":"sprite"}),type:B?"video":"sprite",src:R.fileId,width:R.width,height:R.height,...So(t.background,{includeDefaultAlpha:!0}),...$e(J,t.background)};B&&(U.loop=t.background.loop??!1,U.volume=R.volume??50),k.children.push(U)}}if(V){let{layouts:x={}}=o,C=x[V];if(C){let R={id:zr({resourceId:V,kind:"container"}),type:"container",children:C.elements,...So(t.background)};M&&Object.assign(R,$e({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...w},t.background));let B=ie(R,ye({variables:a,runtime:l,saveSlots:A,dialogueState:t.dialogue,isLineCompleted:s,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,characters:o.characters||{},skipTransitionsAndAnimations:c}),{functions:xe});k.children.push(Ce(ke(B,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:c}),o))}}let pe=Ro({resources:o,resourceId:F,colorId:Z}),G=Ro({resources:o,resourceId:V,colorId:q}),H=Se({animationsDef:t.background.animations,resources:o,previousResourceId:pe.resourceId,currentResourceId:G.resourceId,previousTargetId:pe.targetId,currentTargetId:G.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});ge({animationInstances:H,isLineCompleted:s,skipTransitionsAndAnimations:c,activePersistentAnimations:d,restoredPersistentAnimations:u,isAuthoredOnCurrentLine:P})&&_.push(...H)}return e},Ec=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:c,animations:a}=e;if(t.character&&n){let l=c.find(h=>h.id==="story");if(!l)return e;let d=t.character.items||[],u=r?.character?.items||[],f=wo(d),p=wo(u);for(let h=0;h<d.length;h++){let g=d[h],{transformId:y,sprites:b}=g,A=u.find(V=>V.id===g.id),v=u.findIndex(V=>V.id===g.id),_=A?.sprites&&A.sprites.length>0,P=b&&b.length>0,k=v>=0?Ut(A,v,p):void 0,w=Se({animationsDef:g.animations,resources:n,previousResourceId:k,currentResourceId:P?Ut(g,h,f):void 0,previousTargetId:k,currentTargetId:P?Ut(g,h,f):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&_&&ge({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...w);continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let M=Ut(g,h,f),F=n.transforms[y];if(!F){console.warn("Transform not found:",y);continue}let Z={type:"container",id:M,...$e(F,g),...pt(g),children:[]};for(let V of b){let q=Vo({id:`${M}-${V.id}`,item:V,resources:n});q&&Z.children.push(q)}l.children.push(Z),ge({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...w)}}return e},Yo=(e,t)=>{if(!Dr.includes(e))throw new Error(`${t} must be one of: ${Dr.join(", ")}.`)},vc=(e,t)=>{let r=!!e.resourceId||rn(e),n=e.layer??(r?void 0:t?.layer)??Tr;return Yo(n,`Visual item "${e.id}" layer`),n},xc=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:c,activePersistentAnimations:a,autoMode:l,skipMode:d,isChoiceVisible:u,isFormVisible:f,canRollback:p,form:h,saveSlots:g=[],visualLayer:y})=>{let{elements:b,animations:A}=e;if(t.visual&&n){let v=b.find(w=>w.id==="story");if(!v)return e;let _=t.visual.items,P=r?.visual?.items||[],k=ye({variables:s,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:l,skipMode:d,isChoiceVisible:u,isFormVisible:f,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i});y!==void 0&&Yo(y,"visualLayer");for(let w of _){let M=P.find(Y=>Y.id===w.id),F=vc(w,M);if(y!==void 0&&F!==y)continue;if(cc(w),w.text){let Y=Bt(n,w),te={...structuredClone(w.text),id:`visual-${w.id}`,type:"text",...$e(Y,w)};Object.assign(te,pt(w)),v.children.push(Ce(ie(te,k,{functions:xe}),n))}if(w.resourceId){let{images:Y={},videos:te={},spritesheets:pe={}}=n,G=pe[w.resourceId];if(G){let H=Bt(n,w),x=w.animationName;if(x){let C=G.animations?.[x];if(!C)throw new Error(`Animation '${x}' not found in spritesheet resource '${w.resourceId}'`);let R=pt(w),B={id:`visual-${w.id}`,type:"spritesheet-animation",...$e(H,w),width:w.width??G.width,height:w.height??G.height,alpha:R.alpha??w.alpha??1,src:G.fileId,atlas:G.jsonData,playback:{frames:C.frames,animationSpeed:w.animationSpeed??C.animationSpeed??.5,loop:w.loop??C.loop??!0}};R.blur&&(B.blur=R.blur),v.children.push(structuredClone(B))}}else{let H=Y[w.resourceId]||te[w.resourceId];if(H){let x=te[w.resourceId]!==void 0,C=Bt(n,w),R={id:`visual-${w.id}`,type:x?"video":"sprite",src:H.fileId,width:H.width,height:H.height,...$e(C,w)};Object.assign(R,pt(w)),x&&(R.loop=H.loop??!1,R.volume=H.volume??50),v.children.push(R)}}}if(w.resourceId){let{layouts:Y={}}=n,te=Y[w.resourceId];if(te){let pe=Bt(n,w),G={id:`visual-${w.id}`,type:"container",children:structuredClone(te.elements),...$e(pe,w)};Object.assign(G,pt(w));let H=ie(G,k,{functions:xe});v.children.push(Ce(ke(H,{isLineCompleted:o,skipMode:d,skipTransitionsAndAnimations:i}),n))}}let Z=_o(M),V=_o(w),q=Se({animationsDef:w.animations,resources:n,previousResourceId:Z,currentResourceId:V,previousTargetId:Z?`visual-${w.id}`:void 0,currentTargetId:V?`visual-${w.id}`:void 0,animationPath:`visual.items[${w.id}].animations`,idPrefix:w.id});ge({animationInstances:q,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:a})&&A.push(...q)}}return e},Ze="dialogue-character-sprite",ko=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,Cc=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=Be(e.elements);if(!a)return e;let l=t.dialogue?.character?.sprite,d=r?.dialogue?.character?.sprite,u=ko(l),f=ko(d),p=Se({animationsDef:l?.animations,resources:n,previousResourceId:f?Ze:void 0,currentResourceId:u?Ze:void 0,previousTargetId:f?Ze:void 0,currentTargetId:u?Ze:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!u)return l?.animations&&f&&ge({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e;let h=n.transforms?.[l.transformId];if(!h)return console.warn("Transform not found:",l.transformId),e;let g={type:"container",id:Ze,...$e(h),children:[]};for(let y of l.items){let b=Vo({id:`${Ze}-${y.id}`,item:y,resources:n});b&&g.children.push(b)}return a.children.push(g),ge({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e},Sc=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:d,skipOnlyViewedLines:u,isLineCompleted:f,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:y,saveSlots:b=[]})=>{let{elements:A,animations:v}=e;if(!t.dialogue||o)return e;let _=A.find(k=>k.id==="story");if(!_)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:k={}}=n,w=k[t.dialogue.ui.resourceId];if(w){let M={elements:w.elements},F=ye({variables:h,runtime:g,saveSlots:b,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:f,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:d,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:u,skipTransitionsAndAnimations:p}),Z={functions:xe},V=zt(M,F,Z),q=ie(V,F,Z),Y=Ce(ke(q?.elements,{isLineCompleted:f,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(Y))for(let te of Y)_.children.push(te);else Y&&_.children.push(Y)}}Cc(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let P=Se({animationsDef:t.dialogue.ui?.animations,resources:n,previousResourceId:r?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:r?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return ge({animationInstances:P,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&v.push(...P),e},_c=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:c,runtime:a,autoMode:l,skipMode:d,isChoiceVisible:u,isFormVisible:f,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:b,animations:A}=e;if(t.choice&&n){let v=Be(b);if(!v)return e;let _=n?.layouts[t.choice.resourceId];if(_&&_.elements){let k={elements:_.elements},w=ie(k,{...ye({variables:c,runtime:a,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:d,isChoiceVisible:u??!!t.choice,isFormVisible:f,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:xe}),M=Yr(Ce(ke(w?.elements,{isLineCompleted:i,skipMode:d,skipTransitionsAndAnimations:s}),n));if(Array.isArray(M))for(let F of M)v.children.push(F);else M&&v.children.push(M)}let P=Se({animationsDef:t.choice.animations,resources:n,previousResourceId:r?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:r?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});ge({animationInstances:P,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&A.push(...P)}return e},Rc=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:c,runtime:a,autoMode:l,skipMode:d,isChoiceVisible:u,isFormVisible:f,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:b,animations:A}=e;if(!y?.resourceId||!n)return e;let v=Be(b);if(!v)return e;let _=n?.layouts?.[y.resourceId];if(!_)return console.warn(`Form layout not found: ${y.resourceId}`),e;let P={id:"form-container",type:"container",x:0,y:0,children:_.elements||[]},k={...ye({variables:c,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:d,isChoiceVisible:u,isFormVisible:f,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},w=ie(P,k,{functions:xe}),M=Gr(Ce(ke(Kr(w,y),{isLineCompleted:i,skipMode:d,skipTransitionsAndAnimations:s}),n),y);M&&v.children.push(M);let F=Se({animationsDef:y.animations,resources:n,previousResourceId:r?.form?.resourceId,currentResourceId:y.resourceId,previousTargetId:r?.form?.resourceId?"form-container":void 0,currentTargetId:y.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return ge({animationInstances:F,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(...F),e},Oc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,form:u,saveSlots:f=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=Ic(h.keyboard,h.keyup);if(g&&Object.keys(g).length>0&&(e.global.keyboard=g),!Array.isArray(h.elements)||h.elements.length===0)return e;let y=Be(e.elements);if(!y)return e;let b={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(Ho({container:b,resources:r,templateData:ye({variables:n,runtime:o,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,form:u,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:c,skipTransitionsAndAnimations:p})),e},Lc=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Be(i))return e;let a=r.sounds[t.bgm.resourceId];if(!a)return e;let l=ye({variables:o,runtime:n}).runtime;s.push({id:"bgm",type:"sound",src:a.fileId,loop:t.bgm.loop??!0,volume:fc(l,t.bgm.volume??a.volume??Ht),startDelayMs:t.bgm.startDelayMs??null})}return e},$c=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx.items;for(let[s,c]of i.entries()){let a=r.sounds?.[c.resourceId];a&&o.push({id:pc({item:c,index:s}),type:"sound",src:a.fileId,loop:c.loop??a.loop??!1,volume:dc(n,c.volume??a.volume??Ht),startDelayMs:c.startDelayMs??a.startDelayMs??null})}}return e},kc=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},Tc=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,Dc=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let c=t.voice,{resourceId:a,loop:l,startDelayMs:d}=c,u=kc(r,n,a);if(!u)return e;let f=ye({variables:i,runtime:o}).runtime;return s.push({id:`voice-${n}-${a}`,type:"sound",src:u.fileId,volume:Tc(c,f),loop:l??!1,startDelayMs:d??null}),e},Pc=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,form:u,saveSlots:f=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:b}=e;if(t.layout){let P=Be(y);if(!P)return e;let k=n.layouts[t.layout.resourceId];if(!k)return e;Array.isArray(k.transitions)&&!p&&!h&&Qr({animations:b,transitions:k.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let w={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:k.elements||[]};P.children.push(Ho({container:w,resources:n,templateData:ye({variables:o,runtime:i,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,form:u,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:c,skipTransitionsAndAnimations:h}))}let A=r?.layout?.resourceId,v=t.layout?.resourceId,_=Se({animationsDef:t.layout?.animations,resources:n,previousResourceId:A,currentResourceId:v,previousTargetId:A?`layout-${A}`:void 0,currentTargetId:v?`layout-${v}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return ge({animationInstances:_,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(..._),e},Nc=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=t?.screen?.animations;if(!a)return e;let l=r!=null,d=Se({animationsDef:a,resources:n,previousResourceId:l?"story":void 0,currentResourceId:"story",previousTargetId:l?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return ge({animationInstances:d,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...d),e},Vc=(e,{presentationState:t})=>{let r=Be(e.elements);return!r||!t?.screen||Object.assign(r,Uo(t.screen)),e},jc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:d,overlayStack:u=[],dialogueHistory:f=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;return u&&u.length>0&&u.forEach((v,_)=>{let P=r.layouts[v.resourceId];if(!P){console.warn(`Overlay layout not found: ${v.resourceId}`);return}Array.isArray(P.transitions)&&(y||Qr({animations:A,transitions:P.transitions,defaultTargetId:`overlayStack-${_}`,idPrefix:`overlayStack-${_}`,animationPathPrefix:`overlayStack[${_}]`}));let k={id:`overlayStack-${_}`,type:"container",x:0,y:0,children:[Wo({id:`overlayStack-${_}-blocker`,screen:h}),...P.elements||[]]},w=qo(f,r.characters,n),M=ye({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:d,historyDialogue:w,characters:r.characters||{},skipTransitionsAndAnimations:y}),F=ie(k,M,{functions:xe}),[Z,...V]=F.children||[],q=Ce(ke({...F,children:V},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...q,children:Z?[Z,...q.children||[]]:q.children})}),e},Mc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,form:u,confirmDialog:f,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;if(!f?.resourceId)return e;let v=r.layouts?.[f.resourceId];if(!v)return console.warn(`ConfirmDialog layout not found: ${f.resourceId}`),e;Array.isArray(v.transitions)&&!y&&Qr({animations:A,transitions:v.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let _={id:"confirmDialog",type:"container",x:0,y:0,children:[Wo({id:"confirmDialog-blocker",screen:h}),...v.elements||[]]},P=qo(p,r.characters,n),k=ie(_,ye({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,form:u,confirmDialog:f,historyDialogue:P,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:xe}),[w,...M]=k.children||[],F=Ce(ke({...k,children:M},{isLineCompleted:g,skipMode:c,skipTransitionsAndAnimations:y}),r);return b.push({...F,children:w?[w,...F.children||[]]:F.children}),e},gt=e=>(t,r)=>xc(t,{...r,visualLayer:e}),Fc=gt(ve.BEHIND_BACKGROUND),Uc=gt(ve.BEHIND_CHARACTER),Bc=gt(ve.BEHIND_DIALOGUE),zc=gt(ve.BEHIND_CHOICE),Wc=gt(ve.FOREGROUND),Ko=e=>Pt(Ac,[Oc,Fc,wc,Uc,Ec,Bc,Sc,zc,_c,Rc,Pc,Wc,Vc,Nc,Lc,$c,Dc,jc,Mc])(e);var Yt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Zo=1,nn="choice",Kt="form",Xt=()=>({manual:{...Yt.manual},auto:{...Yt.auto},applyMode:Yt.applyMode}),on=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...Xt()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},D=e=>{let t=ae(e)?Ne(e):e;return structuredClone(t)},T=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Qt=e=>String(e),ei=()=>({sections:[],resources:[]}),qc=e=>T(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):ei(),Hc=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Yc=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:Hc(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),Kc=()=>({resourceId:void 0}),Gc=e=>{if(!T(e))return e;let t={...e};return Object.prototype.hasOwnProperty.call(t,"requireComplete")&&!Object.prototype.hasOwnProperty.call(t,"requireLineCompleted")&&(t.requireLineCompleted=t.requireComplete),delete t.requireComplete,t},sn=(e,t)=>{let r=e?.story?.scenes??{};for(let[n,o]of Object.entries(r))if(o?.sections?.[t])return{sceneId:n,section:o.sections[t]};return{sceneId:void 0,section:void 0}},ti=e=>{let t=e?.story?.scenes??{},r=new Map;for(let[n,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let c=r.get(s);if(c!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${c}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},ri=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},ni=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Zo)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Jc=(e,t={})=>{let r;try{r=ni(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:ri(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},Xc=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Jc(t,r)])),oi=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Bu(r));return t.length>0?t:void 0},Qc=e=>{!T(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!T(t))return;let r=oi(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},Go=(e,t,r,n="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!T(e))throw new Error(`Malformed ${n}.${t}[${r}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${n}.${t}[${r}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${n}.sections[${r}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},Zc=(e,t="viewedRegistry")=>{if(e===void 0)return ei();if(!T(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let r=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Go(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Go(o,"resources",i,t);return[s.resourceId,s]})))}},ii=(e,t,r)=>{if(!T(e))throw new Error(`Malformed save slot ${r}.`);let{sectionId:n,lineId:o}=e;if(typeof n!="string"||n.length===0)throw new Error(`Malformed save slot ${r}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${r}: missing lineId.`);let{sceneId:i,section:s}=sn(t,n);if(!s)throw new Error(`Malformed save slot ${r}: section "${n}" does not exist in projectData.`);if(!s.lines?.some(a=>a.id===o))throw new Error(`Malformed save slot ${r}: line "${o}" does not exist in section "${n}".`);return{sceneId:i,sectionId:n,lineId:o}},el=(e,t,r)=>{if(!T(e)||!Array.isArray(e.timeline))return yt({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((c,a)=>{if(!T(c))return[];try{let l=ii(c,r,`rollback.timeline[${a}]`),d=Jt({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:c.rollbackPolicy}),u=oi(D(c.executedActions));return u&&(d.executedActions=u),[d]}catch{return[]}});if(n.length===0)return yt({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):n.length-1;(o<0||o>=n.length)&&(o=n.length-1);let i=n[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let c=n.findLastIndex(a=>a.sectionId===t.sectionId&&a.lineId===t.lineId);c>=0?o=c:(n.push(Jt({sectionId:t.sectionId,lineId:t.lineId})),o=n.length-1)}let s=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),o):0;return{currentIndex:o,isRestoring:!1,replayStartIndex:s,timeline:n}},tl=(e,t,r)=>{if(!T(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=ln(t),o=ii(e.pointers?.read,t,`contexts[${r}].pointers.read`);if(e.variables!==void 0&&!T(e.variables))throw new Error(`Malformed save slot contexts[${r}].variables entry.`);if(e.runtime!==void 0&&!T(e.runtime))throw new Error(`Malformed save slot contexts[${r}].runtime entry.`);let i=e.variables?Xe(D(e.variables),t.resources?.variables??{}):{},s=hl({loadedContextRuntime:T(e.runtime)?D(e.runtime):{}}),c={currentPointerMode:"read",pointers:{read:o},configuration:T(e.configuration)?D(e.configuration):{},views:Array.isArray(e.views)?D(e.views):[],bgm:T(e.bgm)?D(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:el(e.rollback,o,t)};return s&&(c.runtime=s),c},rl=(e,t)=>{if(!T(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((r,n)=>tl(r,t,n))}},nl=(e,t)=>{if(!T(e))throw new Error("Malformed save slot.");let r=ni(e.formatVersion);return{...e,formatVersion:r,state:rl(e.state,t)}},Jo=(e,t,{required:r=!1}={})=>{if(e===void 0){if(r)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let n=D(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},ol=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Jo(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Jo(e.cancelActions,"cancelActions")}},tt=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},il=e=>(T(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),rt=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},si=e=>{if(!(!T(e)||!e.animations))return{animations:D(e.animations)}},sl=(e,t)=>{let r=si(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},al=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},cl=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},Gt=e=>String(e??""),ai=(e,t)=>{let r=Gt(t);return e?.trim===!0?r.trim():r},ll=e=>T(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>T(t)).map(([t,r])=>[t,{id:t,...D(r)}])):{},ul=(e,t)=>{if(!t||!T(e.global.formDrafts))return;let r=e.global.formDrafts[t];return T(r)?r:void 0},ci=(e,t)=>{let r=il(e);T(r[t])||(r[t]={values:{},touched:{},errors:{},submitted:!1});let n=r[t];return T(n.values)||(n.values={}),T(n.touched)||(n.touched={}),T(n.errors)||(n.errors={}),typeof n.submitted!="boolean"&&(n.submitted=!1),n},an=(e,t)=>{let r=ai(e,t);return e?.required===!0&&r.length===0?"required":null},dl=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=ne({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:je(n.slice(0,o+1).map(i=>i.actions||{}))},fl=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=al(t),o=cl(r,n);if(!n||!o)return null;let i=ul(e,o),s=ll(t),c=pn({state:e}),a={},l=[],d={},u=!0;return Object.entries(s).forEach(([f,p])=>{let h=Gt(c?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},f)?Gt(i.values[f]):h,y=i?.touched?.[f]===!0,b=an(p,g),A=i?.submitted||y?b:null,v=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,_={id:f,variableId:p.variableId,value:g,initialValue:h,valid:!b,error:A,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...v!==void 0?{maxLength:v}:{}};b&&(u=!1),a[f]=_,l.push(_),d[f]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:u,submitted:i?.submitted===!0,fields:a,fieldList:l,values:d,submitActions:{submitForm:{formKey:o,actions:D(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:D(t.cancelActions??{})}}}},ze=[],Xo="line",cn="interaction",Jt=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),ln=e=>{let{contextVariableDefaultValues:t}=Vt(e??{});return D(t)},li=()=>({...D(ft)}),ui=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:D(r),hasLoadedValues:!1};if(!T(e))throw new Error(`Malformed ${n}.`);let o=D(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=di(s,D(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},pl=({loadedGlobalRuntime:e={}})=>ui({loadedRuntime:e,runtimeIds:$r,defaults:Me,path:"global.runtime"}).runtimeState,hl=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=ui({loadedRuntime:e,runtimeIds:kr,defaults:li(),path:"context.runtime"});return r?t:void 0},Zt=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},ml=e=>e.runtime?(kr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=D(ft[t]))}),e.runtime):(e.runtime=li(),e.runtime),gl=e=>Io(e.global),yl=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:gl(e)}})},bl=e=>bo[e],Il=(e,t)=>{let r=bl(e);if(r==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(r==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(r==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},di=(e,t)=>(Il(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),fi=(e,t,r)=>{let n=di(t,r);if(t in ft){let o=Zt(e);if(!o)return n;let i=ml(o);return i[t]=n,n}return e.global[t]=n,n},pi=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:D(e)},configuration:{},views:[],bgm:Kc(),variables:ln(t),rollback:yt({pointer:e})}),nt=e=>e?(e.currentPointerMode="read",T(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Al=(e,{queueRender:t=!0}={})=>{let r=e.contexts?.[e.contexts.length-1],n=r?.pointers?.read;if(!r||!n?.sectionId||!n?.lineId)return null;let o=pi({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,wl(e,{queueRender:t}),o},wl=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,tt(e),rt(e),e.global.nextLineConfig=Xt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},hi=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},yt=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[Jt({sectionId:e.sectionId,lineId:e.lineId})]:[]}},He=(e,t={})=>{if(e?.rollback)return hi(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let r=e?.pointers?.read;return e.rollback=yt({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},un=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=He(r);if(n.isRestoring)return;n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1));let o=n.timeline[n.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){n.currentIndex=n.timeline.length-1;return}n.timeline.push(Jt(t)),n.currentIndex=n.timeline.length-1},El=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;if(!r||r.isRestoring||!Array.isArray(r.timeline)||typeof r.currentIndex!="number")return null;let n=ze[ze.length-1],o=typeof n?.checkpointIndex=="number"?n.checkpointIndex:r.currentIndex;return o<0||o>=r.timeline.length?null:(typeof n?.checkpointIndex!="number"&&o<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,o+1)),r.timeline[o]??null)},vl=({state:e},t={})=>{let r=t?.source===Xo?Xo:cn,o=e.contexts?.[e.contexts.length-1]?.rollback;return!o||o.isRestoring||!Array.isArray(o.timeline)||typeof o.currentIndex!="number"||o.currentIndex<0||o.currentIndex>=o.timeline.length?(ze.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),ze.push({checkpointIndex:o.currentIndex,source:r}),e)},xl=({state:e})=>(ze.pop(),e),Ae=(e,t,r)=>{let o=ze[ze.length-1]?.source??cn;if(!zu(t,o))return;let i=El(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:D(r)}))},Qo=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:c}of n){let a=e.projectData.resources?.variables?.[o],l=a?.scope,d=a?.type;if(Le(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);jt(l,o),Mt(d,i,o),_r(d,i,s,o,{roundTo:c}),l==="context"&&(r.variables[o]=Ft(r.variables[o],i,s,{roundTo:c}))}},Cl=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{Wu(e,r,n)})},Sl=(e,t)=>{let{sectionId:r,lineId:n}=t,s=ne({state:e},{sectionId:r})?.lines?.find(c=>c.id===n)?.actions;s&&Object.entries(s).forEach(([c,a])=>{$i(e,c,a)})},mi=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=He(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&It({state:e}),e.global.skipMode&&We({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=ln(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=D(Yt),e.global.overlayStack=[],tt(e),rt(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let c=i;c<=t;c++)c>i&&on(e),Sl(e,n.timeline[c]),Cl(e,n.timeline[c]);let s=nt(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(c=>c?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},_l=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;ti(t);let c=t.story.initialSceneId,a=t.story.scenes[c],l=a.initialSectionId,d=a.sections[l],u={sceneId:c,sectionId:l,lineId:d.initialLineId??d.lines[0].id},{globalVariablesDefaultValues:f}=Vt(t),p={...f,...Xe(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:Zc(s,"accountViewedRegistry"),nextLineConfig:Xt(),saveSlots:Xc(n),overlayStack:[],variables:p,...pl({loadedGlobalRuntime:i})},contexts:[pi({pointer:u,projectData:t})]}},Rl=({state:e})=>e.global.overlayStack||[],Ol=({state:e})=>e.global.pendingEffects,gi=({state:e})=>e.global.skipMode,Ll=({state:e})=>e.global.autoMode,yi=({state:e})=>e.global.dialogueUIHidden,bi=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(!r)return[];let{sectionId:n,lineId:o}=r.pointers.read,i=ne({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),c=i.lines.slice(0,s+1),a=[],l={},d=ut({variables:{...e.global?.variables??{},...Zt(e)?.variables??{}},runtime:Fe(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let u of c){let f=u.actions||{};if(l=je([l,f]),!f.dialogue)continue;let p=l.dialogue||{},h=Nt({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:d}),g=Yc({sectionId:n,lineId:u.id,content:f.dialogue.append===!0?p.content:f.dialogue.content,dialogueState:p,characterName:h});if(f.dialogue.append===!0&&a.length>0){a[a.length-1]={...a[a.length-1],content:g.content,text:g.text,characterId:g.characterId,character:g.character,characterName:g.characterName};continue}a.push(g)}return a},$l=({state:e})=>e.global.confirmDialog??null,bt=({state:e},{pointer:t}={})=>{let r=t??fe({state:e})?.pointer,n=dl({state:e,pointer:r});return fl({state:e,form:n.form,pointer:r})},kl=({state:e},{pointer:t}={})=>!!bt({state:e},{pointer:t}),we=({state:e},{pointer:t}={})=>{let r=bt({state:e},{pointer:t});if(r)return{source:Kt,formId:r.id,formKey:r.key};let n=Ii({state:e,pointer:t});return n?{source:nn,resourceId:n}:null},Tl=({state:e,registry:t},r)=>{let{sectionId:n,lineId:o}=r,s=(Array.isArray(t?.sections)?t.sections:[]).find(d=>d.sectionId===n);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let c=ne({state:e},{sectionId:n});if(!c||!c.lines||!Array.isArray(c.lines))return s.lastLineId===o;let a=c.lines.findIndex(d=>d.id===s.lastLineId),l=c.lines.findIndex(d=>d.id===o);return a===-1||l===-1?s.lastLineId===o:l<=a},Dl=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},dn=({state:e},t)=>Tl({state:e,registry:e.global.accountViewedRegistry},t),Pl=({state:e},t)=>Dl({registry:e.global.accountViewedRegistry},t),Nl=({state:e})=>e.global.nextLineConfig,Ii=({state:e,pointer:t}={})=>{let r=t??fe({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=ne({state:e},{sectionId:n})?.lines||[],c=s.findIndex(l=>l.id===o);if(c<0)return;let a;for(let l of s.slice(0,c+1)){let d=l?.actions;if(d?.cleanAll&&(a=void 0),!d||!Object.prototype.hasOwnProperty.call(d,"choice")){a=void 0;continue}let u=d.choice;if(u?.resourceId){a=u.resourceId;continue}u?.animations||(a=void 0)}return a},Ai=({state:e})=>!!Ii({state:e}),Vl=({state:e})=>structuredClone(e),wi=({state:e})=>e.global.saveSlots,jl=({state:e},t)=>{let r=t?.slotId,n=Qt(r);return e.global.saveSlots[n]},fn=({state:e})=>Fe(e),Ml=({state:e},t)=>Ee(e,t?.runtimeId),pn=({state:e})=>{let t={...e.global?.variables??{},...Zt(e)?.variables??{}};return ut({variables:t,runtime:Fe(e),variableConfigs:e.projectData.resources?.variables??{}})},fe=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},ne=({state:e},t)=>{let{sectionId:r}=t;return sn(e.projectData,r).section},hn=({state:e})=>{let t=fe({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=ne({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},Ei=({state:e})=>{let{sectionId:t,lineId:r}=fe({state:e}).pointer,o=ne({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===r),c=o.slice(0,i+1).map(l=>{let d=l.actions||{},u={};return Object.keys(d).forEach(f=>{u[f]=d[f]}),u});return je(c)},Fl=({state:e})=>{let t=vi({state:e}),n=hn({state:e})?.actions??{},o=je([t??{},n]);return Rr(t??{},o??{})},Ul=({state:e},{sectionId:t})=>{let r=ne({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},c=je([o,s]),a=Rr(o,c);n.push({id:i.id,changes:a,presentationState:c}),o=Or(c)}return n},Bl=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=Ul({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},vi=({state:e})=>{let{sectionId:t,lineId:r}=fe({state:e}).pointer,o=ne({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===r);if(i<=0)return null;let c=o.slice(0,i).map(a=>{let l=a.actions||{},d={};return Object.keys(l).forEach(u=>{d[u]=l[u]}),d});return Or(je(c))},mn=({state:e},{slotsPerPage:t=6}={})=>{let o=((fn({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let c=o+s,a=e.global.saveSlots&&e.global.saveSlots[Qt(c)]||{};i.push({...a,slotId:c})}return{saveSlots:i}},zl=wi,Wl=mn,ql=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;return!r||!Array.isArray(r.timeline)||typeof r.currentIndex!="number"?!1:r.currentIndex>=0&&r.currentIndex<r.timeline.length-1},Hl=({state:e},t={})=>{let r=Ei({state:e}),n=vi({state:e}),o=hn({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:D(i)}:o,c=i?.animations&&n===null?{}:n,{sectionId:a}=fe({state:e}).pointer,{sceneId:l}=sn(e.projectData,a),d=fn({state:e}),u=t?.activePersistentAnimations??[],f=t?.restoredPersistentAnimations??[],p=bt({state:e}),h=Ai({state:e}),g=pn({state:e}),{saveSlots:y}=mn({state:e}),b=ql(e);return Ko({presentationState:r,previousPresentationState:c,currentLineActions:s,resources:e.projectData.resources,currentSceneId:l,screen:e.projectData.screen,dialogueUIHidden:d.dialogueUIHidden,autoMode:d.autoMode,skipMode:d.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:Ti({state:e}),skipOnlyViewedLines:!d.skipUnseenText,isLineCompleted:d.isLineCompleted,skipTransitionsAndAnimations:!!d.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:bi({state:e}),saveSlots:y,variables:g,runtime:d,activePersistentAnimations:u,restoredPersistentAnimations:f})},Yl=({state:e},t)=>(e.global.confirmDialog=ol(t),e.global.pendingEffects.push({name:"render"}),e),Kl=({state:e})=>(e.global.confirmDialog&&(tt(e),e.global.pendingEffects.push({name:"render"})),e),Gl=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Ae(e,"pushOverlay",t),e),Jl=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Ae(e,"popOverlay",void 0),e),Xl=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),Ae(e,"replaceLastOverlay",t),e),Ql=({state:e})=>(e.global.overlayStack=[],tt(e),rt(e),e.global.pendingEffects.push({name:"render"}),Ae(e,"clearOverlays",void 0),e),Zl=e=>{e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},er=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,sl(e,r),rt(e);let n=we({state:e},{pointer:t}),o=n?.source===nn,i=n?.source===Kt;return n&&Zl(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},xi=({state:e})=>(we({state:e})||(e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.autoMode=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.isLineCompleted&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ee(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),It=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),eu=({state:e})=>{let t=e.global.autoMode;return we({state:e})&&!t||(t?It({state:e}):xi({state:e})),e},Ci=({state:e})=>(we({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),We=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),tu=({state:e})=>{let t=gi({state:e});return we({state:e})&&!t||(t?We({state:e}):Ci({state:e})),e},tr=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Ae(e,"showDialogueUI",void 0),e),Si=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Ae(e,"hideDialogueUI",void 0),e),ru=({state:e})=>(yi({state:e})?tr({state:e}):Si({state:e}),e),Ye=(e,t,r)=>(fi(e,t,r),yl(e),e.global.pendingEffects.push({name:"render"}),e),At=(e,t,r,n)=>{let o=fi(e,t,r);return e.global.pendingEffects.push({name:"render"}),Ae(e,n,{value:o}),e},nu=({state:e},t)=>Ye(e,"dialogueTextSpeed",t?.value),ou=({state:e},t)=>Ye(e,"autoForwardDelay",t?.value),iu=({state:e},t)=>Ye(e,"skipUnseenText",t?.value),su=({state:e},t)=>Ye(e,"skipTransitionsAndAnimations",t?.value),au=({state:e},t)=>Ye(e,"soundVolume",t?.value),cu=({state:e},t)=>Ye(e,"musicVolume",t?.value),lu=({state:e},t)=>Ye(e,"muteAll",t?.value),uu=({state:e},t)=>At(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),du=({state:e})=>{let t=Ee(e,"saveLoadPagination")+1;return At(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},fu=({state:e})=>{let t=Ee(e,"saveLoadPagination")-1;return At(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},pu=({state:e},t)=>At(e,"menuPage",t?.value,"setMenuPage"),hu=({state:e},t)=>At(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),mu=({state:e})=>(e.global.pendingEffects=[],e),gu=({state:e},t)=>(e.global.pendingEffects.push(t),e),_i=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!si(n),i=ne({state:e},{sectionId:t});if(!i)return console.warn(`Section not found: ${t}`),e;let s=i.lines?.[0];if(!s)return console.warn(`Section ${t} has no lines`),e;if(r&&!Al(e,{queueRender:!o}))return e;e.global.autoMode&&It({state:e}),r&&e.global.skipMode&&We({state:e});let c=e.contexts?.[e.contexts.length-1];if(c){let a=nt(c),l=a.read;r||qe(e,{sectionId:l?.sectionId,lineId:l?.lineId}),c.rollback||He(c,{compatibilityAnchor:!0}),a.read={sectionId:t,lineId:s.id},r?c.rollback=yt({pointer:a.read}):un(e,{sectionId:t,lineId:s.id})}return er(e,c?.pointers?.read,{screenTransition:n}),e},yu=({state:e},t)=>_i(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),Ri=e=>(e.global.accountViewedRegistry=qc(e.global.accountViewedRegistry),e.global.accountViewedRegistry),gn=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(r=>({scope:r.scope,path:r.path,op:r.op,value:D(r.value)}))}})},Oi=(e,t)=>{gn(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(r=>({sectionId:r.sectionId,...r.lastLineId===void 0?{}:{lineId:r.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},bu=(e,t,{sectionId:r,lineId:n})=>{if(!r||!n)return!1;let o=T(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===r);if(i){if(i.lastLineId===void 0)return!1;let s=ne({state:e},{sectionId:r});if(s?.lines){let c=s.lines.findIndex(l=>l.id===i.lastLineId),a=s.lines.findIndex(l=>l.id===n);if(c===-1||a>c)return i.lastLineId===n?!1:(i.lastLineId=n,!0)}else return i.lastLineId===n?!1:(i.lastLineId=n,!0);return!1}else return o.sections.push({sectionId:r,lastLineId:n}),!0},qe=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;bu(e,Ri(e),t)&&Oi(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},Iu=({state:e},t)=>(qe(e,t),e.global.pendingEffects.push({name:"render"}),e),Au=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=Ri(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),Oi(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},Li=({state:e},t)=>{let r=Gc(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,c=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;r&&n?(e.global.nextLineConfig={manual:r,auto:n},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(r&&(e.global.nextLineConfig.manual=r),n&&(e.global.nextLineConfig.auto=n),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let a=e.global.nextLineConfig.auto?.enabled,l=we({state:e});return!c&&!l&&a===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!c&&a===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),Ae(e,"setNextLineConfig",t),e},wu=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:n}=t,o=t?.savedAt,i=Qt(r),s=D(e.contexts);s?.forEach(l=>{nt(l),hi(l.rollback),Qc(l.rollback)});let c={contexts:s},a={formatVersion:Zo,slotId:ri(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:c};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Eu=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=Qt(r),o=e.global.saveSlots[n];if(o){let i=nl(o,e.projectData);e.contexts=i.state.contexts,e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=Xt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,tt(e),rt(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},vu=({state:e},t)=>{let{projectData:r}=t;ti(r),e.projectData=r;let n=r?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=Vt(r??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...Xe(e.global.variables,n)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...Xe(s.variables,n)})}),tt(e),rt(e),e.global.pendingEffects.push({name:"render"}),e},xu=({state:e},t)=>{let{sectionId:r,lineId:n}=t;if(!n)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=r||o.pointers.read?.sectionId;if(r&&!ne({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=ne({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(l=>l.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let a=nt(o);return a.read={sectionId:i,lineId:n},er(e,a.read),e},Cu=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return tr({state:e}),e;let r=we({state:e});if(r?.source===nn&&t?.bypassChoice!==!0||r?.source===Kt&&t?._interactionSource!==Kt)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let d=fe({state:e})?.pointer,u=d?.sectionId,f=d?.lineId;u&&f&&qe(e,{sectionId:u,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ee(e,"autoForwardDelay")}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=fe({state:e})?.pointer,o=n?.sectionId,i=ne({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],c=i?.lines||[],l=c.findIndex(d=>d.id===n?.lineId)+1;if(l<c.length){let d=c[l],u=!Ee(e,"skipUnseenText");if(e.global.skipMode&&u&&!dn({state:e},{sectionId:o,lineId:d.id}))return We({state:e}),e;if(s&&!s.rollback&&He(s,{compatibilityAnchor:!0}),s){let h=nt(s),g=h.read?.lineId;g&&o&&qe(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:d.id}}un(e,{sectionId:o,lineId:d.id}),on(e);let{activeInteraction:f}=er(e,{sectionId:o,lineId:d.id}),p=e.global.nextLineConfig;p?.auto?.enabled&&!f&&p.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}})}else e.global.autoMode&&It({state:e}),e.global.skipMode&&We({state:e});return e},Su=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=we({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ee(e,"autoForwardDelay")}});let r=fe({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&qe(e,{sectionId:n,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},_u=({state:e},t)=>_i(e,{sectionId:t?.sectionId,screen:t?.screen}),Ru=({state:e})=>{if(e.global.dialogueUIHidden)return tr({state:e}),e;if(we({state:e}))return e;let t=fe({state:e})?.pointer,r=t?.sectionId,n=ne({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],c=i.findIndex(a=>a.id===t?.lineId)+1;if(c<i.length){let a=i[c],l=!Ee(e,"skipUnseenText");if(e.global.skipMode&&l&&!dn({state:e},{sectionId:r,lineId:a.id}))return We({state:e}),e;if(o&&!o.rollback&&He(o,{compatibilityAnchor:!0}),o){let u=nt(o),f=u.read?.lineId;f&&r&&qe(e,{sectionId:r,lineId:f}),u.read={sectionId:r,lineId:a.id}}un(e,{sectionId:r,lineId:a.id}),on(e);let{activeInteraction:d}=er(e,{sectionId:r,lineId:a.id});e.global.nextLineConfig.auto?.enabled&&!d&&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},yn=(e,t={})=>{let r=bt({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},Ou=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let r=e.projectData.resources?.variables?.[t.variableId],n=r?.scope,o=r?.type;if(Le(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return jt(n,t.variableId),Mt(o,"set",t.variableId),{variableConfig:r,scope:n}},Lu=(e,t)=>({id:e.id,key:e.key,valid:!0,values:D(t),fields:D(e.fields),fieldList:D(e.fieldList)}),$u=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=fe({state:e})?.pointer,r=t?.sectionId,n=t?.lineId;r&&n&&qe(e,{sectionId:r,lineId:n})},ku=({state:e},t={})=>{let r=yn(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=ci(e,r.key),i=Gt(t.value),s=r.fields[n],c=an(s,i);return o.values[n]=i,o.touched[n]=!0,c?o.errors[n]=c:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},Tu=({state:e},t={})=>{let r=yn(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=ci(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([u,f])=>{let p=Object.prototype.hasOwnProperty.call(n.values,u)?n.values[u]:f.value,h=an(f,p);n.touched[u]=!0,h&&(i[u]=h),o[u]=ai(f,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:D(i),form:{id:r.id,key:r.key,values:D(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let c=!1,a=[],l=[];Object.entries(r.fields).forEach(([u,f])=>{let{scope:p}=Ou(e,f),h=p==="context"?s.variables:e.global.variables,g=o[u];h[f.variableId]=Ft(h[f.variableId],"set",g),p==="context"&&(c=!0,l.push({variableId:f.variableId,op:"set",value:g})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${f.variableId}`,op:"set",value:D(h[f.variableId])})}),c&&Ae(e,"updateVariable",{id:"submitForm",operations:l}),gn(e,a);let d=Lu(r,o);return $u(e),delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:d}},Du=({state:e},t={})=>{let r=yn(e,t);return r?(delete e.global.formDrafts?.[r.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:r.id,key:r.key,values:D(r.values),fields:D(r.fields),fieldList:D(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},Pu=({state:e},t)=>{let{id:r,operations:n=[]}=t;if(!r)throw new Error("updateVariable requires an id field");if(typeof r!="string"||!/^[a-zA-Z0-9]+$/.test(r))throw new Error(`updateVariable id must be alphanumeric, got: "${r}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],c=[];return n.forEach(({variableId:a,op:l,value:d,roundTo:u})=>{let f=e.projectData.resources?.variables?.[a],p=f?.scope,h=f?.type;if(Le(f))throw new Error(`Cannot update computed variable: ${a}`);if(f?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);jt(p,a),Mt(h,l,a),_r(h,l,d,a,{roundTo:u});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:a,op:l,value:d};u!==void 0&&(y.roundTo=u),c.push(y)}g[a]=Ft(g[a],l,d,{roundTo:u}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:D(g[a])})}),i&&Ae(e,"updateVariable",{id:r,operations:c}),gn(e,s),e.global.pendingEffects.push({name:"render"}),e},Nu=e=>(t,r)=>e({state:t},r),Vu=e=>({variables:ut({variables:{...e.global?.variables??{},...Zt(e)?.variables??{}},runtime:Fe(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:Fe(e)}),ju=e=>{if(!T(e))throw new Error("conditional action payload must be an object");if(!Array.isArray(e.branches))throw new Error("conditional action requires branches array");if(e.branches.length===0)throw new Error("conditional action requires at least one branch")},Mu=(e,t,r)=>{if(!T(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!T(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==r-1)throw new Error("conditional else branch must be the last branch")},Fu=(e,t)=>{ju(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(Mu(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!lt(n.when,Vu(e)))){Object.entries(n.actions).forEach(([i,s])=>{$i(e,i,s)});return}}},Uu={conditional:{replayLine:Fu},updateVariable:{recordSources:[cn],replayLine:Qo,replayRecorded:Qo,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Nu(Li)}},rr=e=>Uu[e]??null,Bu=e=>rr(e)?.persistInSaveSlot===!0,zu=(e,t)=>{let r=rr(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},Wu=(e,t,r)=>{rr(t)?.replayRecorded?.(e,r)},$i=(e,t,r)=>{rr(t)?.replayLine?.(e,r)},ki=({state:e},t)=>{let{offset:r}=t;if(r===void 0||typeof r!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let n=e.contexts[e.contexts.length-1];if(!n)return null;let o=n.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+r;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},Ti=({state:e})=>ki({state:e},{offset:-1})!==null,qu=({state:e},t)=>{let{offset:r=-1}=t;if(r>=0)throw new Error("rollbackByOffset requires a negative offset");let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let o=He(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:mi(e,i)},Hu=({state:e},t)=>{let{sectionId:r,lineId:n}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=He(o,{compatibilityAnchor:!o.rollback}),c=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===r&&a.lineId===n);if(c===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return c===i.currentIndex?e:mi(e,c)},Di=e=>{let t=_l(e);return ro(t,{selectPendingEffects:Ol,selectSkipMode:gi,selectAutoMode:Ll,selectIsChoiceVisible:Ai,selectIsFormVisible:kl,selectActiveInteraction:we,selectActiveForm:bt,selectDialogueUIHidden:yi,selectDialogueHistory:bi,selectConfirmDialog:$l,selectIsLineAccountViewed:dn,selectIsResourceAccountViewed:Pl,selectNextLineConfig:Nl,selectSystemState:Vl,selectSaveSlotMap:wi,selectSaveSlots:zl,selectSaveSlot:jl,selectRuntime:fn,selectRuntimeValue:Ml,selectAllVariables:pn,selectCurrentPointer:fe,selectSection:ne,selectCurrentLine:hn,selectPresentationState:Ei,selectPresentationChanges:Fl,selectSectionLineChanges:Bl,selectSaveSlotPage:mn,selectCurrentPageSlots:Wl,selectRenderState:Hl,selectOverlayStack:Rl,selectLineIdByOffset:ki,selectCanRollback:Ti,startAutoMode:xi,stopAutoMode:It,toggleAutoMode:eu,startSkipMode:Ci,stopSkipMode:We,toggleSkipMode:tu,showDialogueUI:tr,hideDialogueUI:Si,toggleDialogueUI:ru,setDialogueTextSpeed:nu,setAutoForwardDelay:ou,setSkipUnseenText:iu,setSkipTransitionsAndAnimations:su,setSoundVolume:au,setMusicVolume:cu,setMuteAll:lu,setSaveLoadPagination:uu,incrementSaveLoadPagination:du,decrementSaveLoadPagination:fu,setMenuPage:pu,setMenuEntryPoint:hu,showConfirmDialog:Yl,hideConfirmDialog:Kl,resetStoryAtSection:yu,clearPendingEffects:mu,appendPendingEffect:gu,beginRollbackActionBatch:vl,endRollbackActionBatch:xl,addViewedLine:Iu,addViewedResource:Au,setNextLineConfig:Li,saveSlot:wu,loadSlot:Eu,updateProjectData:vu,sectionTransition:_u,jumpToLine:xu,nextLine:Cu,markLineCompleted:Su,rollbackToLine:Hu,rollbackByOffset:qu,pushOverlay:Gl,popOverlay:Jl,replaceLastOverlay:Xl,clearOverlays:Ql,updateFormField:ku,submitForm:Tu,cancelForm:Du,updateVariable:Pu,nextLineFromSystem:Ru},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var Yu="route-engine",Ku="projectPersistence";var Ni=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),ee=e=>Object.prototype.toString.call(e)==="[object Object]",Pi="variables.",Gu=(e={})=>{let t=ee(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!ee(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lineId=="string"?{lineId:r.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!ee(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Ju=(e={})=>{let t=ee(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!ee(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lastLineId=="string"?{lastLineId:r.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!ee(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Xu=(e,t)=>{let r=Ju(e),n=Gu(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let c=o.find(a=>a.sectionId===s.sectionId);if(!c){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(c.lastLineId!==void 0){if(s.lineId===void 0){delete c.lastLineId;return}c.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},Vi=(e={})=>{let t=ee(e)?e:{};return{saveSlots:ee(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:ee(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:ee(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:ee(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:ee(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Qu=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!ee(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(Pi)?t.path.slice(Pi.length):null;if(n!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(n.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${r}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:n}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${r}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${r}].`)})},Zu=(e,t)=>{let r={};return Qu(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=Xu(r.accountViewedRegistry??e.accountViewedRegistry,n.value);return}let o=n.scope==="device"?"globalDeviceVariables":"globalAccountVariables";r[o]={...e[o],...r[o],[n.variableId]:n.value}}),r},bn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},ed=e=>{let t=bn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},td=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},rd=({indexedDB:e,databaseName:t,objectStoreName:r})=>new Promise((n,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(r)||s.createObjectStore(r,{keyPath:"namespace"})},i.onsuccess=()=>{n(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),nd=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let a=n.transaction(t,"readonly").objectStore(t).get(r);a.onsuccess=()=>{o(a.result??null)},a.onerror=()=>{i(a.error??new Error(`Failed to read persisted namespace "${r}" from IndexedDB.`))}})},wt=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let c=o.transaction(t,"readwrite"),a=c.objectStore(t),l=a.get(r),d=!1,u=p=>{d||(d=!0,s(p))},f=()=>{d||(d=!0,i())};l.onerror=()=>{u(l.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},l.onsuccess=()=>{let p=Vi(l.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...Ni(),...p,...h},y=a.put(g);y.onerror=()=>{u(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},c.oncomplete=()=>{f()},c.onerror=()=>{u(c.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},c.onabort=()=>{u(c.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},od=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let s=n.transaction(t,"readwrite"),a=s.objectStore(t).delete(r),l=!1,d=f=>{l||(l=!0,i(f))},u=()=>{l||(l=!0,o())};a.onerror=()=>{d(a.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{u()},s.onerror=()=>{d(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{d(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},In=(e={})=>{let{indexedDB:t,databaseName:r=Yu,objectStoreName:n=Ku,namespace:o}=e,i=td(t),s=ed(o),c=rd({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let a=await nd({databasePromise:c,objectStoreName:n,namespace:s});return{...Ni(),...Vi(a)}},clear:async()=>od({databasePromise:c,objectStoreName:n,namespace:s}),saveSlots:async a=>wt({databasePromise:c,objectStoreName:n,namespace:s,patch:{saveSlots:ee(a)?a:{}}}),saveGlobalDeviceVariables:async a=>wt({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:ee(a)?a:{}}}),saveGlobalAccountVariables:async a=>wt({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalAccountVariables:ee(a)?a:{}}}),saveGlobalRuntime:async a=>wt({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalRuntime:ee(a)?a:{}}}),applyScopedDataUpdates:async a=>wt({databasePromise:c,objectStoreName:n,namespace:s,patch:l=>Zu(l,a)})}},id=In;var sd=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),ad=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),ji="conditional",An="form",cd=new Set(["submitForm","cancelForm"]),Et=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function wn(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:c}=e,a=(I=new Map,S=Date.now())=>new Map(Array.from(I.entries()).filter(([,O])=>S<O.expiresAt).map(([O,j])=>[O,{animation:structuredClone(j.animation),startedAt:j.startedAt,expiresAt:j.expiresAt}])),l=(I=new Map)=>Array.from(I.values()).map(S=>structuredClone(S.animation)),d=(I=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,S])=>I<S.expiresAt))},u=()=>{for(;t.selectPendingEffects().length>0;){let I=[...t.selectPendingEffects()];t.clearPendingEffects();try{c(I)}catch(S){throw t.clearPendingEffects(),I.forEach(O=>{t.appendPendingEffect(O)}),S}}},f=({initialState:I,namespace:S})=>{t=Di(I),r=0,n=bn(S),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),u()},p=()=>n,h=()=>t.selectPresentationState(),g=()=>t.selectPresentationChanges(),y=I=>t.selectSectionLineChanges(I),b=(I={})=>{r+=1;let S=Date.now();d(S);let O=i.size>0,j=a(o,S),z=O?a(i,S):new Map,be={...t.selectRenderState({activePersistentAnimations:l(j),restoredPersistentAnimations:l(z)}),id:`render-${r}`};return s.set(be.id,{builtAt:S,persistentAnimationSessions:new Map([...z.entries(),...j.entries()]),usedRestoredPersistentAnimationSessions:O}),be},A=(I={})=>b(I),v=(I={})=>b(I),_=I=>{let S=typeof I?.id=="string"&&I.id.length>0?I.id:null,O=S?s.get(S):null;S&&s.delete(S);let j=new Map;Do(I?.animations).forEach(z=>{let le=Wt(z);if(!le)return;let be=O?.persistentAnimationSessions?.get(le)??o.get(le),xt=Math.max(0,No(z)),xn=be?.startedAt??O?.builtAt??Date.now();j.set(le,{animation:structuredClone(z),startedAt:xn,expiresAt:xn+xt})}),o=j,O?.usedRestoredPersistentAnimationSessions&&(i=new Map)},P=()=>t.selectSystemState(),k=()=>t.selectSaveSlotMap(),w=I=>t.selectSaveSlot(I),M=I=>t.selectSaveSlotPage(I),F=()=>t.selectSkipMode(),Z=()=>t.selectAutoMode(),V=()=>t.selectRuntime(),q=()=>t.selectIsChoiceVisible(),Y=()=>t.selectIsFormVisible(),te=()=>t.selectActiveInteraction(),pe=(I,S,O={})=>I!=="nextLine"||!Et(S)?S:O.bypassChoice===!0?{...S,bypassChoice:!0}:O.interactionSource===An?{...S,_interactionSource:An}:S,G=(I,S)=>{if(!t[I])return;sd.has(I)&&(ad.has(I)?i=a(o):i=new Map,o=new Map);let O=t[I](S);return u(),O},H=(I,S,O,j={})=>{if(I===ji){let z=C(O),le=Lr({[I]:S},z);J(le[I],O,j);return}G(I,S)},x=(I,S)=>{H(I,S)},C=I=>{if(!I)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(I,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:S,...O}=I,j=t.selectAllVariables?t.selectAllVariables():void 0;return{...O,_event:S,variables:j,runtime:t.selectRuntime?t.selectRuntime():{}}},R=I=>{if(!Et(I))throw new Error("conditional action payload must be an object");if(!Array.isArray(I.branches))throw new Error("conditional action requires branches array");if(I.branches.length===0)throw new Error("conditional action requires at least one branch")},B=(I,S,O)=>{if(!Et(I))throw new Error(`conditional branch at index ${S} must be an object`);if(!Et(I.actions))throw new Error(`conditional branch at index ${S} requires actions object`);if(!Object.prototype.hasOwnProperty.call(I,"when")&&S!==O-1)throw new Error("conditional else branch must be the last branch")},J=(I,S,O)=>{R(I);for(let j=0;j<I.branches.length;j+=1){let z=I.branches[j];B(z,j,I.branches.length);let le=C(S);if(!(Object.prototype.hasOwnProperty.call(z,"when")&&!lt(z.when,le))){or(z.actions,S,O);return}}},U=(I,S)=>({...I??{},_form:S}),vt=(I,S,O,j)=>{let z=G(I,S),le=z?.submitted===!0&&z.valid===!0,be=z?.cancelled===!0;!le&&!be||Et(S.actions)&&or(S.actions,U(O,z.form),{...j,interactionSource:An})},Ke=(I,S,O,j)=>{let z=C(O),be=Lr({[I]:S},z)[I];if(I===ji){J(be,O,j);return}let xt=pe(I,be,j);if(cd.has(I)){vt(I,xt,O,j);return}G(I,xt)},or=(I,S,O)=>{Object.entries(I).forEach(([j,z])=>{Ke(j,z,S,O)})},vn=(I,S,O={})=>{t.beginRollbackActionBatch({source:O.rollbackSource});try{or(I,S,O)}finally{t.endRollbackActionBatch({})}};return{init:f,handleAction:H,handleInternalAction:x,handleActions:vn,selectRenderState:A,prepareRenderState:v,commitRenderState:_,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:P,selectSaveSlotMap:k,selectSaveSlot:w,selectSaveSlotPage:M,selectSaveSlots:k,selectRuntime:V,selectIsChoiceVisible:q,selectIsFormVisible:Y,selectActiveInteraction:te,handleLineActions:()=>{let I=t.selectCurrentLine();return I?.actions?(vn(I.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var En=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},ld=80,Fi=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},ud=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&Fi({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},dd=({engine:e,ticker:t,autoTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n.delay??1e3;r.getElapsed()>=c&&(t.remove(i),r.setCallback(null),r.setElapsed(0),nr(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},fd=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},pd=({engine:e,ticker:t,skipTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n?.delay??ld;r.getElapsed()>=c&&(r.setElapsed(0),nr(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},hd=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},md=({engine:e,ticker:t,nextLineConfigTimerState:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n.delay??1e3;r.getElapsed()>=c&&(r.setElapsed(0),nr(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},gd=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},yd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},bd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},Id=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},Ad=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},wd=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},Mi={render:Fi,saveSlots:yd,saveGlobalDeviceVariables:bd,saveGlobalAccountVariables:Id,saveGlobalRuntime:Ad,applyScopedDataUpdates:wd,handleLineActions:ud,startAutoNextTimer:dd,clearAutoNextTimer:fd,startSkipNextTimer:pd,clearSkipNextTimer:hd,nextLineConfigTimer:md,clearNextLineConfigTimer:gd},Ed=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),nr=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},vd=(e=[])=>{let t=new Set,r=[];for(let n=e.length-1;n>=0;n-=1){let o=e[n];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!Ed.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},xd=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:c})=>{let a=En(),l=En(),d=En(),u=s??null,f=Promise.resolve(),p=null,h=null,g=!1,y=0,b=x=>{if(o){o(x);return}console.error("RouteEngine persistence write failed.",x)},A=()=>{if(u)return u;let x=e();return u=In({indexedDB:i,namespace:c??x?.getNamespace?.()}),u},v=x=>{f=f.catch(()=>{}).then(()=>{let C=A();return x(C)}).catch(C=>{b(C)})},_=x=>{let C=typeof x?.id=="string"&&x.id.length>0?x.id:null;y+=1,p=C,g=!1},P=()=>y,k=(x={})=>{if(x?.aborted===!0)return!1;let C=typeof x?.id=="string"&&x.id.length>0?x.id:null;return C?C!==p||C===h?!1:(h=C,!0):p!==null||g?!1:(g=!0,!0)},w=(x,C={})=>{if(x!=="renderComplete"||!k(C))return!1;let R=e();return nr(R,"markLineCompleted",{}),!0},M=new Set(["updateFormField","submitForm","cancelForm"]),F=x=>typeof x?.selectActiveInteraction=="function"?x.selectActiveInteraction():typeof x?.selectIsChoiceVisible=="function"&&x.selectIsChoiceVisible()?{source:"choice"}:null,Z=x=>x?._formKey??x?.formKey,V=(x,C)=>Z(x)===C?.formKey,q=(x,C)=>!x||typeof x!="object"||Array.isArray(x)||x._interactionSource!==C?.source?!1:C.source==="form"?V(x,C):!0,Y=(x,C)=>!x||typeof x!="object"||Array.isArray(x)||C?.source!=="form"?!1:V(x,C),te=(x={},C)=>{let R=x?.actions;return C?.source==="form"?q(x,C)?!0:!R||typeof R!="object"||Array.isArray(R)?!1:Object.entries(R).some(([B,J])=>M.has(B)&&Y(J,C)):q(x,C)?!0:!R||typeof R!="object"||Array.isArray(R)?!1:Object.values(R).some(B=>q(B,C))},pe=(x,C={})=>{if(!C?.actions)return!1;let R=F(x);return!R||R.source==="choice"?!1:!te(C,R)},G=({preprocessPayload:x,onEvent:C}={})=>async(R,B={})=>{let J=e();if(pe(J,B))return C?.(R,B);let U=await x?.(R,B)??B;if(pe(J,U))return C?.(R,U);if(w(R,U),U?.actions){let vt=U?._event?{_event:U._event}:U?.event?{_event:U.event}:void 0,Ke;U?.bypassChoice===!0?Ke={bypassChoice:!0}:U?._interactionSource&&(Ke={interactionSource:U._interactionSource}),Ke?J.handleActions(U.actions,vt,Ke):J.handleActions(U.actions,vt)}return C?.(R,U)},H=x=>{let C=e(),R=vd(x);R.forEach(J=>{if(!Mi[J.name]&&!n)throw new Error(`Unhandled pending effect "${J.name}".`)});let B={engine:C,routeGraphics:t,ticker:r,autoTimer:a,skipTimer:l,nextLineConfigTimerState:d,trackRenderDispatch:_,getRenderDispatchCount:P,enqueuePersistenceWrite:v};for(let J of R){let U=Mi[J.name];if(U){U(B,J.payload);continue}n(J,B)}};return H.handleRouteGraphicsEvent=w,H.createRouteGraphicsEventHandler=G,H},Cd=xd;var Sd=(e,t={})=>{let{resources:r={}}=t;return tn(e,r)};var Hf=wn;export{Tr as DEFAULT_VISUAL_LAYER,Qe as RENDER_LAYER,ve as VISUAL_LAYER,Cd as createEffectsHandler,id as createIndexedDbPersistence,Hf as default,Ks as resolveComputedVariables,Sd as resolveLayoutReferences};
1
+ var Ui=Object.defineProperty;var Bi=(e,t)=>{for(var r in t)Ui(e,r,{get:t[r],enumerable:!0})};var Ln=Symbol.for("immer-nothing"),Cn=Symbol.for("immer-draftable"),se=Symbol.for("immer-state");function he(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Ge=Object.getPrototypeOf;function ae(e){return!!e&&!!e[se]}function Pe(e){return e?$n(e)||Array.isArray(e)||!!e[Cn]||!!e.constructor?.[Cn]||Ot(e)||Lt(e):!1}var zi=Object.prototype.constructor.toString();function $n(e){if(!e||typeof e!="object")return!1;let t=Ge(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===zi}function Ct(e,t){Rt(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function Rt(e){let t=e[se];return t?t.type_:Array.isArray(e)?1:Ot(e)?2:Lt(e)?3:0}function ar(e,t){return Rt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function kn(e,t,r){let n=Rt(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function Wi(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Ot(e){return e instanceof Map}function Lt(e){return e instanceof Set}function De(e){return e.copy_||e.base_}function cr(e,t){if(Ot(e))return new Map(e);if(Lt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=$n(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[se];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],c=n[s];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(n[s]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[s]})}return Object.create(Ge(e),n)}else{let n=Ge(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function pr(e,t=!1){return $t(e)||ae(e)||!Pe(e)||(Rt(e)>1&&(e.set=e.add=e.clear=e.delete=qi),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>pr(n,!0))),e}function qi(){he(2)}function $t(e){return Object.isFrozen(e)}var Hi={};function Ne(e){let t=Hi[e];return t||he(0,e),t}var ot;function Tn(){return ot}function Yi(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Sn(e,t){t&&(Ne("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function lr(e){ur(e),e.drafts_.forEach(Ki),e.drafts_=null}function ur(e){e===ot&&(ot=e.parent_)}function _n(e){return ot=Yi(ot,e)}function Ki(e){let t=e[se];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Rn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[se].modified_&&(lr(t),he(4)),Pe(e)&&(e=St(t,e),t.parent_||_t(t,e)),t.patches_&&Ne("Patches").generateReplacementPatches_(r[se].base_,e,t.patches_,t.inversePatches_)):e=St(t,r,[]),lr(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Ln?e:void 0}function St(e,t,r){if($t(t))return t;let n=t[se];if(!n)return Ct(t,(o,i)=>On(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return _t(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let o=n.copy_,i=o,s=!1;n.type_===3&&(i=new Set(o),o.clear(),s=!0),Ct(i,(c,a)=>On(e,n,o,c,a,r,s)),_t(e,o,!1),r&&e.patches_&&Ne("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function On(e,t,r,n,o,i,s){if(ae(o)){let c=i&&t&&t.type_!==3&&!ar(t.assigned_,n)?i.concat(n):void 0,a=St(e,o,c);if(kn(r,n,a),ae(a))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(Pe(o)&&!$t(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;St(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&_t(e,o)}}function _t(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&pr(t,r)}function Gi(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:Tn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=hr;r&&(o=[n],i=it);let{revoke:s,proxy:c}=Proxy.revocable(o,i);return n.draft_=c,n.revoke_=s,c}var hr={get(e,t){if(t===se)return e;let r=De(e);if(!ar(r,t))return Ji(e,r,t);let n=r[t];return e.finalized_||!Pe(n)?n:n===ir(e.base_,t)?(sr(e),e.copy_[t]=fr(n,e)):n},has(e,t){return t in De(e)},ownKeys(e){return Reflect.ownKeys(De(e))},set(e,t,r){let n=Dn(De(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=ir(De(e),t),i=o?.[se];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(Wi(r,o)&&(r!==void 0||ar(e.base_,t)))return!0;sr(e),dr(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return ir(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,sr(e),dr(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=De(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){he(11)},getPrototypeOf(e){return Ge(e.base_)},setPrototypeOf(){he(12)}},it={};Ct(hr,(e,t)=>{it[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});it.deleteProperty=function(e,t){return it.set.call(this,e,t,void 0)};it.set=function(e,t,r){return hr.set.call(this,e[0],t,r,e[0])};function ir(e,t){let r=e[se];return(r?De(r):e)[t]}function Ji(e,t,r){let n=Dn(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function Dn(e,t){if(!(t in e))return;let r=Ge(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=Ge(r)}}function dr(e){e.modified_||(e.modified_=!0,e.parent_&&dr(e.parent_))}function sr(e){e.copy_||(e.copy_=cr(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Xi=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,n)=>{if(typeof t=="function"&&typeof r!="function"){let i=r;r=t;let s=this;return function(a=i,...l){return s.produce(a,d=>r.call(this,d,...l))}}typeof r!="function"&&he(6),n!==void 0&&typeof n!="function"&&he(7);let o;if(Pe(t)){let i=_n(this),s=fr(t,void 0),c=!0;try{o=r(s),c=!1}finally{c?lr(i):ur(i)}return Sn(i,n),Rn(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===Ln&&(o=void 0),this.autoFreeze_&&pr(o,!0),n){let i=[],s=[];Ne("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else he(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...c)=>this.produceWithPatches(s,a=>t(a,...c));let n,o;return[this.produce(t,r,(s,c)=>{n=s,o=c}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Pe(e)||he(8),ae(e)&&(e=Ve(e));let t=_n(this),r=fr(e,void 0);return r[se].isManual_=!0,ur(t),r}finishDraft(e,t){let r=e&&e[se];(!r||!r.isManual_)&&he(9);let{scope_:n}=r;return Sn(n,t),Rn(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let o=t[r];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}r>-1&&(t=t.slice(r+1));let n=Ne("Patches").applyPatches_;return ae(e)?n(e,t):this.produce(e,o=>n(o,t))}};function fr(e,t){let r=Ot(e)?Ne("MapSet").proxyMap_(e,t):Lt(e)?Ne("MapSet").proxySet_(e,t):Gi(e,t);return(t?t.scope_:Tn()).drafts_.push(r),r}function Ve(e){return ae(e)||he(10,e),Pn(e)}function Pn(e){if(!Pe(e)||$t(e))return e;let t=e[se],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=cr(e,t.scope_.immer_.useStrictShallowCopy_)}else r=cr(e,!0);return Ct(r,(n,o)=>{kn(r,n,Pn(o))}),t&&(t.finalized_=!1),r}var ce=new Xi,mr=ce.produce,Od=ce.produceWithPatches.bind(ce),Ld=ce.setAutoFreeze.bind(ce),$d=ce.setUseStrictShallowCopy.bind(ce),kd=ce.applyPatches.bind(ce),Td=ce.createDraft.bind(ce),Dd=ce.finishDraft.bind(ce);var m={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},L={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},Je={NOT:0};var E=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},oe=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var gr=e=>{if(!e||e.trim()==="")throw new E("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new E(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${r}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let r of t)if(e.trim().endsWith(r))throw new E(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Nn=e=>{if(e.trim().endsWith(" in"))throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new E(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);let n=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of n){if(!o)throw new E(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new E(`Invalid loop syntax (got: '$for ${e}')`)}};var Vn=(e,t,r=!1)=>{if(t===null)return new oe(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new oe(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new oe(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new oe(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},jn=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new oe(`Unknown function '${e}' (${r})`)};var Qi=(e,t,r={})=>{let n={},o={};r&&typeof r=="object"&&(r.functions!==void 0||r.partials!==void 0?(n=r.functions||{},o=r.partials||{}):typeof r=="object"&&(n=r));let s=$(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},$=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return K(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return K(e.path,r,n);if(e.type===m.INTERPOLATION)return es(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return Fn(e,t,r,n);case m.BINARY:return Un(e,t,r,n);case m.UNARY:return Bn(e,t,r,n);case m.CONDITIONAL:return rs(e,t,r,n);case m.LOOP:return as(e,t,r,n);case m.OBJECT:return ls(e,t,r,n);case m.ARRAY:return us(e,t,r,n);case m.PARTIAL:return ds(e,t,r,n);case m.PATH_REFERENCE:return fs(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Mn=new Map,Zi=e=>{let t=[],r="",n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")r&&(t.push({type:"property",value:r}),r=""),n=!0;else if(i==="]"){if(n&&r){let s=r.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let c=s.slice(1,-1);t.push({type:"property",value:c})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},K=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=Mn.get(e);if(!n){let i=[],s="",c=0;for(let a=0;a<e.length;a++){let l=e[a];l==="["?(c++,s+=l):l==="]"?(c--,s+=l):l==="."&&c===0?s&&(i.push(s),s=""):s+=l}s&&i.push(s),n=[];for(let a of i){let l=Zi(a.trim());n.push(...l)}Mn.set(e,n)}let o=t;for(let i=0;i<n.length;i++){let s=n[i];if(s.type==="property"&&s.value in r){o=r[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},es=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=$(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},Fn=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw jn(e.name,o);let s=e.args.map(c=>$(c,t,r,n));return i(...s)},_e=(e,t,r,n)=>{if(e.var&&!e.type)return K(e.var,r,n);switch(e.type){case m.VARIABLE:return K(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return Un(e,t,r,n);case m.UNARY:return Bn(e,t,r,n);case m.FUNCTION:return Fn(e,t,r,n);default:return $(e,t,r,n)}},Un=(e,t,r,n)=>{if(e.op===L.AND||e.op===L.OR){let s=_e(e.left,t,r,n),c=_e(e.right,t,r,n);switch(e.op){case L.AND:return s&&c;case L.OR:return s||c}}let o=$(e.left,t,r,n),i=$(e.right,t,r,n);switch(e.op){case L.EQ:return o==i;case L.NEQ:return o!=i;case L.GT:return o>i;case L.LT:return o<i;case L.GTE:return o>=i;case L.LTE:return o<=i;case L.IN:return Array.isArray(i)?i.includes(o):!1;case L.ADD:if(typeof o!="number"||typeof i!="number")throw new oe(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case L.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new oe(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Bn=(e,t,r,n)=>{let o=e.op===Je.NOT?_e(e.operand,t,r,n):$(e.operand,t,r,n);if(e.op===Je.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},ts=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(K(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let c={};for(let a of s.properties){let l=a.parsedKey?$(a.parsedKey,t,r,n):a.key,d=a.value;if(d.type===m.LITERAL)c[l]=d.value;else if(d.type===m.VARIABLE)c[l]=K(d.path,r,n);else if(d.type===m.INTERPOLATION){let u=[];for(let f of d.parts)if(typeof f=="string")u.push(f);else if(f.type===m.VARIABLE){let p=K(f.path,r,n);u.push(p!=null?String(p):"")}else{let p=$(f,t,r,n);u.push(p!=null?String(p):"")}c[l]=u.join("")}else c[l]=$(d,t,r,n)}return c}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let c={};for(let a of s.properties){let l=a.parsedKey?$(a.parsedKey,t,r,n):a.key,d=a.value;if(d.type===m.LITERAL)c[l]=d.value;else if(d.type===m.VARIABLE)c[l]=K(d.path,r,n);else if(d.type===m.INTERPOLATION){let u=[];for(let f of d.parts)if(typeof f=="string")u.push(f);else if(f.type===m.VARIABLE){let p=K(f.path,r,n);u.push(p!=null?String(p):"")}else{let p=$(f,t,r,n);u.push(p!=null?String(p):"")}c[l]=u.join("")}else c[l]=$(d,t,r,n)}return c}}}return null},rs=(e,t,r,n)=>{let o=ts(e,t,r,n);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||_e(s,t,r,n))return $(e.bodies[i],t,r,n)}return zn},ns=(e,t)=>{let r=e.body,n=e.itemVar;if(r.type===m.CONDITIONAL&&r.conditions.length===1&&r.conditions[0].type===m.VARIABLE){let o=r.conditions[0].path,i=r.bodies[0];if(o.startsWith(n+".")){let s=o.substring(n.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let a of i.properties)if(a.parsedKey)return null;let c=[];for(let a=0;a<t.length;a++){let l=t[a];if(l[s]){let d={};for(let u of i.properties){let f=u.key,p=u.value;if(p.type===m.LITERAL)d[f]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)d[f]=l;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);d[f]=l[g]}else return null}else if(p.type===m.INTERPOLATION){let h=[],g=!0;for(let y of p.parts)if(typeof y=="string")h.push(y);else if(y.type===m.VARIABLE){let b=y.path;if(b===n)h.push(l!=null?String(l):"");else if(b.startsWith(n+".")){let A=b.substring(n.length+1),v=l[A];h.push(v!=null?String(v):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;d[f]=h.join("")}else return null}c.push(d)}}return c}}}return null},os=(e,t)=>{let r=e.body,n=e.itemVar,o=ns(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let c of r.properties)if(c.parsedKey)return null;let i=[],s=!0;for(let c of r.properties){let a=c.key,l=c.value;if(l.type===m.LITERAL)i.push({key:a,type:"literal",value:l.value});else if(l.type===m.VARIABLE){let d=l.path;if(d===n)i.push({key:a,type:"item"});else if(d.startsWith(n+".")){let u=d.substring(n.length+1);if(!u.includes(".")&&!u.includes("["))i.push({key:a,type:"prop",prop:u});else{s=!1;break}}else{s=!1;break}}else if(l.type===m.INTERPOLATION&&l.parts.length===1){let d=l.parts[0];if(d.type===m.VARIABLE){let u=d.path;if(u===n)i.push({key:a,type:"item_string"});else if(u.startsWith(n+".")){let f=u.substring(n.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:a,type:"prop_string",prop:f});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let c=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let a=0;a<t.length;a++){let l=t[a];c[a]={id:l.id,title:l.title!=null?String(l.title):"",completed:l.completed}}else for(let a=0;a<t.length;a++){let l=t[a],d={};for(let u of i)if(u.type==="literal")d[u.key]=u.value;else if(u.type==="item")d[u.key]=l;else if(u.type==="prop")d[u.key]=l[u.prop];else if(u.type==="item_string")d[u.key]=l!=null?String(l):"";else if(u.type==="prop_string"){let f=l[u.prop];d[u.key]=f!=null?String(f):""}c[a]=d}return c}}return null},is=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let c=e.itemVar,a=e.indexVar;for(let l=0;l<o.length;l++){let d=o[l],u={},f={...n,[c]:d,...a&&{[a]:l}};f.__paths__||(f.__paths__=n.__paths__||{});let p=e.iterable.path||"";if(n&&n.__paths__&&p){let h=p.split("."),g=h[0];g in n.__paths__&&(p=n.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}f.__paths__={...f.__paths__,[c]:`${p}[${l}]`,...a&&{[a]:l}};for(let h of s.properties){let g=h.parsedKey?$(h.parsedKey,t,r,f):h.key,y=h.value;if(y.type===m.LITERAL)u[g]=y.value;else if(y.type===m.VARIABLE){let b=y.path;if(b===c)u[g]=d;else if(b===a)u[g]=l;else if(b.startsWith(c+".")){let A=b.substring(c.length+1);!A.includes(".")&&!A.includes("[")?u[g]=d[A]:u[g]=K(b,r,{...n,[c]:d,...a&&{[a]:l}})}else u[g]=K(b,r,{...n,[c]:d,...a&&{[a]:l}})}else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let v=A.path,_;if(v===c)_=d;else if(v===a)_=l;else if(v.startsWith(c+".")){let P=v.substring(c.length+1);!P.includes(".")&&!P.includes("[")?_=d[P]:_=K(v,r,{...n,[c]:d,...a&&{[a]:l}})}else _=K(v,r,{...n,[c]:d,...a&&{[a]:l}});b.push(_!=null?String(_):"")}else{let v={...n,[c]:d,...a&&{[a]:l}},_=$(A,t,r,v);b.push(_!=null?String(_):"")}u[g]=b.join("")}else{let b={...n,[c]:d,...a&&{[a]:l}};u[g]=$(y,t,r,b)}}i.push(u)}return i}return null},ss=(e,t,r)=>{let n=e.body;if(n.type===m.OBJECT&&n.properties.length===1&&n.properties[0].key==="$if item.visible"){let i=n.properties[0].value;if(i.type===m.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===m.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===m.OBJECT&&s.properties.length===2){let c=s.properties[0],a=s.properties[1];if(c.key==="id"&&c.value.type===m.VARIABLE&&c.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===m.CONDITIONAL){let l=[];for(let d=0;d<t.length;d++){let u=t[d];if(u.visible){let f={id:u.id};u.highlighted?(f.highlight=!0,f.message=`This item is highlighted: ${u.name}`):(f.highlight=!1,f.message=u.name),l.push(f)}}return l}}}}return null},as=(e,t,r,n)=>{let o=$(e.iterable,t,r,n);if(!Array.isArray(o)){let l,d=!1;if(e.iterable.type===m.FUNCTION){d=!0;let f=e.iterable.args.map(p=>p.type===m.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===m.VARIABLE?p.path:p.type===m.FUNCTION?`${p.name}(...)`:"?").join(", ");l=`${e.iterable.name}(${f})`}else l=e.iterable.path||"undefined";let u=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw Vn(u,o,d)}if(!e.indexVar){let l=ss(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=os(e,o);if(l!==null)return l}let i=is(e,t,r,n,o);if(i!==null)return i;let s=[],c=e.iterable.path||"";if(n&&n.__paths__&&c){let l=c.split("."),d=l[0];d in n.__paths__&&(c=n.__paths__[d],l.length>1&&(c+="."+l.slice(1).join(".")))}let a=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(l=>l.type===m.OBJECT&&l.properties.some(d=>d.key.startsWith("$if ")||d.key.startsWith("$when "))));for(let l=0;l<o.length;l++){let d=e.indexVar?{...n,[e.itemVar]:o[l],[e.indexVar]:l}:{...n,[e.itemVar]:o[l]};d.__paths__||(d.__paths__=n.__paths__||{}),d.__paths__={...d.__paths__,[e.itemVar]:`${c}[${l}]`},e.indexVar&&(d.__paths__[e.indexVar]=l);let u=$(e.body,t,r,d);if(Array.isArray(u)&&u.length===1&&!a){let f=u[0];s.push(f===void 0?{}:f)}else s.push(u===void 0?{}:u)}return s},cs=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?$(o.parsedKey,t,r,n):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let c={},a={},l=!0;for(let d of s.properties){let u=d.parsedKey?$(d.parsedKey,t,r,n):d.key,f=d.value;if(f.type===m.LITERAL)a[u]=f.value;else if(f.type===m.VARIABLE)a[u]=K(f.path,r,n);else if(f.type===m.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=K(h.path,r,n);p.push(g!=null?String(g):"")}else{l=!1;break}if(!l)break;a[u]=p.join("")}else if(f.type===m.OBJECT&&f.properties.length<=5){let p={};for(let h of f.properties){let g=h.key,y=h.value;if(y.type===m.LITERAL)p[g]=y.value;else if(y.type===m.VARIABLE)p[g]=K(y.path,r,n);else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let v=K(A.path,r,n);b.push(v!=null?String(v):"")}else{l=!1;break}if(!l)break;p[g]=b.join("")}else{l=!1;break}}if(!l)break;a[u]=p}else{l=!1;break}}if(l)return c[i]=a,c}}return null},ls=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!_e(e.whenCondition,o,r,n))return;let i=cs(e,t,r,n);if(i!==null)return i;if(e.fast){let l={};for(let d of e.properties){let u=d.parsedKey?$(d.parsedKey,t,r,n):d.key,f=d.value;if(f.type===m.LITERAL)l[u]=f.value;else if(f.type===m.VARIABLE)l[u]=K(f.path,r,n);else if(f.type===m.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=K(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=$(h,t,r,n);p.push(g!=null?String(g):"")}l[u]=p.join("")}else l[u]=$(f,t,r,n)}return l}let s={},c=null,a=!1;for(let l of e.properties)if(!l.key.startsWith("$if ")&&!l.key.match(/^\$if\s+\w+.*:?$/)&&!l.key.startsWith("$elif")&&!l.key.startsWith("$else")&&!l.key.startsWith("$for ")){a=!0;break}for(let l of e.properties)if(l.key.startsWith("$if ")||l.key.match(/^\$if\s+\w+.*:?$/)){let d=$(l.value,t,r,n);if(!a&&d!==null&&d!==void 0)return Array.isArray(d)&&d.length===1?d[0]:d;typeof d=="object"&&d!==null&&!Array.isArray(d)&&Object.assign(s,d)}else if(l.key.startsWith("$for ")){if(e.properties.length===1)return $(l.value,t,r,n)}else{let d=l.value;if(d&&d.type===m.OBJECT&&d.properties){let u=d.properties.find(f=>f.key.startsWith("$for "));if(u){let f=$(u.value,t,r,n);f!==void 0&&(s[l.key]=f)}else{let f=$(l.value,t,r,n);f!==void 0&&(s[l.key]=f)}}else{let u=l.parsedKey?$(l.parsedKey,t,r,n):l.key,f=$(l.value,t,r,n);f!==void 0&&(s[u]=f)}}return s},zn={},us=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=$(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=$(i,t,r,n);s!==zn&&s!==void 0&&o.push(s)}return o},ds=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,c=t.partials||{},a=t.functions||t;if(s&&!_e(s,a,r,n))return;if(!c[o])throw new oe(`Partial '${o}' is not defined`);let l=n._partialStack||[];if(l.includes(o))throw new oe(`Circular partial reference detected: ${o}`);let d=c[o],u=r,f={...n,_partialStack:[...l,o]};if(n){u={...r};for(let p of Object.keys(n))p.startsWith("_")||(u[p]=n[p])}if(i){let p=$(i,t,r,n);u={...u,...p}}return $(d,t,u,f)},fs=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],c=i.slice(1);if(!n||!(s in n))throw new oe(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(n.__paths__||(n.__paths__={}),!(s in n.__paths__))throw new oe(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=n.__paths__[s];if(typeof a=="number"){if(c.length>0)throw new oe(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return c.length>0&&(a+="."+c.join(".")),a};var yr=Qi;var ps=/\$\{([^}]*)\}/g,hs=/#\{([^}]*)\}/g,qn=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=ms(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},ms=(e,t={})=>e.trim()?gs(e).map(n=>ys(n.trim(),t)):[],gs=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let c=e[s],a=s>0?e[s-1]:"";!o&&(c==='"'||c==="'")?(o=!0,i=c,r+=c):o&&c===i&&a!=="\\"?(o=!1,i="",r+=c):!o&&c==="("?(n++,r+=c):!o&&c===")"?(n--,r+=c):!o&&c===","&&n===0?(t.push(r),r=""):r+=c}return r&&t.push(r),t},ys=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:m.LITERAL,value:parseFloat(e)};if(e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};let r=qn(e,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};let n=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:c,type:a}of o){let l=0;for(;l<n.length;){let d=je(n.substring(l),c);if(d===-1)break;let u=l+d;u>i&&(i=u,s={op:c,type:a}),l=u+c.length}}if(i!==-1)try{return X(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},Hn=/^\w+\(.*\)$/,bs=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Is=e=>{if(!(!e||e.trim()===""||Hn.test(e))&&bs.test(e))throw e.includes("?")&&e.includes(":")?new E(`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 E(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new E(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Wn=e=>{let t=e.trim();if(Hn.test(t))throw new E(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new E(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new E(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new E(`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 E(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:m.PATH_REFERENCE,path:t}},st=(e,t={})=>{let r=e.trim();Is(r);let n=qn(r,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};if(r.includes("[")&&!/[\s+\-*/%|&?:]/.test(r)){let o=0;for(let i of r)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:r}},br=(e,t={})=>{let r=e,n=[];(e.includes("\\${")||e.includes("\\#{"))&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),r=r.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(l,d)=>{let u=`__ESCAPED_${n.length}__`;return n.push(d),u}),r=r.replace(/\\(#\{[^}]*\})/g,(l,d)=>{let u=`__ESCAPED_${n.length}__`;return n.push(d),u}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(ps)],i=[...r.matchAll(hs)],s=[...o.map(l=>({match:l,type:"variable"})),...i.map(l=>({match:l,type:"pathref"}))].sort((l,d)=>l.match.index-d.match.index);if(s.length===0){let l=r;for(let d=0;d<n.length;d++)l=l.replace(`__ESCAPED_${d}__`,n[d]);return{type:m.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:l,type:d}=s[0];try{return d==="variable"?st(l[1],t):Wn(l[1])}catch(u){if(u.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw u}}let c=[],a=0;for(let{match:l,type:d}of s){let[u,f]=l,p=l.index;if(p>a){let h=r.substring(a,p);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&c.push(h)}try{let h;d==="variable"?h=st(f.trim(),t):h=Wn(f.trim()),c.push(h)}catch(h){if(h.message==="Invalid array index syntax")c.push(u);else throw h}a=p+u.length}if(a<r.length){let l=r.substring(a);for(let d=0;d<n.length;d++)l=l.replace(`__ESCAPED_${d}__`,n[d]);l&&c.push(l)}return{type:m.INTERPOLATION,parts:c}};var wr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Gn=e=>Object.keys(e),re=e=>e.join("."),Re=(e,t,r)=>{let n=Gn(e).filter(o=>!t.has(o));if(n.length>0)throw new E(`Unexpected key '${n[0]}' in condition JSON at '${re(r)}'`)},Oe=(e,t)=>typeof e=="string"?br(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?ws(e,t):Es(e,t):{type:m.LITERAL,value:e},As=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new E("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new E("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new E("Empty $each body not allowed");if(r.$partial!==void 0)throw new E("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${n}`]:r}},ws=(e,t)=>{let r=[],n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let a=As(i),l=Object.keys(a);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let d=Kn(l[0],a[l[0]],t,!0);r.push(d),n=!0;continue}}catch(a){throw a instanceof E?a:new E(a.message)}let c=Object.keys(i);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let a=Kn(c[0],i[c[0]],t);r.push(a),n=!0;continue}}let s=Oe(i,t);r.push(s),(s.type===m.FUNCTION||s.type===m.CONDITIONAL||s.type===m.LOOP||s.type===m.PARTIAL||s.type===m.OBJECT&&!s.fast||s.type===m.ARRAY&&!s.fast)&&(n=!0)}return{type:m.ARRAY,items:r,fast:!n}},Es=(e,t)=>{let r=[],n=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new E("$partial value must be a string");if(e.$partial.trim()==="")throw new E("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],l=[];for(let[b]of i)for(let A of a)if(b===A||b.startsWith(A+" ")||b.startsWith(A+"#")){l.push(A);break}if(l.length>0)throw new E(`Cannot use $partial with ${l.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:d,$when:u,...f}=e,p={},h=!1;for(let[b,A]of Object.entries(f)){let v=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(v=b.slice(1)),p[v]=A,h=!0}let g=null;if(h&&(g=Oe(p,t),g.type===m.OBJECT)){let b=!1;for(let A of g.properties)if(A.value.type===m.VARIABLE||A.value.type===m.INTERPOLATION||A.value.type===m.FUNCTION||A.value.type===m.CONDITIONAL||A.value.type===m.OBJECT&&!A.value.fast||A.value.type===m.ARRAY&&!A.value.fast){b=!0;break}b&&(g.fast=!1)}let y={type:m.PARTIAL,name:d,data:g};return u!==void 0&&(y.whenCondition=Yn(u,t)),y}for(let[a,l]of i)if(a==="$when"){if(o!==null)throw new E("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new E("Missing condition expression after '$when'");o=Yn(l,t),n=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new E("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[a,l]=i[s];if(a==="$when"){s++;continue}if(a==="$each")throw new E("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let d=vs(i,s,t);r.push({key:a,value:d.node}),n=!0,s=d.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let d=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",u=d?`:${d}`:"";throw new E(`$for loops must be inside arrays - use '- $for${u} item in items:' instead of '$for${u} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(a.startsWith("$elif ")||a.startsWith("$else"))throw new E(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new E("Missing condition expression after '$if'");{let d=Oe(l,t);(d.type===m.FUNCTION||d.type===m.CONDITIONAL||d.type===m.PARTIAL||d.type===m.OBJECT&&!d.fast||d.type===m.ARRAY&&!d.fast)&&(n=!0);let u=br(a,t),f={key:a,value:d};(u.type!==m.LITERAL||u.value!==a)&&(f.parsedKey=u),r.push(f),s++}}}let c={type:m.OBJECT,properties:r,fast:!n};return o&&(c.whenCondition=o),c},vs=(e,t,r={})=>{let n=[],o=[],i=t,[s,c]=e[i],a=null,l;if(s.startsWith("$if#")){let u=s.match(/^\$if#(\w+)\s+(.+)$/);if(u)a=u[1],l=u[2];else throw new E(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());gr(l);let d=X(l,r);for(n.push(d),o.push(Oe(c,r)),i++;i<e.length;){let[u,f]=e[i],p=!1,h;if(a?u.startsWith(`$elif#${a} `)?(h=u.substring(`$elif#${a} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(u===`$else#${a}`||u===`$else#${a}:`)&&(p=!0,h=null):u.startsWith("$elif ")?(h=u.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(u==="$else"||u==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{gr(h);let g=X(h,r);n.push(g)}if(o.push(Oe(f,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:a},nextIndex:i}},Ir={eq:L.EQ,neq:L.NEQ,gt:L.GT,gte:L.GTE,lt:L.LT,lte:L.LTE,in:L.IN,add:L.ADD,sub:L.SUBTRACT},Ar={all:L.AND,any:L.OR},xs=new Set(["var","literal","call","not",...Object.keys(Ir),...Object.keys(Ar)]),Cs=(e,t,r)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${re(r)}' requires an array`);if(e.length!==2)throw new E(`Condition JSON operator '${t}' at '${re(r)}' requires exactly 2 operands`);return e},Ss=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${re(o)}' requires an array`);if(e.length===0)throw new E(`Condition JSON operator '${t}' at '${re(o)}' requires at least 1 condition`);return e.map((s,c)=>Ie(s,n,[...o,c])).reduce((s,c)=>({type:m.BINARY,op:r,left:s,right:c}))},_s=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],Re(e,new Set(["call","args"]),r);else if(wr(e.call))n=e.call.name,o=e.call.args??[],Re(e,new Set(["call"]),r),Re(e.call,new Set(["name","args"]),[...r,"call"]);else throw new E(`Condition JSON call at '${re(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new E(`Condition JSON call at '${re(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new E(`Invalid condition JSON function name '${n}' at '${re(r)}'`);if(!Array.isArray(o))throw new E(`Condition JSON call '${n}' at '${re(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>Ie(i,t,[...r,"args",s]))}},Ie=(e,t={},r=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:m.LITERAL,value:e};if(Array.isArray(e))throw new E(`Condition JSON array at '${re(r)}' must be wrapped in an operator or { literal: [...] }`);if(!wr(e))throw new E(`Invalid condition JSON value at '${re(r)}'`);let n=Gn(e);if(n.length===0)throw new E(`Condition JSON object at '${re(r)}' must contain an operator`);let o=n.filter(s=>xs.has(s));if(o.length===0)throw new E(`Unknown condition JSON operator '${n[0]}' at '${re(r)}'`);if(o.length>1)throw new E(`Condition JSON at '${re(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(Re(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new E(`Condition JSON var at '${re(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return Re(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return _s(e,t,r);if(i==="not")return Re(e,new Set(["not"]),r),{type:m.UNARY,op:Je.NOT,operand:Ie(e.not,t,[...r,"not"])};if(i in Ar)return Re(e,new Set([i]),r),Ss(e[i],i,Ar[i],t,[...r,i]);if(i in Ir){Re(e,new Set([i]),r);let s=Cs(e[i],i,[...r,i]);return{type:m.BINARY,op:Ir[i],left:Ie(s[0],t,[...r,i,0]),right:Ie(s[1],t,[...r,i,1])}}throw new E(`Unknown condition JSON operator '${i}' at '${re(r)}'`)},Yn=(e,t={})=>{if(e==null)throw new E("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression after '$when'");return X(e,t)}return wr(e)||Array.isArray(e)?Ie(e,t):{type:m.LITERAL,value:e}},X=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let l=e.slice(1,-1),d=0,u=!0;for(let f=0;f<l.length;f++)if(l[f]==="("?d++:l[f]===")"&&d--,d<0){u=!1;break}if(u&&d===0)return X(l,t)}let r=je(e,"||");if(r!==-1)return{type:m.BINARY,op:L.OR,left:X(e.substring(0,r).trim(),t),right:X(e.substring(r+2).trim(),t)};let n=je(e,"&&");if(n!==-1)return{type:m.BINARY,op:L.AND,left:X(e.substring(0,n).trim(),t),right:X(e.substring(n+2).trim(),t)};let o=[{op:">=",type:L.GTE},{op:"<=",type:L.LTE},{op:"==",type:L.EQ},{op:"!=",type:L.NEQ},{op:">",type:L.GT},{op:"<",type:L.LT},{op:" in ",type:L.IN}];for(let{op:l,type:d}of o){let u=je(e,l);if(u!==-1)return{type:m.BINARY,op:d,left:X(e.substring(0,u).trim(),t),right:X(e.substring(u+l.length).trim(),t)}}let i=-1,s=null,c=[{op:" + ",type:L.ADD},{op:" - ",type:L.SUBTRACT}];for(let{op:l,type:d}of c){let u=0;for(;u<e.length;){let f=je(e.substring(u),l);if(f===-1)break;let p=u+f;p>i&&(i=p,s={op:l,type:d}),u=p+l.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:X(e.substring(0,i).trim(),t),right:X(e.substring(i+s.op.length).trim(),t)};let a=[" * "," / "," % "];for(let l of a)if(je(e,l)!==-1)throw new E(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:m.UNARY,op:Je.NOT,operand:X(e.substring(1).trim(),t)}:Jn(e,t)},je=(e,t)=>{let r=0,n=0;for(;n<=e.length-t.length;){if(e[n]==="(")r++;else if(e[n]===")")r--;else if(r===0&&e.substring(n,n+t.length)===t)return n;n++}return-1},Rs=e=>{if(e=e.trim(),e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:m.LITERAL,value:""};if(e==="{}")return{type:m.LITERAL,value:{}};if(e==="[]")return{type:m.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:m.LITERAL,value:t}:{type:m.VARIABLE,path:e}},Jn=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return st(r,t);let o=Rs(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return st(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Os=(e,t=!1)=>{let r=t?"$each":"$for";try{Nn(e)}catch(n){if(n instanceof E&&t){let o=n.message.replace(/\$for/g,"$each");throw new E(o.replace("Parse Error: ",""))}throw n}},Kn=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new E(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],c=i[2].trim();Os(c,n);let a=c.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let y=n?"$each":"$for";throw new E(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${c}')`)}let l=a[1].trim(),d=a[2].trim(),u,f=null;if(l.includes(",")){let y=l.split(",").map(b=>b.trim());if(y.length!==2)throw new E(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);u=y[0],f=y[1]}else u=l;let p=["this","undefined","null","true","false"];if(p.includes(u))throw new E(`Reserved variable name: ${u}`);if(f&&p.includes(f))throw new E(`Reserved variable name: ${f}`);let h=Jn(d,r),g=Oe(t,r);return{type:m.LOOP,itemVar:u,indexVar:f,iterable:h,body:g,flatten:s!=="nested"}};var Ls=(e,t={})=>{let{functions:r={}}=t;return Oe(e,r)},kt=Ls;var at={};Bi(at,{now:()=>$s});var $s=()=>Date.now();var ks=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...at,...n},s=kt(e,{functions:i}),c={};for(let[a,l]of Object.entries(o))c[a]=kt(l,{functions:i});return yr(s,t,{functions:i,partials:c})},ie=ks;var Ts=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Ds=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Ps=(e,t)=>{if(Ts(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression");return X(e,t)}return Ie(e,t)},Ns=(e,t={},r={})=>{let n=Ds(r),o={...at,...n},i=Ps(e,o);return!!_e(i,{functions:o,partials:{}},t,{})},Er=Ns;var lt=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return Er(e,t)},ro=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=a=>a,transformActionFirstArgument:c=a=>a}=r;for(let[a,l]of Object.entries(t))a!=="createInitialState"&&(a.startsWith("select")?o[a]=(...d)=>l(s(n),...d):i[a]=(...d)=>{let u;return n=mr(n,p=>{let h=l(c(p),...d);u=h!==void 0&&!ae(h)?h:void 0}),u});return{...o,...i}},Pt=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return mr(n,i=>{o.forEach(s=>{t.forEach(c=>{c(i,s)})})})};var Vs=(e,t)=>{if(e.default!==void 0)return e.default;let r=["number","boolean","string","object"];if(!r.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${r.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},de=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),ct=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),no=e=>{let t=ae(e)?Ve(e):e;return structuredClone(t)},js=({characterId:e,resourceCharacter:t,variables:r={}}={})=>{if(!de(t,"nameVariableId"))return;let n=t.nameVariableId,o=r?.[n];if(typeof o!="string")throw new Error(`Character "${e}" nameVariableId "${n}" must resolve to a string variable`);return o},Nt=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0;if(t?.name!==void 0)return t.name;if(r!==void 0)return r;let s=js({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},Le=e=>de(e,"computed"),Xe=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Le(t[r]))),Ms=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),vr=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},Fs=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=Ms(e),[n,o,...i]=r;if(n==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return vr(s,i)}return n==="runtime"?vr(t.runtime,r.slice(1)):vr(t,r)},Us=(e,t,r)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(r!==void 0&&t.length!==r)throw new Error(`Computed expression operator "${e}" requires ${r} operand(s)`)},Xn=(e,t)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(t.length===0)throw new Error(`Computed expression operator "${e}" requires at least one operand`)},Bs=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},me=(e,t,r,n)=>(Us(e,t,n),t.map(o=>Dt(o,r))),ue=(e,t,r,n)=>{let o=me(e,t,r,n);return o.forEach(i=>Bs(e,i)),o},zs=(e,t,r)=>{switch(e){case"var":return Fs(t,r);case"add":{let[n,o]=ue(e,t,r,2);return n+o}case"sub":{let[n,o]=ue(e,t,r,2);return n-o}case"mul":{let[n,o]=ue(e,t,r,2);return n*o}case"div":{let[n,o]=ue(e,t,r,2);return n/o}case"mod":{let[n,o]=ue(e,t,r,2);return n%o}case"neg":{let[n]=ue(e,t,r,1);return-n}case"round":{let[n]=ue(e,t,r,1);return Math.round(n)}case"floor":{let[n]=ue(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=ue(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=ue(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=ue(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=ue(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=me(e,t,r,2);return n==o}case"neq":{let[n,o]=me(e,t,r,2);return n!=o}case"gt":{let[n,o]=me(e,t,r,2);return n>o}case"gte":{let[n,o]=me(e,t,r,2);return n>=o}case"lt":{let[n,o]=me(e,t,r,2);return n<o}case"lte":{let[n,o]=me(e,t,r,2);return n<=o}case"in":{let[n,o]=me(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return Xn(e,t),t.every(n=>!!Dt(n,r));case"or":case"any":return Xn(e,t),t.some(n=>!!Dt(n,r));case"not":{let[n]=me(e,t,r,1);return!n}case"length":{let[n]=me(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:ct(n)?Object.keys(n).length:0}case"includes":{let[n,o]=me(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return no(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},Dt=(e,t={})=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let r=Object.entries(e);if(r.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[n,o]]=r;return zs(n,o,t)},Ws=(e,t={})=>lt(e,{variables:t.variables,runtime:t.runtime}),qs=(e,t)=>{if(!ct(e))throw new Error(`${t} must be an object`);let r=de(e,"expr"),n=de(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},xr=(e,t,r)=>(qs(e,t),de(e,"value")?no(e.value):Dt(e.expr,r)),Hs=(e,t={},r="unknown")=>{if(!ct(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=de(e,"expr"),o=de(e,"value");if(de(e,"branches")){if(n||o)throw new Error(`Computed variable "${r}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${r}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${r}" branches must not be empty`);if(!ct(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let c=e.branches[s];if(!ct(c))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!de(c,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(Ws(c.when,t))return xr(c,`Computed variable "${r}" branch ${s}`,t)}return xr(e.default,`Computed variable "${r}" default`,t)}if(n===o)throw new Error(`Computed variable "${r}" must contain exactly one of expr, value, or branches`);return xr(e,`Computed variable "${r}"`,t)},Ys=(e,t,r)=>{switch(t){case"number":if(typeof r!="number"||!Number.isFinite(r))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(r)?"array":typeof r}`);return;case"boolean":if(typeof r!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(r)?"array":typeof r}`);return;case"string":if(typeof r!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(r)?"array":typeof r}`);return;case"object":if(r===null||typeof r!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof r}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},ut=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=Xe(e,r),i=Object.entries(r).filter(([,u])=>Le(u)).map(([u])=>u),s={},c=[],a=u=>{if(de(s,u))return s[u];let f=r[u];if(!Le(f))return o[u];let p=c.indexOf(u);if(p>=0){let h=[...c.slice(p),u].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}c.push(u);try{let h=Hs(f.computed,d,u);return Ys(u,f.type,h),s[u]=h,h}finally{c.pop()}},l=new Proxy({},{get:(u,f)=>{if(typeof f=="string")return a(f)},has:(u,f)=>typeof f=="string"&&(de(o,f)||i.includes(f)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(u,f)=>{if(!(typeof f!="string"||!de(o,f)&&!i.includes(f)))return{enumerable:!0,configurable:!0}}}),d={variables:l,runtime:t,resolveVariable:a};return n?(i.forEach(u=>{a(u)}),{...o,...s}):l},Ks=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>ut({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),Vt=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(Le(o))return;let i=Vs(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},jt=(e,t)=>{let r=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!r.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${r.join(", ")}`)},Mt=(e,t,r)=>{let n={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=n[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${r}`);if(!Object.values(n).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${r}" of type "${e}". Valid operations: ${o.join(", ")}`)},Gs=2,Qn=12,oo=(e=Gs)=>{if(!Number.isInteger(e)||e<0||e>Qn)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${Qn}.`);return e},Js=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},Tt=e=>typeof e=="number"&&Number.isFinite(e),_r=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!Tt(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!Tt(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!Tt(r))throw new Error(`Operation "divide" requires value to be a number for variable "${n}".`);if(t==="divide"){if(r===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${n}".`);oo(o.roundTo)}}},Ft=(e,t,r,n={})=>{let o=(s,c,a)=>{let l=s??c;if(!Tt(l))throw new Error(`Operation "${t}" requires ${a} to be a number.`);return l},i=s=>{let c=o(s,void 0,"value");if(c===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return c};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return Js(o(e,0,"current value")/i(r),oo(n.roundTo));case"increment":return o(e,0,"current value")+o(r,1,"value");case"decrement":return o(e,0,"current value")-o(r,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var io=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let r=new Date(e),n=o=>String(o).padStart(2,"0");return t.replace("DD",n(r.getDate())).replace("MM",n(r.getMonth()+1)).replace("YYYY",r.getFullYear()).replace("YY",String(r.getFullYear()).slice(-2)).replace("HH",n(r.getHours())).replace("mm",n(r.getMinutes())).replace("ss",n(r.getSeconds()))},Xs=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let c=i.character?.sprite;return c&&Object.keys(c).length>0&&(s.sprite=c),Object.keys(s).length>0?s:void 0},n=r(e),o=r(t);return JSON.stringify(n)===JSON.stringify(o)?null:n&&!o?{changeType:"delete",data:e}:o&&!n?{changeType:"add",data:t}:o&&n?{changeType:"update",data:t}:null},Zn=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};e.transformId!==void 0&&(t.transformId=e.transformId);for(let r of["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"])e[r]!==void 0&&(t[r]=e[r]);return e.loop!==void 0&&(t.loop=e.loop),t},eo=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},to=(e,t)=>t&&!e?{changeType:"add",data:t}:e&&!t?{changeType:"delete",data:e}:e&&t&&JSON.stringify(e)!==JSON.stringify(t)?{changeType:"update",data:t}:null,Qs=(e,t)=>{let r={},n=to(Zn(e),Zn(t)),o=to(eo(e),eo(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},Rr=(e={},t={})=>{let r={},n=["sfx","voice"],o=c=>{let a=e[c],l=t[c];l&&!a?r[c]={changeType:"add",data:l}:a&&!l?n.includes(c)||(r[c]={changeType:"delete",data:a}):a&&l&&JSON.stringify(a)!==JSON.stringify(l)&&(r[c]={changeType:"update",data:l})},i=Qs(e.background,t.background);i&&(r.background=i),o("screen"),o("bgm"),o("voice");let s=Xs(e.dialogue,t.dialogue);return s&&(r.dialogue=s),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),r},Or=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,!t.background.resourceId&&!t.background.colorId&&delete t.background);let r=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};r("layout"),r("choice"),r("form"),r("screen"),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),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let n=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(c=>{let a={...c};return delete a.animations,i(a)?a:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return n("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),n("visual",o=>o.resourceId||o.transformId),t},Zs=(e,t)=>{if(!e||!t)return;let r=e;for(let n of t.split(".")){if(r==null||!(n in Object(r)))return;r=r[n]}return r},ea=(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 r=e.slice(7),n=Zs(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},ta={conditional:new Set(["branches"]),updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"]),form:new Set(["submitActions","cancelActions"]),submitForm:new Set(["actions"]),cancelForm:new Set(["actions"])},so=(e,t)=>{let r=e[e.length-1];return r?ta[r]?.has(t)===!0:!1},Cr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Cr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,so(r,n)?o:Cr(o,t,[...r,n])])):ea(e,t),Sr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Sr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,so(r,n)?o:Sr(o,t,[...r,n])])):typeof e=="string"?ie(e,t):e,Lr=(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 r=Cr(e,t._event);return Sr(r,t)};var Q=e=>structuredClone(ae(e)?Ve(e):e),B=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),ao=e=>e?.animations?.playback?.continuity==="persistent",N=(e,t)=>B(e??{},t)&&e[t]!==void 0,dt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:Q(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},ra=e=>N(e,"opacity")||N(e,"blur"),uo=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],fo=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],na=e=>uo.some(t=>N(e,t)),po=e=>e?.text&&N(e.text,"content")&&N(e.text,"textStyleId"),ho=e=>N(e,"text"),oa=(e,t)=>e.resourceId?!0:po(e)?!t?.text:!1,ia=(e,t)=>{let r={...Q(e),...t};return t.text&&e.text&&(r.text={...Q(e.text),...Q(t.text)}),r},sa=(e,t)=>{if(ho(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!po(e)&&!t?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},co=e=>fo.some(t=>N(e,t)),aa=(e,t,{hasAuthoredTransformId:r=!1}={})=>{if(!t)return e;for(let n of fo)!r&&!N(e,n)&&N(t,n)&&(e[n]=t[n]),B(e,n)&&e[n]===void 0&&delete e[n];return e},mo=(e,t,r)=>{let n=e[r];return n?.id===t?.id?n:e.find(o=>o.id===t?.id)},ca=(e,t)=>{if(!t)return e;for(let r of uo)!N(e,r)&&N(t,r)&&(e[r]=t[r]),B(e,r)&&e[r]===void 0&&delete e[r];return e},la=(e,t)=>(t&&(!N(e,"opacity")&&N(t,"opacity")&&(e.opacity=t.opacity),!N(e,"blur")&&N(t,"blur")&&(e.blur=Q(t.blur)),B(e,"opacity")&&e.opacity===void 0&&delete e.opacity,B(e,"blur")&&e.blur===void 0&&delete e.blur),e),go=(e,t,r=[],{hasPatchFn:n=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,c)=>{let a=mo(r,s,c),l=t(s,a),d=ra(s),u=na(s),f=n(s),p=B(s,"animations"),h=Q(s);return!l&&(d||u||f)&&a&&(h=o?o(a,h):{...Q(a),...h},p||delete h.animations),la(ca(h,a),a)}).filter(s=>t(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},ua=e=>{if(e){if(e.character&&B(e.character,"name"))return e.character.name;if(B(e,"characterName"))return e.characterName}},yo=e=>!!e?.character&&B(e.character,"sprite"),da=e=>{let t={},r=!1,n=ua(e);return n!==void 0&&(t.name=n,r=!0),yo(e)&&(t.sprite=Q(e.character.sprite),r=!0),r?t:void 0},lo=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},fa=({dialogueState:e,content:t,append:r=!1})=>{if(!r||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let n=Array.isArray(e.content)?e.content:[];n.length>0?e.initialRevealedContent=n.map(o=>Q(o)):delete e.initialRevealedContent,e.content=[...n,...t]},pa=()=>({}),ha=(e,t)=>{if(!t.screen)return;let r=N(t.screen,"opacity"),n=N(t.screen,"blur"),o=B(t.screen,"animations");if(!r&&!n){o||delete e.screen;return}let i=e.screen,s={};if(r?s.opacity=t.screen.opacity:N(i,"opacity")&&(s.opacity=i.opacity),n?s.blur=Q(t.screen.blur):N(i,"blur")&&(s.blur=Q(i.blur)),B(s,"opacity")&&s.opacity===void 0&&delete s.opacity,B(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},ma=(e,t)=>{if(t.background){let r=N(t.background,"resourceId"),n=N(t.background,"colorId"),o=N(t.background,"opacity"),i=N(t.background,"blur"),s=N(t.background,"transformId"),c=co(t.background),{animationsOnly:a,state:l}=dt(t.background,f=>N(f,"resourceId")||N(f,"colorId")||N(f,"opacity")||N(f,"blur")||N(f,"transformId")||co(f));if(a){e.background=e.background?{...Q(e.background),...l}:l;return}if(!r&&!n&&!o&&!i&&!s&&!c){delete e.background;return}let d=e.background,u=Q(t.background);if(!r&&d?.resourceId&&(u.resourceId=d.resourceId,!B(u,"transformId")&&d.transformId&&(u.transformId=d.transformId)),aa(u,d,{hasAuthoredTransformId:s}),!n&&d?.colorId&&(u.colorId=d.colorId),!o&&N(d,"opacity")&&(u.opacity=d.opacity),!i&&N(d,"blur")&&(u.blur=Q(d.blur)),B(u,"resourceId")&&u.resourceId===void 0&&delete u.resourceId,B(u,"colorId")&&u.colorId===void 0&&delete u.colorId,B(u,"animations")&&u.animations===void 0&&delete u.animations,B(u,"transformId")&&u.transformId===void 0&&delete u.transformId,B(u,"opacity")&&u.opacity===void 0&&delete u.opacity,B(u,"blur")&&u.blur===void 0&&delete u.blur,!u.resourceId&&!u.colorId){delete e.background;return}d?.resourceId===u.resourceId&&d?.transformId===u.transformId&&!B(u,"animations")&&ao(d)&&(u.animations=Q(d.animations)),e.background=u}else e.background?.animations&&!ao(e.background)&&(e.background.animations={})},ga=(e,t)=>{if(!t.dialogue){e.dialogue&&(lo(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,delete e.dialogue.textSpeed,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let r=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:l,state:d}=dt(t.dialogue.ui,u=>!!u.resourceId);l?e.dialogue.ui={...e.dialogue.ui,...d}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});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");let n=t.dialogue.append===!0&&r!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&fa({dialogueState:e.dialogue,content:t.dialogue.content,append:n}),B(t.dialogue,"textSpeed")?e.dialogue.textSpeed=t.dialogue.textSpeed:delete e.dialogue.textSpeed;let o=B(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=B(t.dialogue,"characterId"),s=da(t.dialogue),c=s!==void 0,a=yo(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,c?e.dialogue.character=!i&&o&&e.dialogue.character?{...Q(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,a||lo(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let l={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.textSpeed!==void 0&&(l.textSpeed=e.dialogue.textSpeed),e.dialogue.character&&(l.character=Q(e.dialogue.character)),e.dialogue.lines.push(l)}},ya=(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},ba=(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}}},Ia=(e,t)=>{if(t.visual){let r=e.visual?.items||[];t.visual.items?.forEach((i,s)=>{sa(i,mo(r,i,s))});let{hasValidItems:n,processedItems:o}=go(t.visual.items,oa,r,{hasPatchFn:ho,mergeItemFn:ia});n?e.visual={items:o}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(r=>r.animations?{...r,animations:{}}:r))},Aa=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:r,processedItems:n}=go(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);r?e.character={items:n}:delete e.character},wa=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Ea=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=dt(t.layout,o=>!!o.resourceId);if(r){e.layout=n;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},va=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=dt(t.choice,o=>!!o.resourceId);if(r){e.choice={...e.choice,...n};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},xa=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=dt(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=Q(t.form)}else e.form&&delete e.form},Ca=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},Sa=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},_a=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},Me=e=>Pt(pa,[_a,ha,ma,ya,ba,Ia,ga,Aa,wa,Ea,va,xa,Ca,Sa])(e);var Ra=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},skipUnseenText:{source:"global.skipUnseenText"},skipTransitionsAndAnimations:{source:"global.skipTransitionsAndAnimations"},soundVolume:{source:"global.soundVolume"},musicVolume:{source:"global.musicVolume"},muteAll:{source:"global.muteAll"},saveLoadPagination:{source:"context.runtime.saveLoadPagination"},menuPage:{source:"context.runtime.menuPage"},menuEntryPoint:{source:"context.runtime.menuEntryPoint"},autoMode:{source:"global.autoMode"},skipMode:{source:"global.skipMode"},dialogueUIHidden:{source:"global.dialogueUIHidden"},isLineCompleted:{source:"global.isLineCompleted"}}),$e=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),ft=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),bo=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",skipUnseenText:"boolean",skipTransitionsAndAnimations:"boolean",soundVolume:"number",musicVolume:"number",muteAll:"boolean",saveLoadPagination:"number",menuPage:"string",menuEntryPoint:"string",autoMode:"boolean",skipMode:"boolean",dialogueUIHidden:"boolean",isLineCompleted:"boolean"}),$r=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),kr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Oa=(e,t)=>{if(t.startsWith("global.")){let r=t.slice(7);return e?.global?.[r]}if(t.startsWith("context.runtime.")){let r=t.slice(16),n=Array.isArray(e?.contexts)?e.contexts:[];return n[n.length-1]?.runtime?.[r]}},Fe=e=>Object.fromEntries(Object.entries(Ra).map(([t,r])=>{let n=Oa(e,r.source),o=n!==void 0?n:$e[t]??ft[t];return[t,o]})),Ee=(e,t)=>Fe(e)[t],Io=(e={})=>Object.fromEntries($r.map(t=>[t,e[t]??$e[t]]));var Qe=Object.freeze({VISUAL_BEHIND_BACKGROUND:10,BACKGROUND:20,VISUAL_BEHIND_CHARACTER:30,CHARACTER:40,VISUAL_BEHIND_DIALOGUE:50,DIALOGUE:60,VISUAL_BEHIND_CHOICE:70,CHOICE:80,VISUAL_FOREGROUND:90}),ve=Object.freeze({BEHIND_BACKGROUND:Qe.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:Qe.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:Qe.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:Qe.VISUAL_BEHIND_CHOICE,FOREGROUND:Qe.VISUAL_FOREGROUND}),Tr=ve.BEHIND_DIALOGUE,Dr=Object.freeze(Object.values(ve).sort((e,t)=>e-t));var xe={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:io},La=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,$a=(e,t)=>{let r=String(t||"").trim();if(!r)return;let n=r.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of n){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},zt=(e,t,r)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),c=La.exec(s);if(c){let[,a,l,d]=c,u=$a(t,d);if(!Array.isArray(u))continue;let f=Array.isArray(i[s])?i[s]:[];u.forEach((p,h)=>{let g={...t,[a]:p};l&&(g[l]=h),f.forEach(y=>{let b=zt(y,g,r),A=ie(b,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(zt(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=zt(i,t,r)}),n},Xr=({animationType:e,animationId:t,animationPath:r})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${r}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},ka=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);if(Xr({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n!==void 0){let s=Na(n,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},Ta=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Xr({animationType:e.type,animationId:t,animationPath:r}),e.type},Da=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Pa=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Na=(e,t="animation.playback")=>{if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`[${t}] playback must be an object.`);if(e.continuity!==void 0&&e.continuity!=="render"&&e.continuity!=="persistent")throw new Error(`[${t}] playback.continuity must be "render" or "persistent".`);if(e.speed!==void 0&&(typeof e.speed!="number"||!Number.isFinite(e.speed)||e.speed<=0))throw new Error(`[${t}] playback.speed must be a finite number greater than 0.`);let r={};return e.continuity!==void 0&&(r.continuity=e.continuity),e.speed!==void 0&&e.speed!==1&&(r.speed=e.speed),Object.keys(r).length>0?r:void 0},Va=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},Ue=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),To=e=>e?.playback?.continuity==="persistent",Fr=e=>Array.isArray(e)?e.map(Fr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=Fr(e[r]),t),{}),Wt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return t.playback&&(delete t.playback.continuity,t.playback.speed===1&&delete t.playback.speed,Object.keys(t.playback).length===0&&delete t.playback),JSON.stringify(Fr(t))},Do=(e=[])=>e.filter(t=>To(t)).map(t=>structuredClone(t)),Po=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,r)=>{let n=typeof r?.duration=="number"&&Number.isFinite(r.duration)?r.duration:0;return t+n},0):0,Pr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,Po(r)),0),No=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(Pr(e.tween),Pr(e.prev?.tween),Pr(e.next?.tween),Po(e.mask?.progress))/Va(e),Ao=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let r=new Set(t.map(Wt).filter(Boolean));return e.some(n=>{if(!To(n))return!1;let o=Wt(n);return o?r.has(o):!1})},ge=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||Ao({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:Ao({animationInstances:e,activePersistentAnimations:o}),ja=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Ma=(e,t)=>{if(ja(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},Fa=({resources:e,animationId:t,playback:r,instanceId:n,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?ka({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},Ua=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Xr({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},Qr=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(Ua(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Ur=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=ie(e,t);return r&&typeof r=="object"?e:r},Br=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(r=>r===null||typeof r!="object"||Array.isArray(r)))throw new Error(`${t} must be an array of objects`);return e},Ba=({content:e,path:t,variables:r})=>Br(e,t).reduce((n,o)=>{let i=Ur(o.text,{variables:r});return n+`${i??""}`.length},0),wo=(e=[])=>{let t=new Map;for(let r of e)r?.id&&t.set(r.id,(t.get(r.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,r])=>r>1).map(([r])=>r))},Ut=(e,t=0,r=new Set)=>{if(!r.has(e?.id))return`character-container-${e.id}`;let n=e?.sprites?.map(({resourceId:o})=>o)||[];return n.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${n.join("-")}`},Bt=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return r},za=(e,t={})=>{if(!t?.transformId)return;let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for background`);return r},Wa=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],qa=(e={})=>Wa.some(t=>Ue(e,t)),Ha=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},zr=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Ya=(e={})=>e.textStyles||{},Ka=(e={})=>e.images||{},Ga=.5,Ja=(e={},t,r)=>{if(t){if(!e.animations?.[t])throw new Error(`Animation '${t}' not found in spritesheet resource '${r}'`);return t}return Object.keys(e.animations??{})[0]},Xa=({id:e,resourceId:t,spritesheet:r,animationName:n,animationSpeed:o,loop:i,transform:s={}}={})=>{let c=Ja(r,n,t),a=c?r.animations?.[c]:void 0;if(!a){console.warn(`Spritesheet animation not found: ${t}`);return}return{id:e,type:"spritesheet-animation",...s,width:r.width,height:r.height,src:r.fileId,atlas:r.jsonData,playback:{frames:a.frames,animationSpeed:o??a.animationSpeed??Ga,loop:i??a.loop??!0}}},Vo=({id:e,item:t,resources:r={}}={})=>{let n=r.images?.[t.resourceId];if(n)return{type:"sprite",id:e,src:n.fileId,width:n.width,height:n.height,x:0,y:0};let o=r.spritesheets?.[t.resourceId];if(o)return Xa({id:e,resourceId:t.resourceId,spritesheet:o,animationName:t.animationName,animationSpeed:t.animationSpeed,loop:t.loop,transform:{x:0,y:0}});console.warn(`Character sprite resource not found: ${t.resourceId}`)},Qa=(e={})=>e.colors||{},Za=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,ht=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,et=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},Eo=(e,t,r)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);return e},Zr=(e,t)=>{if(typeof e!="string"||!Za.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(r=>r.repeat(2)).join("")}`:e},vo=(e,t,r)=>{let n=Zr(e,r);if(t===1)return n;let o=Number.parseInt(n.slice(1,3),16),i=Number.parseInt(n.slice(3,5),16),s=Number.parseInt(n.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},ec=(e={},t)=>{let r=Ya(e)?.[t];if(!r)throw new Error(`Text style "${t}" not found`);let n=e.fonts?.[r.fontId];if(!n)throw new Error(`Font "${r.fontId}" not found for text style "${t}"`);let o=e.colors?.[r.colorId];if(!o)throw new Error(`Color "${r.colorId}" not found for text style "${t}"`);let i=Eo(r.colorAlpha,"colorAlpha",t),s={fontFamily:n.fileId,fontSize:r.fontSize??16,fontWeight:r.fontWeight??"400",fontStyle:r.fontStyle??"normal",lineHeight:r.lineHeight??1.2,fill:vo(o.hex,i,`Color "${r.colorId}" for text style "${t}"`)};if(r.align!==void 0&&(s.align=r.align),r.wordWrap!==void 0&&(s.wordWrap=r.wordWrap),r.breakWords!==void 0&&(s.breakWords=r.breakWords),r.wordWrapWidth!==void 0&&(s.wordWrapWidth=r.wordWrapWidth),r.strokeColorId){let c=e.colors?.[r.strokeColorId];if(!c)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let a=Eo(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=vo(c.hex,a,`Stroke color "${r.strokeColorId}" for text style "${t}"`)}else if(r.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return r.strokeWidth!==void 0&&(s.strokeWidth=r.strokeWidth),s},Wr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Wr(o,t,`${r}[${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 "${r}". Use textStyleId instead`);let n={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(n[o]=Wr(i,t,ht(r,o)));return e.textStyleId!==void 0&&(et(e.textStyleId,r,"textStyleId"),n.textStyle=ec(t,e.textStyleId)),n},en=(e={},t)=>{let r=Qa(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return Zr(r.hex,`Color "${t}"`)},jo=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Nr=(e,t,r)=>{let n=e?.[t];if(!(!n||typeof n!="object"||Array.isArray(n))&&Object.prototype.hasOwnProperty.call(n,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${r}". Use ${jo(`${t}.fill`)} instead`)},tc=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>mt(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;let n={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(n[o]=mt(i,t,ht(r,o)));return e.colorId!==void 0&&(et(e.colorId,r,"colorId"),n.fill=en(t,e.colorId)),n},mt=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>mt(o,t,`${r}[${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 "${r}". Use ${jo("fill")} instead`);Nr(e,"hover",r),Nr(e,"click",r),Nr(e,"rightClick",r)}let n={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){n[o]=tc(i,t,ht(r,o));continue}n[o]=mt(i,t,ht(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(et(e.colorId,r,"colorId"),n.fill=en(t,e.colorId)),n},Vr=(e={},t)=>{let r=Ka(e)?.[t];return r||null},Mo=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",xo=(e,t,r,n)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,n))throw new Error(`Inline ${t}.${n} is not allowed in sprite layout elements at "${r}". Use ${Mo(`${t}.${n}`)} instead`)},Co=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},qr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>qr(o,t,`${r}[${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 "${r}". Use ${Mo(o)} instead`);xo(e,"hover",r,"src"),xo(e,"click",r,"src")}let n={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(n[o]=qr(i,t,ht(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){et(e.imageId,r,"imageId");let o=Vr(t,e.imageId),i=o?.fileId??e.imageId;n.src=i,n.width===void 0&&o?.width!==void 0&&(n.width=o.width),n.height===void 0&&o?.height!==void 0&&(n.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(et(e.hoverImageId,r,"hoverImageId"),Co(n,"hover",Vr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(et(e.clickImageId,r,"clickImageId"),Co(n,"click",Vr(t,e.clickImageId)?.fileId??e.clickImageId)),n},tn=(e,t={},r="root")=>qr(mt(Wr(e,t,r),t,r),t,r),Ce=tn,Be=(e=[])=>e.find(t=>t.id==="story"),rc="#000000",Hr="bg-cg-background-color",nc=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?Zr(r?.backgroundColor??rc,"screen.backgroundColor"):en(e,t.colorId),Fo=(e={})=>{if(Ue(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},oc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},So=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=Fo(e),n=oc(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},ic=(e={})=>{if(Ue(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},sc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Uo=(e={})=>{let t=ic(e),r=sc(e),n={};return t!==void 0&&(n.alpha=t),r&&(n.blur=r),n},pt=(e={})=>Uo(e),ke=(e={},t={})=>{let r={x:t.x??e.x,y:t.y??e.y,anchorX:t.anchorX??e.anchorX,anchorY:t.anchorY??e.anchorY,rotation:t.rotation??e.rotation,scaleX:t.scaleX??e.scaleX,scaleY:t.scaleY??e.scaleY},n=t.originX??e.originX,o=t.originY??e.originY;return n!==void 0&&(r.originX=n),o!==void 0&&(r.originY=o),r},ac=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],rn=(e={})=>e.text&&Ue(e.text,"content")&&Ue(e.text,"textStyleId"),_o=(e={})=>{if(e.resourceId)return e.resourceId;if(rn(e))return"text"},cc=e=>{if(e.text){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!rn(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let t of ac)if(Ue(e.text,t))throw new Error(`Visual item "${e.id}" text.${t} is reserved for the visual item`)}},lc=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:Hr,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:nc({resources:e,background:t,screen:r})};if(n){let i=Fo(t);i!==void 0&&(o.alpha=i)}return o},uc=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.layouts?.[t]):!1,Ro=({resources:e={},resourceId:t,colorId:r})=>{let n=Ha(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:zr({resourceId:t,kind:n})}:r!==void 0?{resourceId:Hr,targetId:Hr}:{resourceId:void 0,targetId:void 0}},Bo=100,Ht=Bo,zo=(e,t)=>e*t/Bo,dc=(e={},t=Ht)=>e?.muteAll?0:zo(t,e?.soundVolume??$e.soundVolume),fc=(e={},t=Ht)=>e?.muteAll?0:zo(t,e?.musicVolume??$e.musicVolume),pc=({item:e,index:t}={})=>`sfx:${t}:${e?.resourceId}`,ye=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,confirmDialog:u,form:f,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:b}={})=>{let A={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??c??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},v=bc({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e,runtime:A}),_={variables:e,runtime:A,saveSlots:r,isChoiceVisible:a,isFormVisible:l,canRollback:d,confirmDialog:u,form:f,historyDialogue:p,characters:h};return v&&(_.dialogue=v,_.dialogueLines=v.lines),_},Oo=100,qt=(e,t)=>{if(Array.isArray(e))return e.map(n=>qt(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=qt(r[n],t)}),r.type==="text-revealing"?t(r):r},hc=e=>qt(e,t=>({...t,revealEffect:"none"})),mc=e=>qt(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,Oo):Oo;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),Te=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?hc(e):r?mc(e):e,Wo=({id:e,screen:t={width:1920,height:1080}})=>({id:e,type:"rect",fill:"transparent",width:t.width,height:t.height,x:0,y:0,click:{payload:{actions:{}}}}),Yr=e=>{if(Array.isArray(e))return e.map(Yr);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Yr(s);let r=t.click?.payload;if(!r||typeof r!="object"||Array.isArray(r))return t;let n=r.actions,o=n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"nextLine")?{...n.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...r,bypassChoice:!0,...o?{actions:{...n,nextLine:o}}:{}}}}},gc=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),Lo="submit",jr=(e,t,r={})=>{let n=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},o=n.actions&&typeof n.actions=="object"?n.actions:{},i=r.replaceActions===!0?t:{...o,...t};return{...e||{},payload:{...n,actions:i}}},Kr=(e,t,r={})=>{if(Array.isArray(e))return e.map(l=>Kr(l,t,r));if(!e||typeof e!="object")return e;let n=typeof e.type=="string",o=n&&e.formRole===Lo,i=n&&r.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},c={};for(let[l,d]of Object.entries(e))c[l]=Kr(d,t,l==="children"?s:{});let a=c;if(a.type==="input"&&typeof a.field=="string"){let l=t?.fields?.[a.field];if(l){let d={updateFormField:{formKey:t.key,field:l.id,value:"_event.value"}};a={...a,value:l.value,placeholder:a.placeholder===void 0?l.placeholder:a.placeholder,multiline:a.multiline===void 0?l.multiline:a.multiline,...a.maxLength===void 0&&l.maxLength!==void 0?{maxLength:l.maxLength}:{},change:jr(a.change,d),submit:jr(a.submit,t.submitActions)}}}return a.formRole===Lo||i?{...a,click:jr(a.click,t.submitActions,{replaceActions:!0})}:a},Gr=(e,t)=>{if(Array.isArray(e))return e.map(n=>Gr(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Gr(o,t);for(let n of gc){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form"}})}return r},Jr=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0,s=Nt({characterId:e,character:t,characterName:r,characters:n,variables:o});return{...i||{},...t||{},name:s}},qo=(e=[],t={},r={})=>e.map(n=>{let o=Jr({characterId:n.characterId,character:n.character,characterName:n.characterName,characters:t,variables:r}),i=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(s=>s?.text??"").join(""):"";return{...n,text:i,character:o,characterName:o.name}}),yc=e=>!(!e||e.mode==="adv"&&e.content===void 0),bc=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n,runtime:o}={})=>{if(!t&&!yc(e))return;let i=e.content===void 0?[{text:""}]:Br(e.content,"dialogue.content"),s=e.content===void 0?0:Ba({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),c=o?.dialogueTextSpeed??$e.dialogueTextSpeed,a=e.textSpeed??c,l=(e.lines||[]).map((u,f)=>{let p=Br(u.content,`dialogue.lines[${f}].content`),h=Jr({characterId:u.characterId,character:u.character,characterName:u.characterName,characters:r,variables:n});return{...u,textSpeed:u.textSpeed??c,content:p.map(g=>({...g,text:Ur(g.text,{variables:n})})),character:h,characterName:h.name}}),d=Jr({characterId:e.characterId,character:e.character,characters:r,variables:n});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:d,textSpeed:a,content:i.map(u=>({...u,text:Ur(u.text,{variables:n})})),initialRevealedCharacters:s,lines:l}},Ho=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=ie(e,r,{functions:xe});return Ce(Te(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},Mr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),$o=({renderStateKeyboard:e,keyboard:t,phase:r})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([n,o])=>{let i=e[n]??{},s=r==="keydown"?o?.keydown:o?.keyup;if(r==="keydown"&&s&&typeof s=="object"){e[n]={...i,keydown:{payload:Mr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:Mr(o.keyup)});return}e[n]={...i,[r]:{payload:Mr(o)}}})},Ic=(e={},t={})=>{let r={};return $o({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),$o({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},Se=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:c})=>{if(!e)return[];let a=[],l=({instanceId:b,targetId:A})=>{let v=Fa({resources:t,animationId:p,playback:h,instanceId:b,targetId:A,animationPath:s});v&&a.push(v)},d=r!=null&&r!==!1,u=n!=null&&n!==!1,f=o&&i&&o===i;Ma(e,s);let p=Da(e),h=Pa(e),g=t?.animations?.[p],y=Ta(g,{animationId:p,animationPath:s});if(y==="update")return u&&i?l({instanceId:`${c}-animation-update`,targetId:i}):d&&o&&l({instanceId:`${c}-animation-update`,targetId:o}),a;if(y==="transition"){let b=`${c}-animation-transition`,A=h?.continuity==="persistent"?b:`${c}-animation-in`;if(d&&u&&f)return l({instanceId:b,targetId:i}),a;d&&l({instanceId:`${c}-animation-out`,targetId:o}),u&&l({instanceId:A,targetId:i})}return a},Ac=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),wc=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:c,variables:a,runtime:l,activePersistentAnimations:d,restoredPersistentAnimations:u,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,saveSlots:A=[]})=>{let{elements:v,animations:_}=e;if(t.background){let P=n===void 0?!0:Ue(n?.background??{},"animations"),k=v.find(x=>x.id==="story");if(!k)return e;let w=za(o,t.background),M=w||qa(t.background),F=r?.background?.resourceId,Z=r?.background?.colorId,V=t.background.resourceId??(t.background.animations?F:void 0),q=t.background.colorId??(t.background.animations?Z:void 0),Y=uc(o,V),te={...t.background,colorId:q};if((q!==void 0||Y)&&k.children.push(lc({resources:o,background:te,screen:i,includeOpacity:!Y})),V){let{images:x={},videos:C={}}=o,R=x[V]||C[V];if(R){let z=C[V]!==void 0,J={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...w},U={id:zr({resourceId:V,kind:z?"video":"sprite"}),type:z?"video":"sprite",src:R.fileId,width:R.width,height:R.height,...So(t.background,{includeDefaultAlpha:!0}),...ke(J,t.background)};z&&(U.loop=t.background.loop??!1,U.volume=R.volume??50),k.children.push(U)}}if(V){let{layouts:x={}}=o,C=x[V];if(C){let R={id:zr({resourceId:V,kind:"container"}),type:"container",children:C.elements,...So(t.background)};M&&Object.assign(R,ke({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...w},t.background));let z=ie(R,ye({variables:a,runtime:l,saveSlots:A,dialogueState:t.dialogue,isLineCompleted:s,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,characters:o.characters||{},skipTransitionsAndAnimations:c}),{functions:xe});k.children.push(Ce(Te(z,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:c}),o))}}let pe=Ro({resources:o,resourceId:F,colorId:Z}),G=Ro({resources:o,resourceId:V,colorId:q}),H=Se({animationsDef:t.background.animations,resources:o,previousResourceId:pe.resourceId,currentResourceId:G.resourceId,previousTargetId:pe.targetId,currentTargetId:G.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});ge({animationInstances:H,isLineCompleted:s,skipTransitionsAndAnimations:c,activePersistentAnimations:d,restoredPersistentAnimations:u,isAuthoredOnCurrentLine:P})&&_.push(...H)}return e},Ec=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:c,animations:a}=e;if(t.character&&n){let l=c.find(h=>h.id==="story");if(!l)return e;let d=t.character.items||[],u=r?.character?.items||[],f=wo(d),p=wo(u);for(let h=0;h<d.length;h++){let g=d[h],{transformId:y,sprites:b}=g,A=u.find(V=>V.id===g.id),v=u.findIndex(V=>V.id===g.id),_=A?.sprites&&A.sprites.length>0,P=b&&b.length>0,k=v>=0?Ut(A,v,p):void 0,w=Se({animationsDef:g.animations,resources:n,previousResourceId:k,currentResourceId:P?Ut(g,h,f):void 0,previousTargetId:k,currentTargetId:P?Ut(g,h,f):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&_&&ge({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...w);continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let M=Ut(g,h,f),F=n.transforms[y];if(!F){console.warn("Transform not found:",y);continue}let Z={type:"container",id:M,...ke(F,g),...pt(g),children:[]};for(let V of b){let q=Vo({id:`${M}-${V.id}`,item:V,resources:n});q&&Z.children.push(q)}l.children.push(Z),ge({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...w)}}return e},Yo=(e,t)=>{if(!Dr.includes(e))throw new Error(`${t} must be one of: ${Dr.join(", ")}.`)},vc=(e,t)=>{let r=!!e.resourceId||rn(e),n=e.layer??(r?void 0:t?.layer)??Tr;return Yo(n,`Visual item "${e.id}" layer`),n},xc=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:c,activePersistentAnimations:a,autoMode:l,skipMode:d,isChoiceVisible:u,isFormVisible:f,canRollback:p,form:h,saveSlots:g=[],visualLayer:y})=>{let{elements:b,animations:A}=e;if(t.visual&&n){let v=b.find(w=>w.id==="story");if(!v)return e;let _=t.visual.items,P=r?.visual?.items||[],k=ye({variables:s,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:l,skipMode:d,isChoiceVisible:u,isFormVisible:f,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i});y!==void 0&&Yo(y,"visualLayer");for(let w of _){let M=P.find(Y=>Y.id===w.id),F=vc(w,M);if(y!==void 0&&F!==y)continue;if(cc(w),w.text){let Y=Bt(n,w),te={...structuredClone(w.text),id:`visual-${w.id}`,type:"text",...ke(Y,w)};Object.assign(te,pt(w)),v.children.push(Ce(ie(te,k,{functions:xe}),n))}if(w.resourceId){let{images:Y={},videos:te={},spritesheets:pe={}}=n,G=pe[w.resourceId];if(G){let H=Bt(n,w),x=w.animationName;if(x){let C=G.animations?.[x];if(!C)throw new Error(`Animation '${x}' not found in spritesheet resource '${w.resourceId}'`);let R=pt(w),z={id:`visual-${w.id}`,type:"spritesheet-animation",...ke(H,w),width:w.width??G.width,height:w.height??G.height,alpha:R.alpha??w.alpha??1,src:G.fileId,atlas:G.jsonData,playback:{frames:C.frames,animationSpeed:w.animationSpeed??C.animationSpeed??.5,loop:w.loop??C.loop??!0}};R.blur&&(z.blur=R.blur),v.children.push(structuredClone(z))}}else{let H=Y[w.resourceId]||te[w.resourceId];if(H){let x=te[w.resourceId]!==void 0,C=Bt(n,w),R={id:`visual-${w.id}`,type:x?"video":"sprite",src:H.fileId,width:H.width,height:H.height,...ke(C,w)};Object.assign(R,pt(w)),x&&(R.loop=H.loop??!1,R.volume=H.volume??50),v.children.push(R)}}}if(w.resourceId){let{layouts:Y={}}=n,te=Y[w.resourceId];if(te){let pe=Bt(n,w),G={id:`visual-${w.id}`,type:"container",children:structuredClone(te.elements),...ke(pe,w)};Object.assign(G,pt(w));let H=ie(G,k,{functions:xe});v.children.push(Ce(Te(H,{isLineCompleted:o,skipMode:d,skipTransitionsAndAnimations:i}),n))}}let Z=_o(M),V=_o(w),q=Se({animationsDef:w.animations,resources:n,previousResourceId:Z,currentResourceId:V,previousTargetId:Z?`visual-${w.id}`:void 0,currentTargetId:V?`visual-${w.id}`:void 0,animationPath:`visual.items[${w.id}].animations`,idPrefix:w.id});ge({animationInstances:q,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:a})&&A.push(...q)}}return e},Ze="dialogue-character-sprite",ko=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,Cc=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=Be(e.elements);if(!a)return e;let l=t.dialogue?.character?.sprite,d=r?.dialogue?.character?.sprite,u=ko(l),f=ko(d),p=Se({animationsDef:l?.animations,resources:n,previousResourceId:f?Ze:void 0,currentResourceId:u?Ze:void 0,previousTargetId:f?Ze:void 0,currentTargetId:u?Ze:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!u)return l?.animations&&f&&ge({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e;let h=n.transforms?.[l.transformId];if(!h)return console.warn("Transform not found:",l.transformId),e;let g={type:"container",id:Ze,...ke(h),children:[]};for(let y of l.items){let b=Vo({id:`${Ze}-${y.id}`,item:y,resources:n});b&&g.children.push(b)}return a.children.push(g),ge({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e},Sc=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:d,skipOnlyViewedLines:u,isLineCompleted:f,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:y,saveSlots:b=[]})=>{let{elements:A,animations:v}=e;if(!t.dialogue||o)return e;let _=A.find(k=>k.id==="story");if(!_)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:k={}}=n,w=k[t.dialogue.ui.resourceId];if(w){let M={elements:w.elements},F=ye({variables:h,runtime:g,saveSlots:b,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:f,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:d,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:u,skipTransitionsAndAnimations:p}),Z={functions:xe},V=zt(M,F,Z),q=ie(V,F,Z),Y=Ce(Te(q?.elements,{isLineCompleted:f,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(Y))for(let te of Y)_.children.push(te);else Y&&_.children.push(Y)}}Cc(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let P=Se({animationsDef:t.dialogue.ui?.animations,resources:n,previousResourceId:r?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:r?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return ge({animationInstances:P,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&v.push(...P),e},_c=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:c,runtime:a,autoMode:l,skipMode:d,isChoiceVisible:u,isFormVisible:f,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:b,animations:A}=e;if(t.choice&&n){let v=Be(b);if(!v)return e;let _=n?.layouts[t.choice.resourceId];if(_&&_.elements){let k={elements:_.elements},w=ie(k,{...ye({variables:c,runtime:a,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:d,isChoiceVisible:u??!!t.choice,isFormVisible:f,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:xe}),M=Yr(Ce(Te(w?.elements,{isLineCompleted:i,skipMode:d,skipTransitionsAndAnimations:s}),n));if(Array.isArray(M))for(let F of M)v.children.push(F);else M&&v.children.push(M)}let P=Se({animationsDef:t.choice.animations,resources:n,previousResourceId:r?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:r?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});ge({animationInstances:P,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&A.push(...P)}return e},Rc=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:c,runtime:a,autoMode:l,skipMode:d,isChoiceVisible:u,isFormVisible:f,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:b,animations:A}=e;if(!y?.resourceId||!n)return e;let v=Be(b);if(!v)return e;let _=n?.layouts?.[y.resourceId];if(!_)return console.warn(`Form layout not found: ${y.resourceId}`),e;let P={id:"form-container",type:"container",x:0,y:0,children:_.elements||[]},k={...ye({variables:c,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:d,isChoiceVisible:u,isFormVisible:f,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},w=ie(P,k,{functions:xe}),M=Gr(Ce(Te(Kr(w,y),{isLineCompleted:i,skipMode:d,skipTransitionsAndAnimations:s}),n),y);M&&v.children.push(M);let F=Se({animationsDef:y.animations,resources:n,previousResourceId:r?.form?.resourceId,currentResourceId:y.resourceId,previousTargetId:r?.form?.resourceId?"form-container":void 0,currentTargetId:y.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return ge({animationInstances:F,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(...F),e},Oc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,form:u,saveSlots:f=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=Ic(h.keyboard,h.keyup);if(g&&Object.keys(g).length>0&&(e.global.keyboard=g),!Array.isArray(h.elements)||h.elements.length===0)return e;let y=Be(e.elements);if(!y)return e;let b={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(Ho({container:b,resources:r,templateData:ye({variables:n,runtime:o,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,form:u,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:c,skipTransitionsAndAnimations:p})),e},Lc=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Be(i))return e;let a=r.sounds[t.bgm.resourceId];if(!a)return e;let l=ye({variables:o,runtime:n}).runtime;s.push({id:"bgm",type:"sound",src:a.fileId,loop:t.bgm.loop??!0,volume:fc(l,t.bgm.volume??a.volume??Ht),startDelayMs:t.bgm.startDelayMs??null})}return e},$c=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx.items;for(let[s,c]of i.entries()){let a=r.sounds?.[c.resourceId];a&&o.push({id:pc({item:c,index:s}),type:"sound",src:a.fileId,loop:c.loop??a.loop??!1,volume:dc(n,c.volume??a.volume??Ht),startDelayMs:c.startDelayMs??a.startDelayMs??null})}}return e},kc=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},Tc=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,Dc=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let c=t.voice,{resourceId:a,loop:l,startDelayMs:d}=c,u=kc(r,n,a);if(!u)return e;let f=ye({variables:i,runtime:o}).runtime;return s.push({id:`voice-${n}-${a}`,type:"sound",src:u.fileId,volume:Tc(c,f),loop:l??!1,startDelayMs:d??null}),e},Pc=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,form:u,saveSlots:f=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:b}=e;if(t.layout){let P=Be(y);if(!P)return e;let k=n.layouts[t.layout.resourceId];if(!k)return e;Array.isArray(k.transitions)&&!p&&!h&&Qr({animations:b,transitions:k.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let w={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:k.elements||[]};P.children.push(Ho({container:w,resources:n,templateData:ye({variables:o,runtime:i,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,form:u,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:c,skipTransitionsAndAnimations:h}))}let A=r?.layout?.resourceId,v=t.layout?.resourceId,_=Se({animationsDef:t.layout?.animations,resources:n,previousResourceId:A,currentResourceId:v,previousTargetId:A?`layout-${A}`:void 0,currentTargetId:v?`layout-${v}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return ge({animationInstances:_,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(..._),e},Nc=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=t?.screen?.animations;if(!a)return e;let l=r!=null,d=Se({animationsDef:a,resources:n,previousResourceId:l?"story":void 0,currentResourceId:"story",previousTargetId:l?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return ge({animationInstances:d,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...d),e},Vc=(e,{presentationState:t})=>{let r=Be(e.elements);return!r||!t?.screen||Object.assign(r,Uo(t.screen)),e},jc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:d,overlayStack:u=[],dialogueHistory:f=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;return u&&u.length>0&&u.forEach((v,_)=>{let P=r.layouts[v.resourceId];if(!P){console.warn(`Overlay layout not found: ${v.resourceId}`);return}Array.isArray(P.transitions)&&(y||Qr({animations:A,transitions:P.transitions,defaultTargetId:`overlayStack-${_}`,idPrefix:`overlayStack-${_}`,animationPathPrefix:`overlayStack[${_}]`}));let k={id:`overlayStack-${_}`,type:"container",x:0,y:0,children:[Wo({id:`overlayStack-${_}-blocker`,screen:h}),...P.elements||[]]},w=qo(f,r.characters,n),M=ye({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:d,historyDialogue:w,characters:r.characters||{},skipTransitionsAndAnimations:y}),F=ie(k,M,{functions:xe}),[Z,...V]=F.children||[],q=Ce(Te({...F,children:V},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...q,children:Z?[Z,...q.children||[]]:q.children})}),e},Mc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,form:u,confirmDialog:f,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;if(!f?.resourceId)return e;let v=r.layouts?.[f.resourceId];if(!v)return console.warn(`ConfirmDialog layout not found: ${f.resourceId}`),e;Array.isArray(v.transitions)&&!y&&Qr({animations:A,transitions:v.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let _={id:"confirmDialog",type:"container",x:0,y:0,children:[Wo({id:"confirmDialog-blocker",screen:h}),...v.elements||[]]},P=qo(p,r.characters,n),k=ie(_,ye({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,form:u,confirmDialog:f,historyDialogue:P,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:xe}),[w,...M]=k.children||[],F=Ce(Te({...k,children:M},{isLineCompleted:g,skipMode:c,skipTransitionsAndAnimations:y}),r);return b.push({...F,children:w?[w,...F.children||[]]:F.children}),e},gt=e=>(t,r)=>xc(t,{...r,visualLayer:e}),Fc=gt(ve.BEHIND_BACKGROUND),Uc=gt(ve.BEHIND_CHARACTER),Bc=gt(ve.BEHIND_DIALOGUE),zc=gt(ve.BEHIND_CHOICE),Wc=gt(ve.FOREGROUND),Ko=e=>Pt(Ac,[Oc,Fc,wc,Uc,Ec,Bc,Sc,zc,_c,Rc,Pc,Wc,Vc,Nc,Lc,$c,Dc,jc,Mc])(e);var Yt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Zo=1,nn="choice",Kt="form",Xt=()=>({manual:{...Yt.manual},auto:{...Yt.auto},applyMode:Yt.applyMode}),on=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...Xt()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},D=e=>{let t=ae(e)?Ve(e):e;return structuredClone(t)},T=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Qt=e=>String(e),ei=()=>({sections:[],resources:[]}),qc=e=>T(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):ei(),Hc=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Yc=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:Hc(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),Kc=()=>({resourceId:void 0}),Gc=e=>{if(!T(e))return e;let t={...e};return Object.prototype.hasOwnProperty.call(t,"requireComplete")&&!Object.prototype.hasOwnProperty.call(t,"requireLineCompleted")&&(t.requireLineCompleted=t.requireComplete),delete t.requireComplete,t},sn=(e,t)=>{let r=e?.story?.scenes??{};for(let[n,o]of Object.entries(r))if(o?.sections?.[t])return{sceneId:n,section:o.sections[t]};return{sceneId:void 0,section:void 0}},ti=e=>{let t=e?.story?.scenes??{},r=new Map;for(let[n,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let c=r.get(s);if(c!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${c}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},ri=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},ni=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Zo)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Jc=(e,t={})=>{let r;try{r=ni(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:ri(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},Xc=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Jc(t,r)])),oi=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Bu(r));return t.length>0?t:void 0},Qc=e=>{!T(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!T(t))return;let r=oi(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},Go=(e,t,r,n="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!T(e))throw new Error(`Malformed ${n}.${t}[${r}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${n}.${t}[${r}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${n}.sections[${r}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},Zc=(e,t="viewedRegistry")=>{if(e===void 0)return ei();if(!T(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let r=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Go(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Go(o,"resources",i,t);return[s.resourceId,s]})))}},ii=(e,t,r)=>{if(!T(e))throw new Error(`Malformed save slot ${r}.`);let{sectionId:n,lineId:o}=e;if(typeof n!="string"||n.length===0)throw new Error(`Malformed save slot ${r}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${r}: missing lineId.`);let{sceneId:i,section:s}=sn(t,n);if(!s)throw new Error(`Malformed save slot ${r}: section "${n}" does not exist in projectData.`);if(!s.lines?.some(a=>a.id===o))throw new Error(`Malformed save slot ${r}: line "${o}" does not exist in section "${n}".`);return{sceneId:i,sectionId:n,lineId:o}},el=(e,t,r)=>{if(!T(e)||!Array.isArray(e.timeline))return yt({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((c,a)=>{if(!T(c))return[];try{let l=ii(c,r,`rollback.timeline[${a}]`),d=Jt({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:c.rollbackPolicy}),u=oi(D(c.executedActions));return u&&(d.executedActions=u),[d]}catch{return[]}});if(n.length===0)return yt({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):n.length-1;(o<0||o>=n.length)&&(o=n.length-1);let i=n[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let c=n.findLastIndex(a=>a.sectionId===t.sectionId&&a.lineId===t.lineId);c>=0?o=c:(n.push(Jt({sectionId:t.sectionId,lineId:t.lineId})),o=n.length-1)}let s=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),o):0;return{currentIndex:o,isRestoring:!1,replayStartIndex:s,timeline:n}},tl=(e,t,r)=>{if(!T(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=ln(t),o=ii(e.pointers?.read,t,`contexts[${r}].pointers.read`);if(e.variables!==void 0&&!T(e.variables))throw new Error(`Malformed save slot contexts[${r}].variables entry.`);if(e.runtime!==void 0&&!T(e.runtime))throw new Error(`Malformed save slot contexts[${r}].runtime entry.`);let i=e.variables?Xe(D(e.variables),t.resources?.variables??{}):{},s=hl({loadedContextRuntime:T(e.runtime)?D(e.runtime):{}}),c={currentPointerMode:"read",pointers:{read:o},configuration:T(e.configuration)?D(e.configuration):{},views:Array.isArray(e.views)?D(e.views):[],bgm:T(e.bgm)?D(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:el(e.rollback,o,t)};return s&&(c.runtime=s),c},rl=(e,t)=>{if(!T(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((r,n)=>tl(r,t,n))}},nl=(e,t)=>{if(!T(e))throw new Error("Malformed save slot.");let r=ni(e.formatVersion);return{...e,formatVersion:r,state:rl(e.state,t)}},Jo=(e,t,{required:r=!1}={})=>{if(e===void 0){if(r)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let n=D(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},ol=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Jo(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Jo(e.cancelActions,"cancelActions")}},tt=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},il=e=>(T(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),rt=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},si=e=>{if(!(!T(e)||!e.animations))return{animations:D(e.animations)}},sl=(e,t)=>{let r=si(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},al=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},cl=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},Gt=e=>String(e??""),ai=(e,t)=>{let r=Gt(t);return e?.trim===!0?r.trim():r},ll=e=>T(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>T(t)).map(([t,r])=>[t,{id:t,...D(r)}])):{},ul=(e,t)=>{if(!t||!T(e.global.formDrafts))return;let r=e.global.formDrafts[t];return T(r)?r:void 0},ci=(e,t)=>{let r=il(e);T(r[t])||(r[t]={values:{},touched:{},errors:{},submitted:!1});let n=r[t];return T(n.values)||(n.values={}),T(n.touched)||(n.touched={}),T(n.errors)||(n.errors={}),typeof n.submitted!="boolean"&&(n.submitted=!1),n},an=(e,t)=>{let r=ai(e,t);return e?.required===!0&&r.length===0?"required":null},dl=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=ne({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:Me(n.slice(0,o+1).map(i=>i.actions||{}))},fl=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=al(t),o=cl(r,n);if(!n||!o)return null;let i=ul(e,o),s=ll(t),c=pn({state:e}),a={},l=[],d={},u=!0;return Object.entries(s).forEach(([f,p])=>{let h=Gt(c?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},f)?Gt(i.values[f]):h,y=i?.touched?.[f]===!0,b=an(p,g),A=i?.submitted||y?b:null,v=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,_={id:f,variableId:p.variableId,value:g,initialValue:h,valid:!b,error:A,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...v!==void 0?{maxLength:v}:{}};b&&(u=!1),a[f]=_,l.push(_),d[f]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:u,submitted:i?.submitted===!0,fields:a,fieldList:l,values:d,submitActions:{submitForm:{formKey:o,actions:D(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:D(t.cancelActions??{})}}}},ze=[],Xo="line",cn="interaction",Jt=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),ln=e=>{let{contextVariableDefaultValues:t}=Vt(e??{});return D(t)},li=()=>({...D(ft)}),ui=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:D(r),hasLoadedValues:!1};if(!T(e))throw new Error(`Malformed ${n}.`);let o=D(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=di(s,D(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},pl=({loadedGlobalRuntime:e={}})=>ui({loadedRuntime:e,runtimeIds:$r,defaults:$e,path:"global.runtime"}).runtimeState,hl=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=ui({loadedRuntime:e,runtimeIds:kr,defaults:li(),path:"context.runtime"});return r?t:void 0},Zt=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},ml=e=>e.runtime?(kr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=D(ft[t]))}),e.runtime):(e.runtime=li(),e.runtime),gl=e=>Io(e.global),yl=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:gl(e)}})},bl=e=>bo[e],Il=(e,t)=>{let r=bl(e);if(r==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(r==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(r==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},di=(e,t)=>(Il(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),fi=(e,t,r)=>{let n=di(t,r);if(t in ft){let o=Zt(e);if(!o)return n;let i=ml(o);return i[t]=n,n}return e.global[t]=n,n},pi=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:D(e)},configuration:{},views:[],bgm:Kc(),variables:ln(t),rollback:yt({pointer:e})}),nt=e=>e?(e.currentPointerMode="read",T(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Al=(e,{queueRender:t=!0}={})=>{let r=e.contexts?.[e.contexts.length-1],n=r?.pointers?.read;if(!r||!n?.sectionId||!n?.lineId)return null;let o=pi({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,wl(e,{queueRender:t}),o},wl=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,tt(e),rt(e),e.global.nextLineConfig=Xt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},hi=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},yt=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[Jt({sectionId:e.sectionId,lineId:e.lineId})]:[]}},He=(e,t={})=>{if(e?.rollback)return hi(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let r=e?.pointers?.read;return e.rollback=yt({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},un=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=He(r);if(n.isRestoring)return;n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1));let o=n.timeline[n.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){n.currentIndex=n.timeline.length-1;return}n.timeline.push(Jt(t)),n.currentIndex=n.timeline.length-1},El=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;if(!r||r.isRestoring||!Array.isArray(r.timeline)||typeof r.currentIndex!="number")return null;let n=ze[ze.length-1],o=typeof n?.checkpointIndex=="number"?n.checkpointIndex:r.currentIndex;return o<0||o>=r.timeline.length?null:(typeof n?.checkpointIndex!="number"&&o<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,o+1)),r.timeline[o]??null)},vl=({state:e},t={})=>{let r=t?.source===Xo?Xo:cn,o=e.contexts?.[e.contexts.length-1]?.rollback;return!o||o.isRestoring||!Array.isArray(o.timeline)||typeof o.currentIndex!="number"||o.currentIndex<0||o.currentIndex>=o.timeline.length?(ze.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),ze.push({checkpointIndex:o.currentIndex,source:r}),e)},xl=({state:e})=>(ze.pop(),e),Ae=(e,t,r)=>{let o=ze[ze.length-1]?.source??cn;if(!zu(t,o))return;let i=El(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:D(r)}))},Qo=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:c}of n){let a=e.projectData.resources?.variables?.[o],l=a?.scope,d=a?.type;if(Le(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);jt(l,o),Mt(d,i,o),_r(d,i,s,o,{roundTo:c}),l==="context"&&(r.variables[o]=Ft(r.variables[o],i,s,{roundTo:c}))}},Cl=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{Wu(e,r,n)})},Sl=(e,t)=>{let{sectionId:r,lineId:n}=t,s=ne({state:e},{sectionId:r})?.lines?.find(c=>c.id===n)?.actions;s&&Object.entries(s).forEach(([c,a])=>{$i(e,c,a)})},mi=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=He(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&It({state:e}),e.global.skipMode&&We({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=ln(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=D(Yt),e.global.overlayStack=[],tt(e),rt(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let c=i;c<=t;c++)c>i&&on(e),Sl(e,n.timeline[c]),Cl(e,n.timeline[c]);let s=nt(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(c=>c?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},_l=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;ti(t);let c=t.story.initialSceneId,a=t.story.scenes[c],l=a.initialSectionId,d=a.sections[l],u={sceneId:c,sectionId:l,lineId:d.initialLineId??d.lines[0].id},{globalVariablesDefaultValues:f}=Vt(t),p={...f,...Xe(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:Zc(s,"accountViewedRegistry"),nextLineConfig:Xt(),saveSlots:Xc(n),overlayStack:[],variables:p,...pl({loadedGlobalRuntime:i})},contexts:[pi({pointer:u,projectData:t})]}},Rl=({state:e})=>e.global.overlayStack||[],Ol=({state:e})=>e.global.pendingEffects,gi=({state:e})=>e.global.skipMode,Ll=({state:e})=>e.global.autoMode,yi=({state:e})=>e.global.dialogueUIHidden,bi=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(!r)return[];let{sectionId:n,lineId:o}=r.pointers.read,i=ne({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),c=i.lines.slice(0,s+1),a=[],l={},d=ut({variables:{...e.global?.variables??{},...Zt(e)?.variables??{}},runtime:Fe(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let u of c){let f=u.actions||{};if(l=Me([l,f]),!f.dialogue)continue;let p=l.dialogue||{},h=Nt({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:d}),g=Yc({sectionId:n,lineId:u.id,content:f.dialogue.append===!0?p.content:f.dialogue.content,dialogueState:p,characterName:h});if(f.dialogue.append===!0&&a.length>0){a[a.length-1]={...a[a.length-1],content:g.content,text:g.text,characterId:g.characterId,character:g.character,characterName:g.characterName};continue}a.push(g)}return a},$l=({state:e})=>e.global.confirmDialog??null,bt=({state:e},{pointer:t}={})=>{let r=t??fe({state:e})?.pointer,n=dl({state:e,pointer:r});return fl({state:e,form:n.form,pointer:r})},kl=({state:e},{pointer:t}={})=>!!bt({state:e},{pointer:t}),we=({state:e},{pointer:t}={})=>{let r=bt({state:e},{pointer:t});if(r)return{source:Kt,formId:r.id,formKey:r.key};let n=Ii({state:e,pointer:t});return n?{source:nn,resourceId:n}:null},Tl=({state:e,registry:t},r)=>{let{sectionId:n,lineId:o}=r,s=(Array.isArray(t?.sections)?t.sections:[]).find(d=>d.sectionId===n);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let c=ne({state:e},{sectionId:n});if(!c||!c.lines||!Array.isArray(c.lines))return s.lastLineId===o;let a=c.lines.findIndex(d=>d.id===s.lastLineId),l=c.lines.findIndex(d=>d.id===o);return a===-1||l===-1?s.lastLineId===o:l<=a},Dl=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},dn=({state:e},t)=>Tl({state:e,registry:e.global.accountViewedRegistry},t),Pl=({state:e},t)=>Dl({registry:e.global.accountViewedRegistry},t),Nl=({state:e})=>e.global.nextLineConfig,Ii=({state:e,pointer:t}={})=>{let r=t??fe({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=ne({state:e},{sectionId:n})?.lines||[],c=s.findIndex(l=>l.id===o);if(c<0)return;let a;for(let l of s.slice(0,c+1)){let d=l?.actions;if(d?.cleanAll&&(a=void 0),!d||!Object.prototype.hasOwnProperty.call(d,"choice")){a=void 0;continue}let u=d.choice;if(u?.resourceId){a=u.resourceId;continue}u?.animations||(a=void 0)}return a},Ai=({state:e})=>!!Ii({state:e}),Vl=({state:e})=>structuredClone(e),wi=({state:e})=>e.global.saveSlots,jl=({state:e},t)=>{let r=t?.slotId,n=Qt(r);return e.global.saveSlots[n]},fn=({state:e})=>Fe(e),Ml=({state:e},t)=>Ee(e,t?.runtimeId),pn=({state:e})=>{let t={...e.global?.variables??{},...Zt(e)?.variables??{}};return ut({variables:t,runtime:Fe(e),variableConfigs:e.projectData.resources?.variables??{}})},fe=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},ne=({state:e},t)=>{let{sectionId:r}=t;return sn(e.projectData,r).section},hn=({state:e})=>{let t=fe({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=ne({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},Ei=({state:e})=>{let{sectionId:t,lineId:r}=fe({state:e}).pointer,o=ne({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===r),c=o.slice(0,i+1).map(l=>{let d=l.actions||{},u={};return Object.keys(d).forEach(f=>{u[f]=d[f]}),u});return Me(c)},Fl=({state:e})=>{let t=vi({state:e}),n=hn({state:e})?.actions??{},o=Me([t??{},n]);return Rr(t??{},o??{})},Ul=({state:e},{sectionId:t})=>{let r=ne({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},c=Me([o,s]),a=Rr(o,c);n.push({id:i.id,changes:a,presentationState:c}),o=Or(c)}return n},Bl=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=Ul({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},vi=({state:e})=>{let{sectionId:t,lineId:r}=fe({state:e}).pointer,o=ne({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===r);if(i<=0)return null;let c=o.slice(0,i).map(a=>{let l=a.actions||{},d={};return Object.keys(l).forEach(u=>{d[u]=l[u]}),d});return Or(Me(c))},mn=({state:e},{slotsPerPage:t=6}={})=>{let o=((fn({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let c=o+s,a=e.global.saveSlots&&e.global.saveSlots[Qt(c)]||{};i.push({...a,slotId:c})}return{saveSlots:i}},zl=wi,Wl=mn,ql=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;return!r||!Array.isArray(r.timeline)||typeof r.currentIndex!="number"?!1:r.currentIndex>=0&&r.currentIndex<r.timeline.length-1},Hl=({state:e},t={})=>{let r=Ei({state:e}),n=vi({state:e}),o=hn({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:D(i)}:o,c=i?.animations&&n===null?{}:n,{sectionId:a}=fe({state:e}).pointer,{sceneId:l}=sn(e.projectData,a),d=fn({state:e}),u=t?.activePersistentAnimations??[],f=t?.restoredPersistentAnimations??[],p=bt({state:e}),h=Ai({state:e}),g=pn({state:e}),{saveSlots:y}=mn({state:e}),b=ql(e);return Ko({presentationState:r,previousPresentationState:c,currentLineActions:s,resources:e.projectData.resources,currentSceneId:l,screen:e.projectData.screen,dialogueUIHidden:d.dialogueUIHidden,autoMode:d.autoMode,skipMode:d.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:Ti({state:e}),skipOnlyViewedLines:!d.skipUnseenText,isLineCompleted:d.isLineCompleted,skipTransitionsAndAnimations:!!d.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:bi({state:e}),saveSlots:y,variables:g,runtime:d,activePersistentAnimations:u,restoredPersistentAnimations:f})},Yl=({state:e},t)=>(e.global.confirmDialog=ol(t),e.global.pendingEffects.push({name:"render"}),e),Kl=({state:e})=>(e.global.confirmDialog&&(tt(e),e.global.pendingEffects.push({name:"render"})),e),Gl=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Ae(e,"pushOverlay",t),e),Jl=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Ae(e,"popOverlay",void 0),e),Xl=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),Ae(e,"replaceLastOverlay",t),e),Ql=({state:e})=>(e.global.overlayStack=[],tt(e),rt(e),e.global.pendingEffects.push({name:"render"}),Ae(e,"clearOverlays",void 0),e),Zl=e=>{e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},er=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,sl(e,r),rt(e);let n=we({state:e},{pointer:t}),o=n?.source===nn,i=n?.source===Kt;return n&&Zl(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},xi=({state:e})=>(we({state:e})||(e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.autoMode=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.isLineCompleted&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ee(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),It=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),eu=({state:e})=>{let t=e.global.autoMode;return we({state:e})&&!t||(t?It({state:e}):xi({state:e})),e},Ci=({state:e})=>(we({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),We=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),tu=({state:e})=>{let t=gi({state:e});return we({state:e})&&!t||(t?We({state:e}):Ci({state:e})),e},tr=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Ae(e,"showDialogueUI",void 0),e),Si=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Ae(e,"hideDialogueUI",void 0),e),ru=({state:e})=>(yi({state:e})?tr({state:e}):Si({state:e}),e),Ye=(e,t,r)=>(fi(e,t,r),yl(e),e.global.pendingEffects.push({name:"render"}),e),At=(e,t,r,n)=>{let o=fi(e,t,r);return e.global.pendingEffects.push({name:"render"}),Ae(e,n,{value:o}),e},nu=({state:e},t)=>Ye(e,"dialogueTextSpeed",t?.value),ou=({state:e},t)=>Ye(e,"autoForwardDelay",t?.value),iu=({state:e},t)=>Ye(e,"skipUnseenText",t?.value),su=({state:e},t)=>Ye(e,"skipTransitionsAndAnimations",t?.value),au=({state:e},t)=>Ye(e,"soundVolume",t?.value),cu=({state:e},t)=>Ye(e,"musicVolume",t?.value),lu=({state:e},t)=>Ye(e,"muteAll",t?.value),uu=({state:e},t)=>At(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),du=({state:e})=>{let t=Ee(e,"saveLoadPagination")+1;return At(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},fu=({state:e})=>{let t=Ee(e,"saveLoadPagination")-1;return At(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},pu=({state:e},t)=>At(e,"menuPage",t?.value,"setMenuPage"),hu=({state:e},t)=>At(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),mu=({state:e})=>(e.global.pendingEffects=[],e),gu=({state:e},t)=>(e.global.pendingEffects.push(t),e),_i=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!si(n),i=ne({state:e},{sectionId:t});if(!i)return console.warn(`Section not found: ${t}`),e;let s=i.lines?.[0];if(!s)return console.warn(`Section ${t} has no lines`),e;if(r&&!Al(e,{queueRender:!o}))return e;e.global.autoMode&&It({state:e}),r&&e.global.skipMode&&We({state:e});let c=e.contexts?.[e.contexts.length-1];if(c){let a=nt(c),l=a.read;r||qe(e,{sectionId:l?.sectionId,lineId:l?.lineId}),c.rollback||He(c,{compatibilityAnchor:!0}),a.read={sectionId:t,lineId:s.id},r?c.rollback=yt({pointer:a.read}):un(e,{sectionId:t,lineId:s.id})}return er(e,c?.pointers?.read,{screenTransition:n}),e},yu=({state:e},t)=>_i(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),Ri=e=>(e.global.accountViewedRegistry=qc(e.global.accountViewedRegistry),e.global.accountViewedRegistry),gn=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(r=>({scope:r.scope,path:r.path,op:r.op,value:D(r.value)}))}})},Oi=(e,t)=>{gn(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(r=>({sectionId:r.sectionId,...r.lastLineId===void 0?{}:{lineId:r.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},bu=(e,t,{sectionId:r,lineId:n})=>{if(!r||!n)return!1;let o=T(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===r);if(i){if(i.lastLineId===void 0)return!1;let s=ne({state:e},{sectionId:r});if(s?.lines){let c=s.lines.findIndex(l=>l.id===i.lastLineId),a=s.lines.findIndex(l=>l.id===n);if(c===-1||a>c)return i.lastLineId===n?!1:(i.lastLineId=n,!0)}else return i.lastLineId===n?!1:(i.lastLineId=n,!0);return!1}else return o.sections.push({sectionId:r,lastLineId:n}),!0},qe=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;bu(e,Ri(e),t)&&Oi(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},Iu=({state:e},t)=>(qe(e,t),e.global.pendingEffects.push({name:"render"}),e),Au=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=Ri(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),Oi(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},Li=({state:e},t)=>{let r=Gc(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,c=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;r&&n?(e.global.nextLineConfig={manual:r,auto:n},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(r&&(e.global.nextLineConfig.manual=r),n&&(e.global.nextLineConfig.auto=n),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let a=e.global.nextLineConfig.auto?.enabled,l=we({state:e});return!c&&!l&&a===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!c&&a===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),Ae(e,"setNextLineConfig",t),e},wu=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:n}=t,o=t?.savedAt,i=Qt(r),s=D(e.contexts);s?.forEach(l=>{nt(l),hi(l.rollback),Qc(l.rollback)});let c={contexts:s},a={formatVersion:Zo,slotId:ri(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:c};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Eu=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=Qt(r),o=e.global.saveSlots[n];if(o){let i=nl(o,e.projectData);e.contexts=i.state.contexts,e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=Xt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,tt(e),rt(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},vu=({state:e},t)=>{let{projectData:r}=t;ti(r),e.projectData=r;let n=r?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=Vt(r??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...Xe(e.global.variables,n)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...Xe(s.variables,n)})}),tt(e),rt(e),e.global.pendingEffects.push({name:"render"}),e},xu=({state:e},t)=>{let{sectionId:r,lineId:n}=t;if(!n)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=r||o.pointers.read?.sectionId;if(r&&!ne({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=ne({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(l=>l.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let a=nt(o);return a.read={sectionId:i,lineId:n},er(e,a.read),e},Cu=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return tr({state:e}),e;let r=we({state:e});if(r?.source===nn&&t?.bypassChoice!==!0||r?.source===Kt&&t?._interactionSource!==Kt)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let d=fe({state:e})?.pointer,u=d?.sectionId,f=d?.lineId;u&&f&&qe(e,{sectionId:u,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ee(e,"autoForwardDelay")}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=fe({state:e})?.pointer,o=n?.sectionId,i=ne({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],c=i?.lines||[],l=c.findIndex(d=>d.id===n?.lineId)+1;if(l<c.length){let d=c[l],u=!Ee(e,"skipUnseenText");if(e.global.skipMode&&u&&!dn({state:e},{sectionId:o,lineId:d.id}))return We({state:e}),e;if(s&&!s.rollback&&He(s,{compatibilityAnchor:!0}),s){let h=nt(s),g=h.read?.lineId;g&&o&&qe(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:d.id}}un(e,{sectionId:o,lineId:d.id}),on(e);let{activeInteraction:f}=er(e,{sectionId:o,lineId:d.id}),p=e.global.nextLineConfig;p?.auto?.enabled&&!f&&p.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}})}else e.global.autoMode&&It({state:e}),e.global.skipMode&&We({state:e});return e},Su=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=we({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ee(e,"autoForwardDelay")}});let r=fe({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&qe(e,{sectionId:n,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},_u=({state:e},t)=>_i(e,{sectionId:t?.sectionId,screen:t?.screen}),Ru=({state:e})=>{if(e.global.dialogueUIHidden)return tr({state:e}),e;if(we({state:e}))return e;let t=fe({state:e})?.pointer,r=t?.sectionId,n=ne({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],c=i.findIndex(a=>a.id===t?.lineId)+1;if(c<i.length){let a=i[c],l=!Ee(e,"skipUnseenText");if(e.global.skipMode&&l&&!dn({state:e},{sectionId:r,lineId:a.id}))return We({state:e}),e;if(o&&!o.rollback&&He(o,{compatibilityAnchor:!0}),o){let u=nt(o),f=u.read?.lineId;f&&r&&qe(e,{sectionId:r,lineId:f}),u.read={sectionId:r,lineId:a.id}}un(e,{sectionId:r,lineId:a.id}),on(e);let{activeInteraction:d}=er(e,{sectionId:r,lineId:a.id});e.global.nextLineConfig.auto?.enabled&&!d&&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},yn=(e,t={})=>{let r=bt({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},Ou=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let r=e.projectData.resources?.variables?.[t.variableId],n=r?.scope,o=r?.type;if(Le(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return jt(n,t.variableId),Mt(o,"set",t.variableId),{variableConfig:r,scope:n}},Lu=(e,t)=>({id:e.id,key:e.key,valid:!0,values:D(t),fields:D(e.fields),fieldList:D(e.fieldList)}),$u=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=fe({state:e})?.pointer,r=t?.sectionId,n=t?.lineId;r&&n&&qe(e,{sectionId:r,lineId:n})},ku=({state:e},t={})=>{let r=yn(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=ci(e,r.key),i=Gt(t.value),s=r.fields[n],c=an(s,i);return o.values[n]=i,o.touched[n]=!0,c?o.errors[n]=c:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},Tu=({state:e},t={})=>{let r=yn(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=ci(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([u,f])=>{let p=Object.prototype.hasOwnProperty.call(n.values,u)?n.values[u]:f.value,h=an(f,p);n.touched[u]=!0,h&&(i[u]=h),o[u]=ai(f,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:D(i),form:{id:r.id,key:r.key,values:D(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let c=!1,a=[],l=[];Object.entries(r.fields).forEach(([u,f])=>{let{scope:p}=Ou(e,f),h=p==="context"?s.variables:e.global.variables,g=o[u];h[f.variableId]=Ft(h[f.variableId],"set",g),p==="context"&&(c=!0,l.push({variableId:f.variableId,op:"set",value:g})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${f.variableId}`,op:"set",value:D(h[f.variableId])})}),c&&Ae(e,"updateVariable",{id:"submitForm",operations:l}),gn(e,a);let d=Lu(r,o);return $u(e),delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:d}},Du=({state:e},t={})=>{let r=yn(e,t);return r?(delete e.global.formDrafts?.[r.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:r.id,key:r.key,values:D(r.values),fields:D(r.fields),fieldList:D(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},Pu=({state:e},t)=>{let{id:r,operations:n=[]}=t;if(!r)throw new Error("updateVariable requires an id field");if(typeof r!="string"||!/^[a-zA-Z0-9]+$/.test(r))throw new Error(`updateVariable id must be alphanumeric, got: "${r}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],c=[];return n.forEach(({variableId:a,op:l,value:d,roundTo:u})=>{let f=e.projectData.resources?.variables?.[a],p=f?.scope,h=f?.type;if(Le(f))throw new Error(`Cannot update computed variable: ${a}`);if(f?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);jt(p,a),Mt(h,l,a),_r(h,l,d,a,{roundTo:u});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:a,op:l,value:d};u!==void 0&&(y.roundTo=u),c.push(y)}g[a]=Ft(g[a],l,d,{roundTo:u}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:D(g[a])})}),i&&Ae(e,"updateVariable",{id:r,operations:c}),gn(e,s),e.global.pendingEffects.push({name:"render"}),e},Nu=e=>(t,r)=>e({state:t},r),Vu=e=>({variables:ut({variables:{...e.global?.variables??{},...Zt(e)?.variables??{}},runtime:Fe(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:Fe(e)}),ju=e=>{if(!T(e))throw new Error("conditional action payload must be an object");if(!Array.isArray(e.branches))throw new Error("conditional action requires branches array");if(e.branches.length===0)throw new Error("conditional action requires at least one branch")},Mu=(e,t,r)=>{if(!T(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!T(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==r-1)throw new Error("conditional else branch must be the last branch")},Fu=(e,t)=>{ju(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(Mu(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!lt(n.when,Vu(e)))){Object.entries(n.actions).forEach(([i,s])=>{$i(e,i,s)});return}}},Uu={conditional:{replayLine:Fu},updateVariable:{recordSources:[cn],replayLine:Qo,replayRecorded:Qo,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Nu(Li)}},rr=e=>Uu[e]??null,Bu=e=>rr(e)?.persistInSaveSlot===!0,zu=(e,t)=>{let r=rr(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},Wu=(e,t,r)=>{rr(t)?.replayRecorded?.(e,r)},$i=(e,t,r)=>{rr(t)?.replayLine?.(e,r)},ki=({state:e},t)=>{let{offset:r}=t;if(r===void 0||typeof r!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let n=e.contexts[e.contexts.length-1];if(!n)return null;let o=n.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+r;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},Ti=({state:e})=>ki({state:e},{offset:-1})!==null,qu=({state:e},t)=>{let{offset:r=-1}=t;if(r>=0)throw new Error("rollbackByOffset requires a negative offset");let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let o=He(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:mi(e,i)},Hu=({state:e},t)=>{let{sectionId:r,lineId:n}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=He(o,{compatibilityAnchor:!o.rollback}),c=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===r&&a.lineId===n);if(c===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return c===i.currentIndex?e:mi(e,c)},Di=e=>{let t=_l(e);return ro(t,{selectPendingEffects:Ol,selectSkipMode:gi,selectAutoMode:Ll,selectIsChoiceVisible:Ai,selectIsFormVisible:kl,selectActiveInteraction:we,selectActiveForm:bt,selectDialogueUIHidden:yi,selectDialogueHistory:bi,selectConfirmDialog:$l,selectIsLineAccountViewed:dn,selectIsResourceAccountViewed:Pl,selectNextLineConfig:Nl,selectSystemState:Vl,selectSaveSlotMap:wi,selectSaveSlots:zl,selectSaveSlot:jl,selectRuntime:fn,selectRuntimeValue:Ml,selectAllVariables:pn,selectCurrentPointer:fe,selectSection:ne,selectCurrentLine:hn,selectPresentationState:Ei,selectPresentationChanges:Fl,selectSectionLineChanges:Bl,selectSaveSlotPage:mn,selectCurrentPageSlots:Wl,selectRenderState:Hl,selectOverlayStack:Rl,selectLineIdByOffset:ki,selectCanRollback:Ti,startAutoMode:xi,stopAutoMode:It,toggleAutoMode:eu,startSkipMode:Ci,stopSkipMode:We,toggleSkipMode:tu,showDialogueUI:tr,hideDialogueUI:Si,toggleDialogueUI:ru,setDialogueTextSpeed:nu,setAutoForwardDelay:ou,setSkipUnseenText:iu,setSkipTransitionsAndAnimations:su,setSoundVolume:au,setMusicVolume:cu,setMuteAll:lu,setSaveLoadPagination:uu,incrementSaveLoadPagination:du,decrementSaveLoadPagination:fu,setMenuPage:pu,setMenuEntryPoint:hu,showConfirmDialog:Yl,hideConfirmDialog:Kl,resetStoryAtSection:yu,clearPendingEffects:mu,appendPendingEffect:gu,beginRollbackActionBatch:vl,endRollbackActionBatch:xl,addViewedLine:Iu,addViewedResource:Au,setNextLineConfig:Li,saveSlot:wu,loadSlot:Eu,updateProjectData:vu,sectionTransition:_u,jumpToLine:xu,nextLine:Cu,markLineCompleted:Su,rollbackToLine:Hu,rollbackByOffset:qu,pushOverlay:Gl,popOverlay:Jl,replaceLastOverlay:Xl,clearOverlays:Ql,updateFormField:ku,submitForm:Tu,cancelForm:Du,updateVariable:Pu,nextLineFromSystem:Ru},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var Yu="route-engine",Ku="projectPersistence";var Ni=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),ee=e=>Object.prototype.toString.call(e)==="[object Object]",Pi="variables.",Gu=(e={})=>{let t=ee(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!ee(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lineId=="string"?{lineId:r.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!ee(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Ju=(e={})=>{let t=ee(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!ee(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lastLineId=="string"?{lastLineId:r.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!ee(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Xu=(e,t)=>{let r=Ju(e),n=Gu(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let c=o.find(a=>a.sectionId===s.sectionId);if(!c){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(c.lastLineId!==void 0){if(s.lineId===void 0){delete c.lastLineId;return}c.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},Vi=(e={})=>{let t=ee(e)?e:{};return{saveSlots:ee(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:ee(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:ee(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:ee(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:ee(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Qu=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!ee(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(Pi)?t.path.slice(Pi.length):null;if(n!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(n.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${r}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:n}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${r}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${r}].`)})},Zu=(e,t)=>{let r={};return Qu(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=Xu(r.accountViewedRegistry??e.accountViewedRegistry,n.value);return}let o=n.scope==="device"?"globalDeviceVariables":"globalAccountVariables";r[o]={...e[o],...r[o],[n.variableId]:n.value}}),r},bn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},ed=e=>{let t=bn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},td=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},rd=({indexedDB:e,databaseName:t,objectStoreName:r})=>new Promise((n,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(r)||s.createObjectStore(r,{keyPath:"namespace"})},i.onsuccess=()=>{n(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),nd=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let a=n.transaction(t,"readonly").objectStore(t).get(r);a.onsuccess=()=>{o(a.result??null)},a.onerror=()=>{i(a.error??new Error(`Failed to read persisted namespace "${r}" from IndexedDB.`))}})},wt=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let c=o.transaction(t,"readwrite"),a=c.objectStore(t),l=a.get(r),d=!1,u=p=>{d||(d=!0,s(p))},f=()=>{d||(d=!0,i())};l.onerror=()=>{u(l.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},l.onsuccess=()=>{let p=Vi(l.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...Ni(),...p,...h},y=a.put(g);y.onerror=()=>{u(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},c.oncomplete=()=>{f()},c.onerror=()=>{u(c.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},c.onabort=()=>{u(c.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},od=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let s=n.transaction(t,"readwrite"),a=s.objectStore(t).delete(r),l=!1,d=f=>{l||(l=!0,i(f))},u=()=>{l||(l=!0,o())};a.onerror=()=>{d(a.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{u()},s.onerror=()=>{d(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{d(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},In=(e={})=>{let{indexedDB:t,databaseName:r=Yu,objectStoreName:n=Ku,namespace:o}=e,i=td(t),s=ed(o),c=rd({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let a=await nd({databasePromise:c,objectStoreName:n,namespace:s});return{...Ni(),...Vi(a)}},clear:async()=>od({databasePromise:c,objectStoreName:n,namespace:s}),saveSlots:async a=>wt({databasePromise:c,objectStoreName:n,namespace:s,patch:{saveSlots:ee(a)?a:{}}}),saveGlobalDeviceVariables:async a=>wt({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:ee(a)?a:{}}}),saveGlobalAccountVariables:async a=>wt({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalAccountVariables:ee(a)?a:{}}}),saveGlobalRuntime:async a=>wt({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalRuntime:ee(a)?a:{}}}),applyScopedDataUpdates:async a=>wt({databasePromise:c,objectStoreName:n,namespace:s,patch:l=>Zu(l,a)})}},id=In;var sd=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),ad=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),ji="conditional",An="form",cd=new Set(["submitForm","cancelForm"]),Et=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function wn(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:c}=e,a=(I=new Map,S=Date.now())=>new Map(Array.from(I.entries()).filter(([,O])=>S<O.expiresAt).map(([O,j])=>[O,{animation:structuredClone(j.animation),startedAt:j.startedAt,expiresAt:j.expiresAt}])),l=(I=new Map)=>Array.from(I.values()).map(S=>structuredClone(S.animation)),d=(I=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,S])=>I<S.expiresAt))},u=()=>{for(;t.selectPendingEffects().length>0;){let I=[...t.selectPendingEffects()];t.clearPendingEffects();try{c(I)}catch(S){throw t.clearPendingEffects(),I.forEach(O=>{t.appendPendingEffect(O)}),S}}},f=({initialState:I,namespace:S})=>{t=Di(I),r=0,n=bn(S),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),u()},p=()=>n,h=()=>t.selectPresentationState(),g=()=>t.selectPresentationChanges(),y=I=>t.selectSectionLineChanges(I),b=(I={})=>{r+=1;let S=Date.now();d(S);let O=i.size>0,j=a(o,S),W=O?a(i,S):new Map,be={...t.selectRenderState({activePersistentAnimations:l(j),restoredPersistentAnimations:l(W)}),id:`render-${r}`};return s.set(be.id,{builtAt:S,persistentAnimationSessions:new Map([...W.entries(),...j.entries()]),usedRestoredPersistentAnimationSessions:O}),be},A=(I={})=>b(I),v=(I={})=>b(I),_=I=>{let S=typeof I?.id=="string"&&I.id.length>0?I.id:null,O=S?s.get(S):null;S&&s.delete(S);let j=new Map;Do(I?.animations).forEach(W=>{let le=Wt(W);if(!le)return;let be=O?.persistentAnimationSessions?.get(le)??o.get(le),xt=Math.max(0,No(W)),xn=be?.startedAt??O?.builtAt??Date.now();j.set(le,{animation:structuredClone(W),startedAt:xn,expiresAt:xn+xt})}),o=j,O?.usedRestoredPersistentAnimationSessions&&(i=new Map)},P=()=>t.selectSystemState(),k=()=>t.selectSaveSlotMap(),w=I=>t.selectSaveSlot(I),M=I=>t.selectSaveSlotPage(I),F=()=>t.selectSkipMode(),Z=()=>t.selectAutoMode(),V=()=>t.selectRuntime(),q=()=>t.selectIsChoiceVisible(),Y=()=>t.selectIsFormVisible(),te=()=>t.selectActiveInteraction(),pe=(I,S,O={})=>I!=="nextLine"||!Et(S)?S:O.bypassChoice===!0?{...S,bypassChoice:!0}:O.interactionSource===An?{...S,_interactionSource:An}:S,G=(I,S)=>{if(!t[I])return;sd.has(I)&&(ad.has(I)?i=a(o):i=new Map,o=new Map);let O=t[I](S);return u(),O},H=(I,S,O,j={})=>{if(I===ji){let W=C(O),le=Lr({[I]:S},W);J(le[I],O,j);return}G(I,S)},x=(I,S)=>{H(I,S)},C=I=>{if(!I)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(I,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:S,...O}=I,j=t.selectAllVariables?t.selectAllVariables():void 0;return{...O,_event:S,variables:j,runtime:t.selectRuntime?t.selectRuntime():{}}},R=I=>{if(!Et(I))throw new Error("conditional action payload must be an object");if(!Array.isArray(I.branches))throw new Error("conditional action requires branches array");if(I.branches.length===0)throw new Error("conditional action requires at least one branch")},z=(I,S,O)=>{if(!Et(I))throw new Error(`conditional branch at index ${S} must be an object`);if(!Et(I.actions))throw new Error(`conditional branch at index ${S} requires actions object`);if(!Object.prototype.hasOwnProperty.call(I,"when")&&S!==O-1)throw new Error("conditional else branch must be the last branch")},J=(I,S,O)=>{R(I);for(let j=0;j<I.branches.length;j+=1){let W=I.branches[j];z(W,j,I.branches.length);let le=C(S);if(!(Object.prototype.hasOwnProperty.call(W,"when")&&!lt(W.when,le))){or(W.actions,S,O);return}}},U=(I,S)=>({...I??{},_form:S}),vt=(I,S,O,j)=>{let W=G(I,S),le=W?.submitted===!0&&W.valid===!0,be=W?.cancelled===!0;!le&&!be||Et(S.actions)&&or(S.actions,U(O,W.form),{...j,interactionSource:An})},Ke=(I,S,O,j)=>{let W=C(O),be=Lr({[I]:S},W)[I];if(I===ji){J(be,O,j);return}let xt=pe(I,be,j);if(cd.has(I)){vt(I,xt,O,j);return}G(I,xt)},or=(I,S,O)=>{Object.entries(I).forEach(([j,W])=>{Ke(j,W,S,O)})},vn=(I,S,O={})=>{t.beginRollbackActionBatch({source:O.rollbackSource});try{or(I,S,O)}finally{t.endRollbackActionBatch({})}};return{init:f,handleAction:H,handleInternalAction:x,handleActions:vn,selectRenderState:A,prepareRenderState:v,commitRenderState:_,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:P,selectSaveSlotMap:k,selectSaveSlot:w,selectSaveSlotPage:M,selectSaveSlots:k,selectRuntime:V,selectIsChoiceVisible:q,selectIsFormVisible:Y,selectActiveInteraction:te,handleLineActions:()=>{let I=t.selectCurrentLine();return I?.actions?(vn(I.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var En=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},ld=80,Fi=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},ud=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&Fi({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},dd=({engine:e,ticker:t,autoTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n.delay??1e3;r.getElapsed()>=c&&(t.remove(i),r.setCallback(null),r.setElapsed(0),nr(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},fd=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},pd=({engine:e,ticker:t,skipTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n?.delay??ld;r.getElapsed()>=c&&(r.setElapsed(0),nr(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},hd=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},md=({engine:e,ticker:t,nextLineConfigTimerState:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n.delay??1e3;r.getElapsed()>=c&&(r.setElapsed(0),nr(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},gd=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},yd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},bd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},Id=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},Ad=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},wd=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},Mi={render:Fi,saveSlots:yd,saveGlobalDeviceVariables:bd,saveGlobalAccountVariables:Id,saveGlobalRuntime:Ad,applyScopedDataUpdates:wd,handleLineActions:ud,startAutoNextTimer:dd,clearAutoNextTimer:fd,startSkipNextTimer:pd,clearSkipNextTimer:hd,nextLineConfigTimer:md,clearNextLineConfigTimer:gd},Ed=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),nr=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},vd=(e=[])=>{let t=new Set,r=[];for(let n=e.length-1;n>=0;n-=1){let o=e[n];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!Ed.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},xd=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:c})=>{let a=En(),l=En(),d=En(),u=s??null,f=Promise.resolve(),p=null,h=null,g=!1,y=0,b=x=>{if(o){o(x);return}console.error("RouteEngine persistence write failed.",x)},A=()=>{if(u)return u;let x=e();return u=In({indexedDB:i,namespace:c??x?.getNamespace?.()}),u},v=x=>{f=f.catch(()=>{}).then(()=>{let C=A();return x(C)}).catch(C=>{b(C)})},_=x=>{let C=typeof x?.id=="string"&&x.id.length>0?x.id:null;y+=1,p=C,g=!1},P=()=>y,k=(x={})=>{if(x?.aborted===!0)return!1;let C=typeof x?.id=="string"&&x.id.length>0?x.id:null;return C?C!==p||C===h?!1:(h=C,!0):p!==null||g?!1:(g=!0,!0)},w=(x,C={})=>{if(x!=="renderComplete"||!k(C))return!1;let R=e();return nr(R,"markLineCompleted",{}),!0},M=new Set(["updateFormField","submitForm","cancelForm"]),F=x=>typeof x?.selectActiveInteraction=="function"?x.selectActiveInteraction():typeof x?.selectIsChoiceVisible=="function"&&x.selectIsChoiceVisible()?{source:"choice"}:null,Z=x=>x?._formKey??x?.formKey,V=(x,C)=>Z(x)===C?.formKey,q=(x,C)=>!x||typeof x!="object"||Array.isArray(x)||x._interactionSource!==C?.source?!1:C.source==="form"?V(x,C):!0,Y=(x,C)=>!x||typeof x!="object"||Array.isArray(x)||C?.source!=="form"?!1:V(x,C),te=(x={},C)=>{let R=x?.actions;return C?.source==="form"?q(x,C)?!0:!R||typeof R!="object"||Array.isArray(R)?!1:Object.entries(R).some(([z,J])=>M.has(z)&&Y(J,C)):q(x,C)?!0:!R||typeof R!="object"||Array.isArray(R)?!1:Object.values(R).some(z=>q(z,C))},pe=(x,C={})=>{if(!C?.actions)return!1;let R=F(x);return!R||R.source==="choice"?!1:!te(C,R)},G=({preprocessPayload:x,onEvent:C}={})=>async(R,z={})=>{let J=e();if(pe(J,z))return C?.(R,z);let U=await x?.(R,z)??z;if(pe(J,U))return C?.(R,U);if(w(R,U),U?.actions){let vt=U?._event?{_event:U._event}:U?.event?{_event:U.event}:void 0,Ke;U?.bypassChoice===!0?Ke={bypassChoice:!0}:U?._interactionSource&&(Ke={interactionSource:U._interactionSource}),Ke?J.handleActions(U.actions,vt,Ke):J.handleActions(U.actions,vt)}return C?.(R,U)},H=x=>{let C=e(),R=vd(x);R.forEach(J=>{if(!Mi[J.name]&&!n)throw new Error(`Unhandled pending effect "${J.name}".`)});let z={engine:C,routeGraphics:t,ticker:r,autoTimer:a,skipTimer:l,nextLineConfigTimerState:d,trackRenderDispatch:_,getRenderDispatchCount:P,enqueuePersistenceWrite:v};for(let J of R){let U=Mi[J.name];if(U){U(z,J.payload);continue}n(J,z)}};return H.handleRouteGraphicsEvent=w,H.createRouteGraphicsEventHandler=G,H},Cd=xd;var Sd=(e,t={})=>{let{resources:r={}}=t;return tn(e,r)};var Hf=wn;export{Tr as DEFAULT_VISUAL_LAYER,Qe as RENDER_LAYER,ve as VISUAL_LAYER,Cd as createEffectsHandler,id as createIndexedDbPersistence,Hf as default,Ks as resolveComputedVariables,Sd as resolveLayoutReferences};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "route-engine-js",
3
- "version": "1.25.0",
3
+ "version": "1.26.0",
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",