route-engine-js 1.21.0 → 1.22.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 ki=Object.defineProperty;var Ti=(e,t)=>{for(var r in t)ki(e,r,{get:t[r],enumerable:!0})};var Rn=Symbol.for("immer-nothing"),vn=Symbol.for("immer-draftable"),ae=Symbol.for("immer-state");function pe(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Ye=Object.getPrototypeOf;function ce(e){return!!e&&!!e[ae]}function Te(e){return e?On(e)||Array.isArray(e)||!!e[vn]||!!e.constructor?.[vn]||St(e)||_t(e):!1}var Di=Object.prototype.constructor.toString();function On(e){if(!e||typeof e!="object")return!1;let t=Ye(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)===Di}function Et(e,t){Ct(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function Ct(e){let t=e[ae];return t?t.type_:Array.isArray(e)?1:St(e)?2:_t(e)?3:0}function rr(e,t){return Ct(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Ln(e,t,r){let n=Ct(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function Pi(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function St(e){return e instanceof Map}function _t(e){return e instanceof Set}function ke(e){return e.copy_||e.base_}function nr(e,t){if(St(e))return new Map(e);if(_t(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=On(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[ae];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],l=n[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(n[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(Ye(e),n)}else{let n=Ye(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function cr(e,t=!1){return Rt(e)||ce(e)||!Te(e)||(Ct(e)>1&&(e.set=e.add=e.clear=e.delete=Ni),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>cr(n,!0))),e}function Ni(){pe(2)}function Rt(e){return Object.isFrozen(e)}var Vi={};function De(e){let t=Vi[e];return t||pe(0,e),t}var nt;function $n(){return nt}function ji(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function xn(e,t){t&&(De("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function or(e){ir(e),e.drafts_.forEach(Mi),e.drafts_=null}function ir(e){e===nt&&(nt=e.parent_)}function Cn(e){return nt=ji(nt,e)}function Mi(e){let t=e[ae];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Sn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[ae].modified_&&(or(t),pe(4)),Te(e)&&(e=vt(t,e),t.parent_||xt(t,e)),t.patches_&&De("Patches").generateReplacementPatches_(r[ae].base_,e,t.patches_,t.inversePatches_)):e=vt(t,r,[]),or(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Rn?e:void 0}function vt(e,t,r){if(Rt(t))return t;let n=t[ae];if(!n)return Et(t,(o,i)=>_n(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return xt(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),Et(i,(l,a)=>_n(e,n,o,l,a,r,s)),xt(e,o,!1),r&&e.patches_&&De("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function _n(e,t,r,n,o,i,s){if(ce(o)){let l=i&&t&&t.type_!==3&&!rr(t.assigned_,n)?i.concat(n):void 0,a=vt(e,o,l);if(Ln(r,n,a),ce(a))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(Te(o)&&!Rt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;vt(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&xt(e,o)}}function xt(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&cr(t,r)}function Fi(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:$n(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=lr;r&&(o=[n],i=ot);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return n.draft_=l,n.revoke_=s,l}var lr={get(e,t){if(t===ae)return e;let r=ke(e);if(!rr(r,t))return Ui(e,r,t);let n=r[t];return e.finalized_||!Te(n)?n:n===er(e.base_,t)?(tr(e),e.copy_[t]=ar(n,e)):n},has(e,t){return t in ke(e)},ownKeys(e){return Reflect.ownKeys(ke(e))},set(e,t,r){let n=kn(ke(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=er(ke(e),t),i=o?.[ae];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(Pi(r,o)&&(r!==void 0||rr(e.base_,t)))return!0;tr(e),sr(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 er(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,tr(e),sr(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=ke(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){pe(11)},getPrototypeOf(e){return Ye(e.base_)},setPrototypeOf(){pe(12)}},ot={};Et(lr,(e,t)=>{ot[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ot.deleteProperty=function(e,t){return ot.set.call(this,e,t,void 0)};ot.set=function(e,t,r){return lr.set.call(this,e[0],t,r,e[0])};function er(e,t){let r=e[ae];return(r?ke(r):e)[t]}function Ui(e,t,r){let n=kn(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function kn(e,t){if(!(t in e))return;let r=Ye(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=Ye(r)}}function sr(e){e.modified_||(e.modified_=!0,e.parent_&&sr(e.parent_))}function tr(e){e.copy_||(e.copy_=nr(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Bi=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,...c){return s.produce(a,u=>r.call(this,u,...c))}}typeof r!="function"&&pe(6),n!==void 0&&typeof n!="function"&&pe(7);let o;if(Te(t)){let i=Cn(this),s=ar(t,void 0),l=!0;try{o=r(s),l=!1}finally{l?or(i):ir(i)}return xn(i,n),Sn(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===Rn&&(o=void 0),this.autoFreeze_&&cr(o,!0),n){let i=[],s=[];De("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else pe(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,a=>t(a,...l));let n,o;return[this.produce(t,r,(s,l)=>{n=s,o=l}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Te(e)||pe(8),ce(e)&&(e=Pe(e));let t=Cn(this),r=ar(e,void 0);return r[ae].isManual_=!0,ir(t),r}finishDraft(e,t){let r=e&&e[ae];(!r||!r.isManual_)&&pe(9);let{scope_:n}=r;return xn(n,t),Sn(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=De("Patches").applyPatches_;return ce(e)?n(e,t):this.produce(e,o=>n(o,t))}};function ar(e,t){let r=St(e)?De("MapSet").proxyMap_(e,t):_t(e)?De("MapSet").proxySet_(e,t):Fi(e,t);return(t?t.scope_:$n()).drafts_.push(r),r}function Pe(e){return ce(e)||pe(10,e),Tn(e)}function Tn(e){if(!Te(e)||Rt(e))return e;let t=e[ae],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=nr(e,t.scope_.immer_.useStrictShallowCopy_)}else r=nr(e,!0);return Et(r,(n,o)=>{Ln(r,n,Tn(o))}),t&&(t.finalized_=!1),r}var le=new Bi,ur=le.produce,ld=le.produceWithPatches.bind(le),ud=le.setAutoFreeze.bind(le),dd=le.setUseStrictShallowCopy.bind(le),fd=le.applyPatches.bind(le),pd=le.createDraft.bind(le),hd=le.finishDraft.bind(le);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},O={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},Ge={NOT:0};var E=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},ne=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var dr=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}')`)},Dn=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 Pn=(e,t,r=!1)=>{if(t===null)return new ne(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new ne(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new ne(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new ne(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},Nn=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new ne(`Unknown function '${e}' (${r})`)};var zi=(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=L(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},L=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return J(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return J(e.path,r,n);if(e.type===m.INTERPOLATION)return qi(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return jn(e,t,r,n);case m.BINARY:return Mn(e,t,r,n);case m.UNARY:return Fn(e,t,r,n);case m.CONDITIONAL:return Yi(e,t,r,n);case m.LOOP:return Qi(e,t,r,n);case m.OBJECT:return es(e,t,r,n);case m.ARRAY:return ts(e,t,r,n);case m.PARTIAL:return rs(e,t,r,n);case m.PATH_REFERENCE:return ns(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Vn=new Map,Wi=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 l=s.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},J=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=Vn.get(e);if(!n){let i=[],s="",l=0;for(let a=0;a<e.length;a++){let c=e[a];c==="["?(l++,s+=c):c==="]"?(l--,s+=c):c==="."&&l===0?s&&(i.push(s),s=""):s+=c}s&&i.push(s),n=[];for(let a of i){let c=Wi(a.trim());n.push(...c)}Vn.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},qi=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},jn=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Nn(e.name,o);let s=e.args.map(l=>L(l,t,r,n));return i(...s)},Ce=(e,t,r,n)=>{if(e.var&&!e.type)return J(e.var,r,n);switch(e.type){case m.VARIABLE:return J(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return Mn(e,t,r,n);case m.UNARY:return Fn(e,t,r,n);case m.FUNCTION:return jn(e,t,r,n);default:return L(e,t,r,n)}},Mn=(e,t,r,n)=>{if(e.op===O.AND||e.op===O.OR){let s=Ce(e.left,t,r,n),l=Ce(e.right,t,r,n);switch(e.op){case O.AND:return s&&l;case O.OR:return s||l}}let o=L(e.left,t,r,n),i=L(e.right,t,r,n);switch(e.op){case O.EQ:return o==i;case O.NEQ:return o!=i;case O.GT:return o>i;case O.LT:return o<i;case O.GTE:return o>=i;case O.LTE:return o<=i;case O.IN:return Array.isArray(i)?i.includes(o):!1;case O.ADD:if(typeof o!="number"||typeof i!="number")throw new ne(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case O.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new ne(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Fn=(e,t,r,n)=>{let o=e.op===Ge.NOT?Ce(e.operand,t,r,n):L(e.operand,t,r,n);if(e.op===Ge.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Hi=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(J(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?L(a.parsedKey,t,r,n):a.key,u=a.value;if(u.type===m.LITERAL)l[c]=u.value;else if(u.type===m.VARIABLE)l[c]=J(u.path,r,n);else if(u.type===m.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===m.VARIABLE){let p=J(f.path,r,n);d.push(p!=null?String(p):"")}else{let p=L(f,t,r,n);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=L(u,t,r,n)}return l}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?L(a.parsedKey,t,r,n):a.key,u=a.value;if(u.type===m.LITERAL)l[c]=u.value;else if(u.type===m.VARIABLE)l[c]=J(u.path,r,n);else if(u.type===m.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===m.VARIABLE){let p=J(f.path,r,n);d.push(p!=null?String(p):"")}else{let p=L(f,t,r,n);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=L(u,t,r,n)}return l}}}return null},Yi=(e,t,r,n)=>{let o=Hi(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||Ce(s,t,r,n))return L(e.bodies[i],t,r,n)}return Un},Gi=(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 l=[];for(let a=0;a<t.length;a++){let c=t[a];if(c[s]){let u={};for(let d of i.properties){let f=d.key,p=d.value;if(p.type===m.LITERAL)u[f]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)u[f]=c;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);u[f]=c[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(c!=null?String(c):"");else if(b.startsWith(n+".")){let A=b.substring(n.length+1),v=c[A];h.push(v!=null?String(v):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[f]=h.join("")}else return null}l.push(u)}}return l}}}return null},Ki=(e,t)=>{let r=e.body,n=e.itemVar,o=Gi(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let l of r.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of r.properties){let a=l.key,c=l.value;if(c.type===m.LITERAL)i.push({key:a,type:"literal",value:c.value});else if(c.type===m.VARIABLE){let u=c.path;if(u===n)i.push({key:a,type:"item"});else if(u.startsWith(n+".")){let d=u.substring(n.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:a,type:"prop",prop:d});else{s=!1;break}}else{s=!1;break}}else if(c.type===m.INTERPOLATION&&c.parts.length===1){let u=c.parts[0];if(u.type===m.VARIABLE){let d=u.path;if(d===n)i.push({key:a,type:"item_string"});else if(d.startsWith(n+".")){let f=d.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 l=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 c=t[a];l[a]={id:c.id,title:c.title!=null?String(c.title):"",completed:c.completed}}else for(let a=0;a<t.length;a++){let c=t[a],u={};for(let d of i)if(d.type==="literal")u[d.key]=d.value;else if(d.type==="item")u[d.key]=c;else if(d.type==="prop")u[d.key]=c[d.prop];else if(d.type==="item_string")u[d.key]=c!=null?String(c):"";else if(d.type==="prop_string"){let f=c[d.prop];u[d.key]=f!=null?String(f):""}l[a]=u}return l}}return null},Ji=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let l=e.itemVar,a=e.indexVar;for(let c=0;c<o.length;c++){let u=o[c],d={},f={...n,[l]:u,...a&&{[a]:c}};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__,[l]:`${p}[${c}]`,...a&&{[a]:c}};for(let h of s.properties){let g=h.parsedKey?L(h.parsedKey,t,r,f):h.key,y=h.value;if(y.type===m.LITERAL)d[g]=y.value;else if(y.type===m.VARIABLE){let b=y.path;if(b===l)d[g]=u;else if(b===a)d[g]=c;else if(b.startsWith(l+".")){let A=b.substring(l.length+1);!A.includes(".")&&!A.includes("[")?d[g]=u[A]:d[g]=J(b,r,{...n,[l]:u,...a&&{[a]:c}})}else d[g]=J(b,r,{...n,[l]:u,...a&&{[a]:c}})}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,S;if(v===l)S=u;else if(v===a)S=c;else if(v.startsWith(l+".")){let T=v.substring(l.length+1);!T.includes(".")&&!T.includes("[")?S=u[T]:S=J(v,r,{...n,[l]:u,...a&&{[a]:c}})}else S=J(v,r,{...n,[l]:u,...a&&{[a]:c}});b.push(S!=null?String(S):"")}else{let v={...n,[l]:u,...a&&{[a]:c}},S=L(A,t,r,v);b.push(S!=null?String(S):"")}d[g]=b.join("")}else{let b={...n,[l]:u,...a&&{[a]:c}};d[g]=L(y,t,r,b)}}i.push(d)}return i}return null},Xi=(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 l=s.properties[0],a=s.properties[1];if(l.key==="id"&&l.value.type===m.VARIABLE&&l.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===m.CONDITIONAL){let c=[];for(let u=0;u<t.length;u++){let d=t[u];if(d.visible){let f={id:d.id};d.highlighted?(f.highlight=!0,f.message=`This item is highlighted: ${d.name}`):(f.highlight=!1,f.message=d.name),c.push(f)}}return c}}}}return null},Qi=(e,t,r,n)=>{let o=L(e.iterable,t,r,n);if(!Array.isArray(o)){let c,u=!1;if(e.iterable.type===m.FUNCTION){u=!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(", ");c=`${e.iterable.name}(${f})`}else c=e.iterable.path||"undefined";let d=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${c}`;throw Pn(d,o,u)}if(!e.indexVar){let c=Xi(e,o,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=Ki(e,o);if(c!==null)return c}let i=Ji(e,t,r,n,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(n&&n.__paths__&&l){let c=l.split("."),u=c[0];u in n.__paths__&&(l=n.__paths__[u],c.length>1&&(l+="."+c.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(c=>c.type===m.OBJECT&&c.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let c=0;c<o.length;c++){let u=e.indexVar?{...n,[e.itemVar]:o[c],[e.indexVar]:c}:{...n,[e.itemVar]:o[c]};u.__paths__||(u.__paths__=n.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${c}]`},e.indexVar&&(u.__paths__[e.indexVar]=c);let d=L(e.body,t,r,u);if(Array.isArray(d)&&d.length===1&&!a){let f=d[0];s.push(f===void 0?{}:f)}else s.push(d===void 0?{}:d)}return s},Zi=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(o.parsedKey,t,r,n):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let l={},a={},c=!0;for(let u of s.properties){let d=u.parsedKey?L(u.parsedKey,t,r,n):u.key,f=u.value;if(f.type===m.LITERAL)a[d]=f.value;else if(f.type===m.VARIABLE)a[d]=J(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=J(h.path,r,n);p.push(g!=null?String(g):"")}else{c=!1;break}if(!c)break;a[d]=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]=J(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=J(A.path,r,n);b.push(v!=null?String(v):"")}else{c=!1;break}if(!c)break;p[g]=b.join("")}else{c=!1;break}}if(!c)break;a[d]=p}else{c=!1;break}}if(c)return l[i]=a,l}}return null},es=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!Ce(e.whenCondition,o,r,n))return;let i=Zi(e,t,r,n);if(i!==null)return i;if(e.fast){let c={};for(let u of e.properties){let d=u.parsedKey?L(u.parsedKey,t,r,n):u.key,f=u.value;if(f.type===m.LITERAL)c[d]=f.value;else if(f.type===m.VARIABLE)c[d]=J(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=J(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=L(h,t,r,n);p.push(g!=null?String(g):"")}c[d]=p.join("")}else c[d]=L(f,t,r,n)}return c}let s={},l=null,a=!1;for(let c of e.properties)if(!c.key.startsWith("$if ")&&!c.key.match(/^\$if\s+\w+.*:?$/)&&!c.key.startsWith("$elif")&&!c.key.startsWith("$else")&&!c.key.startsWith("$for ")){a=!0;break}for(let c of e.properties)if(c.key.startsWith("$if ")||c.key.match(/^\$if\s+\w+.*:?$/)){let u=L(c.value,t,r,n);if(!a&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(c.key.startsWith("$for ")){if(e.properties.length===1)return L(c.value,t,r,n)}else{let u=c.value;if(u&&u.type===m.OBJECT&&u.properties){let d=u.properties.find(f=>f.key.startsWith("$for "));if(d){let f=L(d.value,t,r,n);f!==void 0&&(s[c.key]=f)}else{let f=L(c.value,t,r,n);f!==void 0&&(s[c.key]=f)}}else{let d=c.parsedKey?L(c.parsedKey,t,r,n):c.key,f=L(c.value,t,r,n);f!==void 0&&(s[d]=f)}}return s},Un={},ts=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=L(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,r,n);s!==Un&&s!==void 0&&o.push(s)}return o},rs=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},a=t.functions||t;if(s&&!Ce(s,a,r,n))return;if(!l[o])throw new ne(`Partial '${o}' is not defined`);let c=n._partialStack||[];if(c.includes(o))throw new ne(`Circular partial reference detected: ${o}`);let u=l[o],d=r,f={...n,_partialStack:[...c,o]};if(n){d={...r};for(let p of Object.keys(n))p.startsWith("_")||(d[p]=n[p])}if(i){let p=L(i,t,r,n);d={...d,...p}}return L(u,t,d,f)},ns=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],l=i.slice(1);if(!n||!(s in n))throw new ne(`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 ne(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=n.__paths__[s];if(typeof a=="number"){if(l.length>0)throw new ne(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return l.length>0&&(a+="."+l.join(".")),a};var fr=zi;var os=/\$\{([^}]*)\}/g,is=/#\{([^}]*)\}/g,zn=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=ss(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},ss=(e,t={})=>e.trim()?as(e).map(n=>cs(n.trim(),t)):[],as=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],a=s>0?e[s-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,r+=l):o&&l===i&&a!=="\\"?(o=!1,i="",r+=l):!o&&l==="("?(n++,r+=l):!o&&l===")"?(n--,r+=l):!o&&l===","&&n===0?(t.push(r),r=""):r+=l}return r&&t.push(r),t},cs=(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=zn(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:l,type:a}of o){let c=0;for(;c<n.length;){let u=Ne(n.substring(c),l);if(u===-1)break;let d=c+u;d>i&&(i=d,s={op:l,type:a}),c=d+l.length}}if(i!==-1)try{return X(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},Wn=/^\w+\(.*\)$/,ls=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,us=e=>{if(!(!e||e.trim()===""||Wn.test(e))&&ls.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}"`)},Bn=e=>{let t=e.trim();if(Wn.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}},it=(e,t={})=>{let r=e.trim();us(r);let n=zn(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}},pr=(e,t={})=>{let r=e,n=[];(e.includes("\\${")||e.includes("\\#{"))&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),r=r.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${n.length}__`;return n.push(u),d}),r=r.replace(/\\(#\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${n.length}__`;return n.push(u),d}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(os)],i=[...r.matchAll(is)],s=[...o.map(c=>({match:c,type:"variable"})),...i.map(c=>({match:c,type:"pathref"}))].sort((c,u)=>c.match.index-u.match.index);if(s.length===0){let c=r;for(let u=0;u<n.length;u++)c=c.replace(`__ESCAPED_${u}__`,n[u]);return{type:m.LITERAL,value:c}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:c,type:u}=s[0];try{return u==="variable"?it(c[1],t):Bn(c[1])}catch(d){if(d.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw d}}let l=[],a=0;for(let{match:c,type:u}of s){let[d,f]=c,p=c.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&&l.push(h)}try{let h;u==="variable"?h=it(f.trim(),t):h=Bn(f.trim()),l.push(h)}catch(h){if(h.message==="Invalid array index syntax")l.push(d);else throw h}a=p+d.length}if(a<r.length){let c=r.substring(a);for(let u=0;u<n.length;u++)c=c.replace(`__ESCAPED_${u}__`,n[u]);c&&l.push(c)}return{type:m.INTERPOLATION,parts:l}};var gr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Yn=e=>Object.keys(e),Z=e=>e.join("."),Se=(e,t,r)=>{let n=Yn(e).filter(o=>!t.has(o));if(n.length>0)throw new E(`Unexpected key '${n[0]}' in condition JSON at '${Z(r)}'`)},_e=(e,t)=>typeof e=="string"?pr(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?fs(e,t):ps(e,t):{type:m.LITERAL,value:e},ds=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}},fs=(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=ds(i),c=Object.keys(a);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let u=Hn(c[0],a[c[0]],t,!0);r.push(u),n=!0;continue}}catch(a){throw a instanceof E?a:new E(a.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let a=Hn(l[0],i[l[0]],t);r.push(a),n=!0;continue}}let s=_e(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}},ps=(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"],c=[];for(let[b]of i)for(let A of a)if(b===A||b.startsWith(A+" ")||b.startsWith(A+"#")){c.push(A);break}if(c.length>0)throw new E(`Cannot use $partial with ${c.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:d,...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=_e(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:u,data:g};return d!==void 0&&(y.whenCondition=qn(d,t)),y}for(let[a,c]of i)if(a==="$when"){if(o!==null)throw new E("Multiple '$when' directives on the same object are not allowed");if(c==null)throw new E("Missing condition expression after '$when'");o=qn(c,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,c]=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 u=hs(i,s,t);r.push({key:a,value:u.node}),n=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let u=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",d=u?`:${u}`:"";throw new E(`$for loops must be inside arrays - use '- $for${d} item in items:' instead of '$for${d} 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 u=_e(c,t);(u.type===m.FUNCTION||u.type===m.CONDITIONAL||u.type===m.PARTIAL||u.type===m.OBJECT&&!u.fast||u.type===m.ARRAY&&!u.fast)&&(n=!0);let d=pr(a,t),f={key:a,value:u};(d.type!==m.LITERAL||d.value!==a)&&(f.parsedKey=d),r.push(f),s++}}}let l={type:m.OBJECT,properties:r,fast:!n};return o&&(l.whenCondition=o),l},hs=(e,t,r={})=>{let n=[],o=[],i=t,[s,l]=e[i],a=null,c;if(s.startsWith("$if#")){let d=s.match(/^\$if#(\w+)\s+(.+)$/);if(d)a=d[1],c=d[2];else throw new E(`Invalid conditional syntax: ${s}`)}else c=s.substring(4),c.endsWith(":")&&(c=c.slice(0,-1).trim());dr(c);let u=X(c,r);for(n.push(u),o.push(_e(l,r)),i++;i<e.length;){let[d,f]=e[i],p=!1,h;if(a?d.startsWith(`$elif#${a} `)?(h=d.substring(`$elif#${a} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(d===`$else#${a}`||d===`$else#${a}:`)&&(p=!0,h=null):d.startsWith("$elif ")?(h=d.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(d==="$else"||d==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{dr(h);let g=X(h,r);n.push(g)}if(o.push(_e(f,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:a},nextIndex:i}},hr={eq:O.EQ,neq:O.NEQ,gt:O.GT,gte:O.GTE,lt:O.LT,lte:O.LTE,in:O.IN,add:O.ADD,sub:O.SUBTRACT},mr={all:O.AND,any:O.OR},ms=new Set(["var","literal","call","not",...Object.keys(hr),...Object.keys(mr)]),gs=(e,t,r)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${Z(r)}' requires an array`);if(e.length!==2)throw new E(`Condition JSON operator '${t}' at '${Z(r)}' requires exactly 2 operands`);return e},ys=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${Z(o)}' requires an array`);if(e.length===0)throw new E(`Condition JSON operator '${t}' at '${Z(o)}' requires at least 1 condition`);return e.map((s,l)=>Ie(s,n,[...o,l])).reduce((s,l)=>({type:m.BINARY,op:r,left:s,right:l}))},bs=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],Se(e,new Set(["call","args"]),r);else if(gr(e.call))n=e.call.name,o=e.call.args??[],Se(e,new Set(["call"]),r),Se(e.call,new Set(["name","args"]),[...r,"call"]);else throw new E(`Condition JSON call at '${Z(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new E(`Condition JSON call at '${Z(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new E(`Invalid condition JSON function name '${n}' at '${Z(r)}'`);if(!Array.isArray(o))throw new E(`Condition JSON call '${n}' at '${Z(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 '${Z(r)}' must be wrapped in an operator or { literal: [...] }`);if(!gr(e))throw new E(`Invalid condition JSON value at '${Z(r)}'`);let n=Yn(e);if(n.length===0)throw new E(`Condition JSON object at '${Z(r)}' must contain an operator`);let o=n.filter(s=>ms.has(s));if(o.length===0)throw new E(`Unknown condition JSON operator '${n[0]}' at '${Z(r)}'`);if(o.length>1)throw new E(`Condition JSON at '${Z(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(Se(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new E(`Condition JSON var at '${Z(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return Se(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return bs(e,t,r);if(i==="not")return Se(e,new Set(["not"]),r),{type:m.UNARY,op:Ge.NOT,operand:Ie(e.not,t,[...r,"not"])};if(i in mr)return Se(e,new Set([i]),r),ys(e[i],i,mr[i],t,[...r,i]);if(i in hr){Se(e,new Set([i]),r);let s=gs(e[i],i,[...r,i]);return{type:m.BINARY,op:hr[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 '${Z(r)}'`)},qn=(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 gr(e)||Array.isArray(e)?Ie(e,t):{type:m.LITERAL,value:e}},X=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let c=e.slice(1,-1),u=0,d=!0;for(let f=0;f<c.length;f++)if(c[f]==="("?u++:c[f]===")"&&u--,u<0){d=!1;break}if(d&&u===0)return X(c,t)}let r=Ne(e,"||");if(r!==-1)return{type:m.BINARY,op:O.OR,left:X(e.substring(0,r).trim(),t),right:X(e.substring(r+2).trim(),t)};let n=Ne(e,"&&");if(n!==-1)return{type:m.BINARY,op:O.AND,left:X(e.substring(0,n).trim(),t),right:X(e.substring(n+2).trim(),t)};let o=[{op:">=",type:O.GTE},{op:"<=",type:O.LTE},{op:"==",type:O.EQ},{op:"!=",type:O.NEQ},{op:">",type:O.GT},{op:"<",type:O.LT},{op:" in ",type:O.IN}];for(let{op:c,type:u}of o){let d=Ne(e,c);if(d!==-1)return{type:m.BINARY,op:u,left:X(e.substring(0,d).trim(),t),right:X(e.substring(d+c.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:O.ADD},{op:" - ",type:O.SUBTRACT}];for(let{op:c,type:u}of l){let d=0;for(;d<e.length;){let f=Ne(e.substring(d),c);if(f===-1)break;let p=d+f;p>i&&(i=p,s={op:c,type:u}),d=p+c.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 c of a)if(Ne(e,c)!==-1)throw new E(`Arithmetic operations are not allowed in conditionals: "${c}"`);return e.startsWith("!")?{type:m.UNARY,op:Ge.NOT,operand:X(e.substring(1).trim(),t)}:Gn(e,t)},Ne=(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},Is=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}},Gn=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return it(r,t);let o=Is(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return it(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},As=(e,t=!1)=>{let r=t?"$each":"$for";try{Dn(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}},Hn=(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],l=i[2].trim();As(l,n);let a=l.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let y=n?"$each":"$for";throw new E(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${l}')`)}let c=a[1].trim(),u=a[2].trim(),d,f=null;if(c.includes(",")){let y=c.split(",").map(b=>b.trim());if(y.length!==2)throw new E(`Invalid loop variables: ${c}. Expected format: "item" or "item, index"`);d=y[0],f=y[1]}else d=c;let p=["this","undefined","null","true","false"];if(p.includes(d))throw new E(`Reserved variable name: ${d}`);if(f&&p.includes(f))throw new E(`Reserved variable name: ${f}`);let h=Gn(u,r),g=_e(t,r);return{type:m.LOOP,itemVar:d,indexVar:f,iterable:h,body:g,flatten:s!=="nested"}};var ws=(e,t={})=>{let{functions:r={}}=t;return _e(e,r)},Ot=ws;var st={};Ti(st,{now:()=>Es});var Es=()=>Date.now();var vs=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...st,...n},s=Ot(e,{functions:i}),l={};for(let[a,c]of Object.entries(o))l[a]=Ot(c,{functions:i});return fr(s,t,{functions:i,partials:l})},se=vs;var xs=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Cs=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Ss=(e,t)=>{if(xs(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression");return X(e,t)}return Ie(e,t)},_s=(e,t={},r={})=>{let n=Cs(r),o={...st,...n},i=Ss(e,o);return!!Ce(i,{functions:o,partials:{}},t,{})},yr=_s;var ct=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return yr(e,t)},eo=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=a=>a,transformActionFirstArgument:l=a=>a}=r;for(let[a,c]of Object.entries(t))a!=="createInitialState"&&(a.startsWith("select")?o[a]=(...u)=>c(s(n),...u):i[a]=(...u)=>{let d;return n=ur(n,p=>{let h=c(l(p),...u);d=h!==void 0&&!ce(h)?h:void 0}),d});return{...o,...i}},kt=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return ur(n,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var Rs=(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{}}},me=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),at=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),to=e=>{let t=ce(e)?Pe(e):e;return structuredClone(t)},Re=e=>me(e,"computed"),Ke=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Re(t[r]))),Os=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),br=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},Ls=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=Os(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 br(s,i)}return n==="runtime"?br(t.runtime,r.slice(1)):br(t,r)},$s=(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)`)},Kn=(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`)},ks=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},he=(e,t,r,n)=>($s(e,t,n),t.map(o=>$t(o,r))),de=(e,t,r,n)=>{let o=he(e,t,r,n);return o.forEach(i=>ks(e,i)),o},Ts=(e,t,r)=>{switch(e){case"var":return Ls(t,r);case"add":{let[n,o]=de(e,t,r,2);return n+o}case"sub":{let[n,o]=de(e,t,r,2);return n-o}case"mul":{let[n,o]=de(e,t,r,2);return n*o}case"div":{let[n,o]=de(e,t,r,2);return n/o}case"mod":{let[n,o]=de(e,t,r,2);return n%o}case"neg":{let[n]=de(e,t,r,1);return-n}case"round":{let[n]=de(e,t,r,1);return Math.round(n)}case"floor":{let[n]=de(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=de(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=de(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=de(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=de(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=he(e,t,r,2);return n==o}case"neq":{let[n,o]=he(e,t,r,2);return n!=o}case"gt":{let[n,o]=he(e,t,r,2);return n>o}case"gte":{let[n,o]=he(e,t,r,2);return n>=o}case"lt":{let[n,o]=he(e,t,r,2);return n<o}case"lte":{let[n,o]=he(e,t,r,2);return n<=o}case"in":{let[n,o]=he(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return Kn(e,t),t.every(n=>!!$t(n,r));case"or":case"any":return Kn(e,t),t.some(n=>!!$t(n,r));case"not":{let[n]=he(e,t,r,1);return!n}case"length":{let[n]=he(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:at(n)?Object.keys(n).length:0}case"includes":{let[n,o]=he(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return to(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},$t=(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 Ts(n,o,t)},Ds=(e,t={})=>ct(e,{variables:t.variables,runtime:t.runtime}),Ps=(e,t)=>{if(!at(e))throw new Error(`${t} must be an object`);let r=me(e,"expr"),n=me(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},Ir=(e,t,r)=>(Ps(e,t),me(e,"value")?to(e.value):$t(e.expr,r)),Ns=(e,t={},r="unknown")=>{if(!at(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=me(e,"expr"),o=me(e,"value");if(me(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(!at(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let l=e.branches[s];if(!at(l))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!me(l,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(Ds(l.when,t))return Ir(l,`Computed variable "${r}" branch ${s}`,t)}return Ir(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 Ir(e,`Computed variable "${r}"`,t)},Vs=(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}`)}},Tt=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=Ke(e,r),i=Object.entries(r).filter(([,d])=>Re(d)).map(([d])=>d),s={},l=[],a=d=>{if(me(s,d))return s[d];let f=r[d];if(!Re(f))return o[d];let p=l.indexOf(d);if(p>=0){let h=[...l.slice(p),d].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}l.push(d);try{let h=Ns(f.computed,u,d);return Vs(d,f.type,h),s[d]=h,h}finally{l.pop()}},c=new Proxy({},{get:(d,f)=>{if(typeof f=="string")return a(f)},has:(d,f)=>typeof f=="string"&&(me(o,f)||i.includes(f)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(d,f)=>{if(!(typeof f!="string"||!me(o,f)&&!i.includes(f)))return{enumerable:!0,configurable:!0}}}),u={variables:c,runtime:t,resolveVariable:a};return n?(i.forEach(d=>{a(d)}),{...o,...s}):c},js=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>Tt({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),Er=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(Re(o))return;let i=Rs(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},Dt=(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(", ")}`)},Pt=(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(", ")}`)},Ms=2,Jn=12,ro=(e=Ms)=>{if(!Number.isInteger(e)||e<0||e>Jn)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${Jn}.`);return e},Fs=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},Lt=e=>typeof e=="number"&&Number.isFinite(e),vr=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!Lt(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!Lt(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!Lt(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}".`);ro(o.roundTo)}}},Nt=(e,t,r,n={})=>{let o=(s,l,a)=>{let c=s??l;if(!Lt(c))throw new Error(`Operation "${t}" requires ${a} to be a number.`);return c},i=s=>{let l=o(s,void 0,"value");if(l===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return l};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return Fs(o(e,0,"current value")/i(r),ro(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 no=(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()))},Us=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let l=i.character?.sprite;return l&&Object.keys(l).length>0&&(s.sprite=l),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},Xn=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};return e.transformId!==void 0&&(t.transformId=e.transformId),e.loop!==void 0&&(t.loop=e.loop),t},Qn=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},Zn=(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,Bs=(e,t)=>{let r={},n=Zn(Xn(e),Xn(t)),o=Zn(Qn(e),Qn(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},xr=(e={},t={})=>{let r={},n=["sfx","voice"],o=l=>{let a=e[l],c=t[l];c&&!a?r[l]={changeType:"add",data:c}:a&&!c?n.includes(l)||(r[l]={changeType:"delete",data:a}):a&&c&&JSON.stringify(a)!==JSON.stringify(c)&&(r[l]={changeType:"update",data:c})},i=Bs(e.background,t.background);i&&(r.background=i),o("screen"),o("bgm"),o("voice");let s=Us(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},Cr=(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(l=>{let a={...l};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},Ws=(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},qs={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"])},oo=(e,t)=>{let r=e[e.length-1];return r?qs[r]?.has(t)===!0:!1},Ar=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Ar(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,oo(r,n)?o:Ar(o,t,[...r,n])])):Ws(e,t),wr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>wr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,oo(r,n)?o:wr(o,t,[...r,n])])):typeof e=="string"?se(e,t):e,Sr=(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=Ar(e,t._event);return wr(r,t)};var oe=e=>structuredClone(ce(e)?Pe(e):e),Y=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),io=e=>e?.animations?.playback?.continuity==="persistent",B=(e,t)=>Y(e??{},t)&&e[t]!==void 0,lt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:oe(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Hs=e=>B(e,"opacity")||B(e,"blur"),ao=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Ys=e=>ao.some(t=>B(e,t)),Gs=(e,t,r)=>{let n=e[r];return n?.id===t?.id?n:e.find(o=>o.id===t?.id)},Ks=(e,t)=>{if(!t)return e;for(let r of ao)!B(e,r)&&B(t,r)&&(e[r]=t[r]),Y(e,r)&&e[r]===void 0&&delete e[r];return e},Js=(e,t)=>(t&&(!B(e,"opacity")&&B(t,"opacity")&&(e.opacity=t.opacity),!B(e,"blur")&&B(t,"blur")&&(e.blur=oe(t.blur)),Y(e,"opacity")&&e.opacity===void 0&&delete e.opacity,Y(e,"blur")&&e.blur===void 0&&delete e.blur),e),co=(e,t,r=[])=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let n=e.map((o,i)=>{let s=Gs(r,o,i),l=t(o),a=Hs(o),c=Ys(o),u=Y(o,"animations"),d=oe(o);return!l&&(a||c)&&s&&(d={...oe(s),...d},u||delete d.animations),Js(Ks(d,s),s)}).filter(o=>t(o)||o.animations);return{hasValidItems:n.length>0,processedItems:n}},Xs=e=>{if(e){if(e.character&&Y(e.character,"name"))return e.character.name;if(Y(e,"characterName"))return e.characterName}},lo=e=>!!e?.character&&Y(e.character,"sprite"),Qs=e=>{let t={},r=!1,n=Xs(e);return n!==void 0&&(t.name=n,r=!0),lo(e)&&(t.sprite=oe(e.character.sprite),r=!0),r?t:void 0},so=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Zs=({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=>oe(o)):delete e.initialRevealedContent,e.content=[...n,...t]},ea=()=>({}),ta=(e,t)=>{if(!t.screen)return;let r=B(t.screen,"opacity"),n=B(t.screen,"blur"),o=Y(t.screen,"animations");if(!r&&!n){o||delete e.screen;return}let i=e.screen,s={};if(r?s.opacity=t.screen.opacity:B(i,"opacity")&&(s.opacity=i.opacity),n?s.blur=oe(t.screen.blur):B(i,"blur")&&(s.blur=oe(i.blur)),Y(s,"opacity")&&s.opacity===void 0&&delete s.opacity,Y(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},ra=(e,t)=>{if(t.background){let r=B(t.background,"resourceId"),n=B(t.background,"colorId"),o=B(t.background,"opacity"),i=B(t.background,"blur"),{animationsOnly:s,state:l}=lt(t.background,u=>B(u,"resourceId")||B(u,"colorId")||B(u,"opacity")||B(u,"blur"));if(s){e.background=e.background?{...oe(e.background),...l}:l;return}if(!r&&!n&&!o&&!i){delete e.background;return}let a=e.background,c=oe(t.background);if(!r&&a?.resourceId&&(c.resourceId=a.resourceId,!Y(c,"transformId")&&a.transformId&&(c.transformId=a.transformId)),!n&&a?.colorId&&(c.colorId=a.colorId),!o&&B(a,"opacity")&&(c.opacity=a.opacity),!i&&B(a,"blur")&&(c.blur=oe(a.blur)),Y(c,"resourceId")&&c.resourceId===void 0&&delete c.resourceId,Y(c,"colorId")&&c.colorId===void 0&&delete c.colorId,Y(c,"animations")&&c.animations===void 0&&delete c.animations,Y(c,"opacity")&&c.opacity===void 0&&delete c.opacity,Y(c,"blur")&&c.blur===void 0&&delete c.blur,!c.resourceId&&!c.colorId){delete e.background;return}a?.resourceId===c.resourceId&&a?.transformId===c.transformId&&!Y(c,"animations")&&io(a)&&(c.animations=oe(a.animations)),e.background=c}else e.background?.animations&&!io(e.background)&&(e.background.animations={})},na=(e,t)=>{if(!t.dialogue){e.dialogue&&(so(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:c,state:u}=lt(t.dialogue.ui,d=>!!d.resourceId);c?e.dialogue.ui={...e.dialogue.ui,...u}: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&&Zs({dialogueState:e.dialogue,content:t.dialogue.content,append:n});let o=Y(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=Y(t.dialogue,"characterId"),s=Qs(t.dialogue),l=s!==void 0,a=lo(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,l?e.dialogue.character=!i&&o&&e.dialogue.character?{...oe(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,a||so(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 c={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(c.character=oe(e.dialogue.character)),e.dialogue.lines.push(c)}},oa=(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},ia=(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}}},sa=(e,t)=>{if(t.visual){let{hasValidItems:r,processedItems:n}=co(t.visual.items,o=>!!o.resourceId,e.visual?.items||[]);r?e.visual={items:n}: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}=co(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},ca=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},la=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=lt(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},ua=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=lt(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},da=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=lt(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=oe(t.form)}else e.form&&delete e.form},fa=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},pa=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},ha=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},Ve=e=>kt(ea,[ha,ta,ra,oa,ia,sa,na,aa,ca,la,ua,da,fa,pa])(e);var ma=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"}}),je=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),ut=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),uo=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"]),Rr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),ga=(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]}},Je=e=>Object.fromEntries(Object.entries(ma).map(([t,r])=>{let n=ga(e,r.source),o=n!==void 0?n:je[t]??ut[t];return[t,o]})),Ee=(e,t)=>Je(e)[t],fo=(e={})=>Object.fromEntries(_r.map(t=>[t,e[t]??je[t]]));var Xe=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:Xe.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:Xe.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:Xe.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:Xe.VISUAL_BEHIND_CHOICE,FOREGROUND:Xe.VISUAL_FOREGROUND}),Or=ve.BEHIND_DIALOGUE,Lr=Object.freeze(Object.values(ve).sort((e,t)=>e-t));var Oe={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:no},ya=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,ba=(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},jt=(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),l=ya.exec(s);if(l){let[,a,c,u]=l,d=ba(t,u);if(!Array.isArray(d))continue;let f=Array.isArray(i[s])?i[s]:[];d.forEach((p,h)=>{let g={...t,[a]:p};c&&(g[c]=h),f.forEach(y=>{let b=jt(y,g,r),A=se(b,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(jt(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=jt(i,t,r)}),n},Gr=({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".`)},Ia=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);if(Gr({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n!==void 0){let s=va(n,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},Aa=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Gr({animationType:e.type,animationId:t,animationPath:r}),e.type},wa=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Ea=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},va=(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},xa=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},Kr=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Co=e=>e?.playback?.continuity==="persistent",Vr=e=>Array.isArray(e)?e.map(Vr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=Vr(e[r]),t),{}),Ft=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(Vr(t))},So=(e=[])=>e.filter(t=>Co(t)).map(t=>structuredClone(t)),_o=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,$r=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,_o(r)),0),Ro=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max($r(e.tween),$r(e.prev?.tween),$r(e.next?.tween),_o(e.mask?.progress))/xa(e),po=({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(Ft).filter(Boolean));return e.some(n=>{if(!Co(n))return!1;let o=Ft(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||po({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:po({animationInstances:e,activePersistentAnimations:o}),Ca=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Sa=(e,t)=>{if(Ca(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},_a=({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?Ia({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},Ra=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Gr({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},Jr=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(Ra(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},jr=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=se(e,t);return r&&typeof r=="object"?e:r},Mr=(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},Oa=({content:e,path:t,variables:r})=>Mr(e,t).reduce((n,o)=>{let i=jr(o.text,{variables:r});return n+`${i??""}`.length},0),ho=(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))},Vt=(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("-")}`},kr=(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},La=(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},$a=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},Fr=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},ka=(e={})=>e.textStyles||{},Ta=(e={})=>e.images||{},Da=(e={})=>e.colors||{},Pa=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,dt=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,Ze=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},mo=(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},Xr=(e,t)=>{if(typeof e!="string"||!Pa.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},go=(e,t,r)=>{let n=Xr(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})`},Na=(e={},t)=>{let r=ka(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=mo(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:go(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 l=e.colors?.[r.strokeColorId];if(!l)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let a=mo(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=go(l.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},Ur=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Ur(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]=Ur(i,t,dt(r,o)));return e.textStyleId!==void 0&&(Ze(e.textStyleId,r,"textStyleId"),n.textStyle=Na(t,e.textStyleId)),n},Qr=(e={},t)=>{let r=Da(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return Xr(r.hex,`Color "${t}"`)},Oo=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Tr=(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 ${Oo(`${t}.fill`)} instead`)},Va=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>ft(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]=ft(i,t,dt(r,o)));return e.colorId!==void 0&&(Ze(e.colorId,r,"colorId"),n.fill=Qr(t,e.colorId)),n},ft=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>ft(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 ${Oo("fill")} instead`);Tr(e,"hover",r),Tr(e,"click",r),Tr(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]=Va(i,t,dt(r,o));continue}n[o]=ft(i,t,dt(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(Ze(e.colorId,r,"colorId"),n.fill=Qr(t,e.colorId)),n},Dr=(e={},t)=>{let r=Ta(e)?.[t];return r||null},Lo=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",yo=(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 ${Lo(`${t}.${n}`)} instead`)},bo=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},Br=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Br(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 ${Lo(o)} instead`);yo(e,"hover",r,"src"),yo(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]=Br(i,t,dt(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){Ze(e.imageId,r,"imageId");let o=Dr(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&&(Ze(e.hoverImageId,r,"hoverImageId"),bo(n,"hover",Dr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(Ze(e.clickImageId,r,"clickImageId"),bo(n,"click",Dr(t,e.clickImageId)?.fileId??e.clickImageId)),n},Zr=(e,t={},r="root")=>Br(ft(Ur(e,t,r),t,r),t,r),Le=Zr,Fe=(e=[])=>e.find(t=>t.id==="story"),ja="#000000",zr="bg-cg-background-color",Ma=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?Xr(r?.backgroundColor??ja,"screen.backgroundColor"):Qr(e,t.colorId),$o=(e={})=>{if(Kr(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Fa=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Io=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=$o(e),n=Fa(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},Ua=(e={})=>{if(Kr(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Ba=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},ko=(e={})=>{let t=Ua(e),r=Ba(e),n={};return t!==void 0&&(n.alpha=t),r&&(n.blur=r),n},Mt=(e={})=>ko(e),Me=(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},za=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:zr,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:Ma({resources:e,background:t,screen:r})};if(n){let i=$o(t);i!==void 0&&(o.alpha=i)}return o},Wa=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.layouts?.[t]):!1,Ao=({resources:e={},resourceId:t,colorId:r})=>{let n=$a(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:Fr({resourceId:t,kind:n})}:r!==void 0?{resourceId:zr,targetId:zr}:{resourceId:void 0,targetId:void 0}},To=100,Bt=To,Do=(e,t)=>e*t/To,qa=(e={},t=Bt)=>e?.muteAll?0:Do(t,e?.soundVolume??je.soundVolume),Ha=(e={},t=Bt)=>e?.muteAll?0:Do(t,e?.musicVolume??je.musicVolume),Ya=({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:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,confirmDialog:d,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??l??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},v=Qa({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e}),S={variables:e,runtime:A,saveSlots:r,isChoiceVisible:a,isFormVisible:c,canRollback:u,confirmDialog:d,form:f,historyDialogue:p,characters:h};return v&&(S.dialogue=v,S.dialogueLines=v.lines),S},wo=100,Ut=(e,t)=>{if(Array.isArray(e))return e.map(n=>Ut(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=Ut(r[n],t)}),r.type==="text-revealing"?t(r):r},Ga=e=>Ut(e,t=>({...t,revealEffect:"none"})),Ka=e=>Ut(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,wo):wo;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),$e=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?Ga(e):r?Ka(e):e,Po=({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:{}}}}),Wr=e=>{if(Array.isArray(e))return e.map(Wr);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Wr(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}}:{}}}}},Ja=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),Eo="submit",Pr=(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}}},qr=(e,t,r={})=>{if(Array.isArray(e))return e.map(c=>qr(c,t,r));if(!e||typeof e!="object")return e;let n=typeof e.type=="string",o=n&&e.formRole===Eo,i=n&&r.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},l={};for(let[c,u]of Object.entries(e))l[c]=qr(u,t,c==="children"?s:{});let a=l;if(a.type==="input"&&typeof a.field=="string"){let c=t?.fields?.[a.field];if(c){let u={updateFormField:{formKey:t.key,field:c.id,value:"_event.value"}};a={...a,value:c.value,placeholder:a.placeholder===void 0?c.placeholder:a.placeholder,multiline:a.multiline===void 0?c.multiline:a.multiline,...a.maxLength===void 0&&c.maxLength!==void 0?{maxLength:c.maxLength}:{},change:Pr(a.change,u),submit:Pr(a.submit,t.submitActions)}}}return a.formRole===Eo||i?{...a,click:Pr(a.click,t.submitActions,{replaceActions:!0})}:a},Hr=(e,t)=>{if(Array.isArray(e))return e.map(n=>Hr(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Hr(o,t);for(let n of Ja){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form"}})}return r},Yr=({characterId:e,character:t,characterName:r,characters:n={}}={})=>{let o=e?n?.[e]:void 0,i=t?.name!==void 0?t.name:r!==void 0?r:o?.name||"";return{...o||{},...t||{},name:i}},No=(e=[],t={})=>e.map(r=>{let n=Yr({characterId:r.characterId,character:r.character,characterName:r.characterName,characters:t}),o=typeof r.text=="string"?r.text:Array.isArray(r.content)?r.content.map(i=>i?.text??"").join(""):"";return{...r,text:o,character:n,characterName:n.name}}),Xa=e=>!(!e||e.mode==="adv"&&e.content===void 0),Qa=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n}={})=>{if(!t&&!Xa(e))return;let o=e.content===void 0?[{text:""}]:Mr(e.content,"dialogue.content"),i=e.content===void 0?0:Oa({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),s=(e.lines||[]).map((a,c)=>{let u=Mr(a.content,`dialogue.lines[${c}].content`),d=Yr({characterId:a.characterId,character:a.character,characterName:a.characterName,characters:r});return{...a,content:u.map(f=>({...f,text:jr(f.text,{variables:n})})),character:d,characterName:d.name}}),l=Yr({characterId:e.characterId,character:e.character,characters:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:l,content:o.map(a=>({...a,text:jr(a.text,{variables:n})})),initialRevealedCharacters:i,lines:s}},Vo=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=se(e,r,{functions:Oe});return Le($e(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},Nr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),vo=({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:Nr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:Nr(o.keyup)});return}e[n]={...i,[r]:{payload:Nr(o)}}})},Za=(e={},t={})=>{let r={};return vo({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),vo({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},xe=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l})=>{if(!e)return[];let a=[],c=({instanceId:b,targetId:A})=>{let v=_a({resources:t,animationId:p,playback:h,instanceId:b,targetId:A,animationPath:s});v&&a.push(v)},u=r!=null&&r!==!1,d=n!=null&&n!==!1,f=o&&i&&o===i;Sa(e,s);let p=wa(e),h=Ea(e),g=t?.animations?.[p],y=Aa(g,{animationId:p,animationPath:s});if(y==="update")return d&&i?c({instanceId:`${l}-animation-update`,targetId:i}):u&&o&&c({instanceId:`${l}-animation-update`,targetId:o}),a;if(y==="transition"){let b=`${l}-animation-transition`,A=h?.continuity==="persistent"?b:`${l}-animation-in`;if(u&&d&&f)return c({instanceId:b,targetId:i}),a;u&&c({instanceId:`${l}-animation-out`,targetId:o}),d&&c({instanceId:A,targetId:i})}return a},ec=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),tc=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:a,runtime:c,activePersistentAnimations:u,restoredPersistentAnimations:d,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,saveSlots:A=[]})=>{let{elements:v,animations:S}=e;if(t.background){let T=n===void 0?!0:Kr(n?.background??{},"animations"),w=v.find(W=>W.id==="story");if(!w)return e;let D=La(o,t.background),F=r?.background?.resourceId,V=r?.background?.colorId,N=t.background.resourceId??(t.background.animations?F:void 0),j=t.background.colorId??(t.background.animations?V:void 0),U=Wa(o,N),q={...t.background,colorId:j};if((j!==void 0||U)&&w.children.push(za({resources:o,background:q,screen:i,includeOpacity:!U})),N){let{images:W={},videos:x={}}=o,_=W[N]||x[N];if(_){let P=x[N]!==void 0,re={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...D},H={id:Fr({resourceId:N,kind:P?"video":"sprite"}),type:P?"video":"sprite",src:_.fileId,width:_.width,height:_.height,...Io(t.background,{includeDefaultAlpha:!0}),...Me(re)};P&&(H.loop=t.background.loop??!1,H.volume=_.volume??50),w.children.push(H)}}if(N){let{layouts:W={}}=o,x=W[N];if(x){let _={id:Fr({resourceId:N,kind:"container"}),type:"container",children:x.elements,...Io(t.background)};D&&Object.assign(_,Me({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...D}));let P=se(_,ye({variables:a,runtime:c,saveSlots:A,dialogueState:t.dialogue,isLineCompleted:s,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,characters:o.characters||{},skipTransitionsAndAnimations:l}),{functions:Oe});w.children.push(Le($e(P,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:l}),o))}}let G=Ao({resources:o,resourceId:F,colorId:V}),ie=Ao({resources:o,resourceId:N,colorId:j}),te=xe({animationsDef:t.background.animations,resources:o,previousResourceId:G.resourceId,currentResourceId:ie.resourceId,previousTargetId:G.targetId,currentTargetId:ie.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});ge({animationInstances:te,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:u,restoredPersistentAnimations:d,isAuthoredOnCurrentLine:T})&&S.push(...te)}return e},rc=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:a}=e;if(t.character&&n){let c=l.find(h=>h.id==="story");if(!c)return e;let u=t.character.items||[],d=r?.character?.items||[],f=ho(u),p=ho(d);for(let h=0;h<u.length;h++){let g=u[h],{transformId:y,sprites:b}=g,A=d.find(j=>j.id===g.id),v=d.findIndex(j=>j.id===g.id),S=A?.sprites&&A.sprites.length>0,T=b&&b.length>0,w=v>=0?Vt(A,v,p):void 0,D=xe({animationsDef:g.animations,resources:n,previousResourceId:w,currentResourceId:T?Vt(g,h,f):void 0,previousTargetId:w,currentTargetId:T?Vt(g,h,f):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&S&&ge({animationInstances:D,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...D);continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let F=Vt(g,h,f),V=n.transforms[y];if(!V){console.warn("Transform not found:",y);continue}let N={type:"container",id:F,...Me(V,g),...Mt(g),children:[]};for(let j of b){let U=n.images[j.resourceId];if(!U){console.warn(`Image resource not found: ${j.resourceId}`);continue}N.children.push({type:"sprite",id:`${F}-${j.id}`,src:U.fileId,width:U.width,height:U.height,x:0,y:0})}c.children.push(N),ge({animationInstances:D,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...D)}}return e},jo=(e,t)=>{if(!Lr.includes(e))throw new Error(`${t} must be one of: ${Lr.join(", ")}.`)},nc=(e,t)=>{let r=e.layer??(e.resourceId?void 0:t?.layer)??Or;return jo(r,`Visual item "${e.id}" layer`),r},oc=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:l,activePersistentAnimations:a,autoMode:c,skipMode:u,isChoiceVisible:d,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 S=t.visual.items,T=r?.visual?.items||[];y!==void 0&&jo(y,"visualLayer");for(let w of S){let D=T.find(N=>N.id===w.id),F=nc(w,D);if(y!==void 0&&F!==y)continue;if(w.resourceId){let{images:N={},videos:j={},spritesheets:U={}}=n,q=U[w.resourceId];if(q){let G=kr(n,w),ie=w.animationName;if(ie){let te=q.animations?.[ie];if(!te)throw new Error(`Animation '${ie}' not found in spritesheet resource '${w.resourceId}'`);let W=Mt(w),x={id:`visual-${w.id}`,type:"animated-sprite",...Me(G,w),width:w.width??q.width,height:w.height??q.height,alpha:W.alpha??w.alpha??1,spritesheetSrc:q.fileId,spritesheetData:q.jsonData,animation:{frames:te.frames,animationSpeed:w.animationSpeed??te.animationSpeed??.5,loop:w.loop??te.loop??!0}};W.blur&&(x.blur=W.blur),v.children.push(structuredClone(x))}}else{let G=N[w.resourceId]||j[w.resourceId];if(G){let ie=j[w.resourceId]!==void 0,te=kr(n,w),W={id:`visual-${w.id}`,type:ie?"video":"sprite",src:G.fileId,width:G.width,height:G.height,...Me(te,w)};Object.assign(W,Mt(w)),ie&&(W.loop=G.loop??!1,W.volume=G.volume??50),v.children.push(W)}}}if(w.resourceId){let{layouts:N={}}=n,j=N[w.resourceId];if(j){let U=kr(n,w),q={id:`visual-${w.id}`,type:"container",children:structuredClone(j.elements),...Me(U,w)};Object.assign(q,Mt(w));let G=se(q,ye({variables:s,runtime:l,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i}),{functions:Oe});v.children.push(Le($e(G,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),n))}}let V=xe({animationsDef:w.animations,resources:n,previousResourceId:D?.resourceId,currentResourceId:w.resourceId,previousTargetId:D?.resourceId?`visual-${w.id}`:void 0,currentTargetId:w.resourceId?`visual-${w.id}`:void 0,animationPath:`visual.items[${w.id}].animations`,idPrefix:w.id});ge({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:a})&&A.push(...V)}}return e},Qe="dialogue-character-sprite",xo=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,ic=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=Fe(e.elements);if(!a)return e;let c=t.dialogue?.character?.sprite,u=r?.dialogue?.character?.sprite,d=xo(c),f=xo(u),p=xe({animationsDef:c?.animations,resources:n,previousResourceId:f?Qe:void 0,currentResourceId:d?Qe:void 0,previousTargetId:f?Qe:void 0,currentTargetId:d?Qe:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!d)return c?.animations&&f&&ge({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e;let h=n.transforms?.[c.transformId];if(!h)return console.warn("Transform not found:",c.transformId),e;let g={type:"container",id:Qe,...Me(h),children:[]};for(let y of c.items){let b=n.images?.[y.resourceId];if(!b){console.warn(`Image resource not found: ${y.resourceId}`);continue}g.children.push({type:"sprite",id:`${Qe}-${y.id}`,src:b.fileId,width:b.width,height:b.height,x:0,y:0})}return a.children.push(g),ge({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e},sc=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,skipOnlyViewedLines:d,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 S=A.find(w=>w.id==="story");if(!S)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:w={}}=n,D=w[t.dialogue.ui.resourceId];if(D){let F={elements:D.elements},V=ye({variables:h,runtime:g,saveSlots:b,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:f,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:d,skipTransitionsAndAnimations:p}),N={functions:Oe},j=jt(F,V,N),U=se(j,V,N),q=Le($e(U?.elements,{isLineCompleted:f,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(q))for(let G of q)S.children.push(G);else q&&S.children.push(q)}}ic(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let T=xe({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:T,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&v.push(...T),e},ac=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:b,animations:A}=e;if(t.choice&&n){let v=Fe(b);if(!v)return e;let S=n?.layouts[t.choice.resourceId];if(S&&S.elements){let w={elements:S.elements},D=se(w,{...ye({variables:l,runtime:a,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:c,skipMode:u,isChoiceVisible:d??!!t.choice,isFormVisible:f,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:Oe}),F=Wr(Le($e(D?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n));if(Array.isArray(F))for(let V of F)v.children.push(V);else F&&v.children.push(F)}let T=xe({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:T,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&A.push(...T)}return e},cc=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:b,animations:A}=e;if(!y?.resourceId||!n)return e;let v=Fe(b);if(!v)return e;let S=n?.layouts?.[y.resourceId];if(!S)return console.warn(`Form layout not found: ${y.resourceId}`),e;let T={id:"form-container",type:"container",x:0,y:0,children:S.elements||[]},w={...ye({variables:l,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},D=se(T,w,{functions:Oe}),F=Hr(Le($e(qr(D,y),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n),y);F&&v.children.push(F);let V=xe({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:V,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(...V),e},lc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,saveSlots:f=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=Za(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=Fe(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(Vo({container:b,resources:r,templateData:ye({variables:n,runtime:o,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:l,skipTransitionsAndAnimations:p})),e},uc=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Fe(i))return e;let a=r.sounds[t.bgm.resourceId];if(!a)return e;let c=ye({variables:o,runtime:n}).runtime;s.push({id:"bgm",type:"sound",src:a.fileId,loop:t.bgm.loop??!0,volume:Ha(c,t.bgm.volume??a.volume??Bt),startDelayMs:t.bgm.startDelayMs??null})}return e},dc=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx.items;for(let[s,l]of i.entries()){let a=r.sounds?.[l.resourceId];a&&o.push({id:Ya({item:l,index:s}),type:"sound",src:a.fileId,loop:l.loop??a.loop??!1,volume:qa(n,l.volume??a.volume??Bt),startDelayMs:l.startDelayMs??a.startDelayMs??null})}}return e},fc=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},pc=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,hc=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let l=t.voice,{resourceId:a,loop:c,startDelayMs:u}=l,d=fc(r,n,a);if(!d)return e;let f=ye({variables:i,runtime:o}).runtime;return s.push({id:`voice-${n}-${a}`,type:"sound",src:d.fileId,volume:pc(l,f),loop:c??!1,startDelayMs:u??null}),e},mc=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,saveSlots:f=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:b}=e;if(t.layout){let T=Fe(y);if(!T)return e;let w=n.layouts[t.layout.resourceId];if(!w)return e;Array.isArray(w.transitions)&&!p&&!h&&Jr({animations:b,transitions:w.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let D={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:w.elements||[]};T.children.push(Vo({container:D,resources:n,templateData:ye({variables:o,runtime:i,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:l,skipTransitionsAndAnimations:h}))}let A=r?.layout?.resourceId,v=t.layout?.resourceId,S=xe({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:S,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(...S),e},gc=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=t?.screen?.animations;if(!a)return e;let c=r!=null,u=xe({animationsDef:a,resources:n,previousResourceId:c?"story":void 0,currentResourceId:"story",previousTargetId:c?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return ge({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...u),e},yc=(e,{presentationState:t})=>{let r=Fe(e.elements);return!r||!t?.screen||Object.assign(r,ko(t.screen)),e},bc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,overlayStack:d=[],dialogueHistory:f=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;return d&&d.length>0&&d.forEach((v,S)=>{let T=r.layouts[v.resourceId];if(!T){console.warn(`Overlay layout not found: ${v.resourceId}`);return}Array.isArray(T.transitions)&&(y||Jr({animations:A,transitions:T.transitions,defaultTargetId:`overlayStack-${S}`,idPrefix:`overlayStack-${S}`,animationPathPrefix:`overlayStack[${S}]`}));let w={id:`overlayStack-${S}`,type:"container",x:0,y:0,children:[Po({id:`overlayStack-${S}-blocker`,screen:h}),...T.elements||[]]},D=No(f,r.characters),F=ye({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,historyDialogue:D,characters:r.characters||{},skipTransitionsAndAnimations:y}),V=se(w,F,{functions:Oe}),[N,...j]=V.children||[],U=Le($e({...V,children:j},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...U,children:N?[N,...U.children||[]]:U.children})}),e},Ic=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,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&&Jr({animations:A,transitions:v.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let S={id:"confirmDialog",type:"container",x:0,y:0,children:[Po({id:"confirmDialog-blocker",screen:h}),...v.elements||[]]},T=No(p,r.characters),w=se(S,ye({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,confirmDialog:f,historyDialogue:T,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:Oe}),[D,...F]=w.children||[],V=Le($e({...w,children:F},{isLineCompleted:g,skipMode:l,skipTransitionsAndAnimations:y}),r);return b.push({...V,children:D?[D,...V.children||[]]:V.children}),e},pt=e=>(t,r)=>oc(t,{...r,visualLayer:e}),Ac=pt(ve.BEHIND_BACKGROUND),wc=pt(ve.BEHIND_CHARACTER),Ec=pt(ve.BEHIND_DIALOGUE),vc=pt(ve.BEHIND_CHOICE),xc=pt(ve.FOREGROUND),Mo=e=>kt(ec,[lc,Ac,tc,wc,rc,Ec,sc,vc,ac,cc,mc,xc,yc,gc,uc,dc,hc,bc,Ic])(e);var zt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Wo=1,en="choice",Wt="form",Yt=()=>({manual:{...zt.manual},auto:{...zt.auto},applyMode:zt.applyMode}),tn=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...Yt()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},k=e=>{let t=ce(e)?Pe(e):e;return structuredClone(t)},$=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Gt=e=>String(e),qo=()=>({sections:[],resources:[]}),Cc=e=>$(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):qo(),Sc=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",_c=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:Sc(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),Rc=()=>({resourceId:void 0}),Oc=e=>{if(!$(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},rn=(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}},Ho=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 l=r.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},Yo=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Go=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Wo)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Lc=(e,t={})=>{let r;try{r=Go(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:Yo(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},$c=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Lc(t,r)])),Ko=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Eu(r));return t.length>0?t:void 0},kc=e=>{!$(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!$(t))return;let r=Ko(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},Fo=(e,t,r,n="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!$(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}},Tc=(e,t="viewedRegistry")=>{if(e===void 0)return qo();if(!$(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=Fo(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Fo(o,"resources",i,t);return[s.resourceId,s]})))}},Jo=(e,t,r)=>{if(!$(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}=rn(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}},Dc=(e,t,r)=>{if(!$(e)||!Array.isArray(e.timeline))return ht({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((l,a)=>{if(!$(l))return[];try{let c=Jo(l,r,`rollback.timeline[${a}]`),u=Ht({sectionId:c.sectionId,lineId:c.lineId,rollbackPolicy:l.rollbackPolicy}),d=Ko(k(l.executedActions));return d&&(u.executedActions=d),[u]}catch{return[]}});if(n.length===0)return ht({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 l=n.findLastIndex(a=>a.sectionId===t.sectionId&&a.lineId===t.lineId);l>=0?o=l:(n.push(Ht({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}},Pc=(e,t,r)=>{if(!$(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=sn(t),o=Jo(e.pointers?.read,t,`contexts[${r}].pointers.read`);if(e.variables!==void 0&&!$(e.variables))throw new Error(`Malformed save slot contexts[${r}].variables entry.`);if(e.runtime!==void 0&&!$(e.runtime))throw new Error(`Malformed save slot contexts[${r}].runtime entry.`);let i=e.variables?Ke(k(e.variables),t.resources?.variables??{}):{},s=Gc({loadedContextRuntime:$(e.runtime)?k(e.runtime):{}}),l={currentPointerMode:"read",pointers:{read:o},configuration:$(e.configuration)?k(e.configuration):{},views:Array.isArray(e.views)?k(e.views):[],bgm:$(e.bgm)?k(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:Dc(e.rollback,o,t)};return s&&(l.runtime=s),l},Nc=(e,t)=>{if(!$(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)=>Pc(r,t,n))}},Vc=(e,t)=>{if(!$(e))throw new Error("Malformed save slot.");let r=Go(e.formatVersion);return{...e,formatVersion:r,state:Nc(e.state,t)}},Uo=(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=k(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},jc=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Uo(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Uo(e.cancelActions,"cancelActions")}},et=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Mc=e=>($(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),tt=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},Xo=e=>{if(!(!$(e)||!e.animations))return{animations:k(e.animations)}},Fc=(e,t)=>{let r=Xo(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},Uc=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},Bc=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},qt=e=>String(e??""),Qo=(e,t)=>{let r=qt(t);return e?.trim===!0?r.trim():r},zc=e=>$(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>$(t)).map(([t,r])=>[t,{id:t,...k(r)}])):{},Wc=(e,t)=>{if(!t||!$(e.global.formDrafts))return;let r=e.global.formDrafts[t];return $(r)?r:void 0},Zo=(e,t)=>{let r=Mc(e);$(r[t])||(r[t]={values:{},touched:{},errors:{},submitted:!1});let n=r[t];return $(n.values)||(n.values={}),$(n.touched)||(n.touched={}),$(n.errors)||(n.errors={}),typeof n.submitted!="boolean"&&(n.submitted=!1),n},nn=(e,t)=>{let r=Qo(e,t);return e?.required===!0&&r.length===0?"required":null},qc=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=ee({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:Ve(n.slice(0,o+1).map(i=>i.actions||{}))},Hc=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=Uc(t),o=Bc(r,n);if(!n||!o)return null;let i=Wc(e,o),s=zc(t),l=dn({state:e}),a={},c=[],u={},d=!0;return Object.entries(s).forEach(([f,p])=>{let h=qt(l?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},f)?qt(i.values[f]):h,y=i?.touched?.[f]===!0,b=nn(p,g),A=i?.submitted||y?b:null,v=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,S={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&&(d=!1),a[f]=S,c.push(S),u[f]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:d,submitted:i?.submitted===!0,fields:a,fieldList:c,values:u,submitActions:{submitForm:{formKey:o,actions:k(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:k(t.cancelActions??{})}}}},Ue=[],Bo="line",on="interaction",Ht=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),sn=e=>{let{contextVariableDefaultValues:t}=Er(e??{});return k(t)},ei=()=>({...k(ut)}),ti=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:k(r),hasLoadedValues:!1};if(!$(e))throw new Error(`Malformed ${n}.`);let o=k(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=ri(s,k(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Yc=({loadedGlobalRuntime:e={}})=>ti({loadedRuntime:e,runtimeIds:_r,defaults:je,path:"global.runtime"}).runtimeState,Gc=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=ti({loadedRuntime:e,runtimeIds:Rr,defaults:ei(),path:"context.runtime"});return r?t:void 0},an=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Kc=e=>e.runtime?(Rr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=k(ut[t]))}),e.runtime):(e.runtime=ei(),e.runtime),Jc=e=>fo(e.global),Xc=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Jc(e)}})},Qc=e=>uo[e],Zc=(e,t)=>{let r=Qc(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}"`)},ri=(e,t)=>(Zc(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),ni=(e,t,r)=>{let n=ri(t,r);if(t in ut){let o=an(e);if(!o)return n;let i=Kc(o);return i[t]=n,n}return e.global[t]=n,n},oi=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:k(e)},configuration:{},views:[],bgm:Rc(),variables:sn(t),rollback:ht({pointer:e})}),rt=e=>e?(e.currentPointerMode="read",$(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,el=(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=oi({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,tl(e,{queueRender:t}),o},tl=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,et(e),tt(e),e.global.nextLineConfig=Yt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},ii=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},ht=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[Ht({sectionId:e.sectionId,lineId:e.lineId})]:[]}},We=(e,t={})=>{if(e?.rollback)return ii(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=ht({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},cn=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=We(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(Ht(t)),n.currentIndex=n.timeline.length-1},rl=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=Ue[Ue.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)},nl=({state:e},t={})=>{let r=t?.source===Bo?Bo:on,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?(Ue.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Ue.push({checkpointIndex:o.currentIndex,source:r}),e)},ol=({state:e})=>(Ue.pop(),e),Ae=(e,t,r)=>{let o=Ue[Ue.length-1]?.source??on;if(!vu(t,o))return;let i=rl(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:k(r)}))},zo=(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:l}of n){let a=e.projectData.resources?.variables?.[o],c=a?.scope,u=a?.type;if(Re(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Dt(c,o),Pt(u,i,o),vr(u,i,s,o,{roundTo:l}),c==="context"&&(r.variables[o]=Nt(r.variables[o],i,s,{roundTo:l}))}},il=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{xu(e,r,n)})},sl=(e,t)=>{let{sectionId:r,lineId:n}=t,s=ee({state:e},{sectionId:r})?.lines?.find(l=>l.id===n)?.actions;s&&Object.entries(s).forEach(([l,a])=>{Ei(e,l,a)})},si=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=We(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&gt({state:e}),e.global.skipMode&&Be({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=sn(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=k(zt),e.global.overlayStack=[],et(e),tt(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let l=i;l<=t;l++)l>i&&tn(e),sl(e,n.timeline[l]),il(e,n.timeline[l]);let s=rt(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},al=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;Ho(t);let l=t.story.initialSceneId,a=t.story.scenes[l],c=a.initialSectionId,u=a.sections[c],d={sceneId:l,sectionId:c,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:f}=Er(t),p={...f,...Ke(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:Tc(s,"accountViewedRegistry"),nextLineConfig:Yt(),saveSlots:$c(n),overlayStack:[],variables:p,...Yc({loadedGlobalRuntime:i})},contexts:[oi({pointer:d,projectData:t})]}},cl=({state:e})=>e.global.overlayStack||[],ll=({state:e})=>e.global.pendingEffects,ai=({state:e})=>e.global.skipMode,ul=({state:e})=>e.global.autoMode,ci=({state:e})=>e.global.dialogueUIHidden,li=({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=ee({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),l=i.lines.slice(0,s+1),a=[],c={};for(let u of l){let d=u.actions||{};if(c=Ve([c,d]),!d.dialogue)continue;let f=c.dialogue||{},p="";f.character?.name!==void 0?p=f.character.name:f.characterId&&(p=e.projectData.resources?.characters?.[f.characterId]?.name||"");let h=_c({sectionId:n,lineId:u.id,content:d.dialogue.append===!0?f.content:d.dialogue.content,dialogueState:f,characterName:p});if(d.dialogue.append===!0&&a.length>0){a[a.length-1]={...a[a.length-1],content:h.content,text:h.text,characterId:h.characterId,character:h.character,characterName:h.characterName};continue}a.push(h)}return a},dl=({state:e})=>e.global.confirmDialog??null,mt=({state:e},{pointer:t}={})=>{let r=t??fe({state:e})?.pointer,n=qc({state:e,pointer:r});return Hc({state:e,form:n.form,pointer:r})},fl=({state:e},{pointer:t}={})=>!!mt({state:e},{pointer:t}),we=({state:e},{pointer:t}={})=>{let r=mt({state:e},{pointer:t});if(r)return{source:Wt,formId:r.id,formKey:r.key};let n=ui({state:e,pointer:t});return n?{source:en,resourceId:n}:null},pl=({state:e,registry:t},r)=>{let{sectionId:n,lineId:o}=r,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===n);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let l=ee({state:e},{sectionId:n});if(!l||!l.lines||!Array.isArray(l.lines))return s.lastLineId===o;let a=l.lines.findIndex(u=>u.id===s.lastLineId),c=l.lines.findIndex(u=>u.id===o);return a===-1||c===-1?s.lastLineId===o:c<=a},hl=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},ln=({state:e},t)=>pl({state:e,registry:e.global.accountViewedRegistry},t),ml=({state:e},t)=>hl({registry:e.global.accountViewedRegistry},t),gl=({state:e})=>e.global.nextLineConfig,ui=({state:e,pointer:t}={})=>{let r=t??fe({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=ee({state:e},{sectionId:n})?.lines||[],l=s.findIndex(c=>c.id===o);if(l<0)return;let a;for(let c of s.slice(0,l+1)){let u=c?.actions;if(u?.cleanAll&&(a=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){a=void 0;continue}let d=u.choice;if(d?.resourceId){a=d.resourceId;continue}d?.animations||(a=void 0)}return a},di=({state:e})=>!!ui({state:e}),yl=({state:e})=>structuredClone(e),fi=({state:e})=>e.global.saveSlots,bl=({state:e},t)=>{let r=t?.slotId,n=Gt(r);return e.global.saveSlots[n]},un=({state:e})=>Je(e),Il=({state:e},t)=>Ee(e,t?.runtimeId),dn=({state:e})=>{let t={...e.global?.variables??{},...an(e)?.variables??{}};return Tt({variables:t,runtime:Je(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}},ee=({state:e},t)=>{let{sectionId:r}=t;return rn(e.projectData,r).section},fn=({state:e})=>{let t=fe({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=ee({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},pi=({state:e})=>{let{sectionId:t,lineId:r}=fe({state:e}).pointer,o=ee({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===r),l=o.slice(0,i+1).map(c=>{let u=c.actions||{},d={};return Object.keys(u).forEach(f=>{d[f]=u[f]}),d});return Ve(l)},Al=({state:e})=>{let t=hi({state:e}),n=fn({state:e})?.actions??{},o=Ve([t??{},n]);return xr(t??{},o??{})},wl=({state:e},{sectionId:t})=>{let r=ee({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},l=Ve([o,s]),a=xr(o,l);n.push({id:i.id,changes:a,presentationState:l}),o=Cr(l)}return n},El=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=wl({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},hi=({state:e})=>{let{sectionId:t,lineId:r}=fe({state:e}).pointer,o=ee({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===r);if(i<=0)return null;let l=o.slice(0,i).map(a=>{let c=a.actions||{},u={};return Object.keys(c).forEach(d=>{u[d]=c[d]}),u});return Cr(Ve(l))},pn=({state:e},{slotsPerPage:t=6}={})=>{let o=((un({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let l=o+s,a=e.global.saveSlots&&e.global.saveSlots[Gt(l)]||{};i.push({...a,slotId:l})}return{saveSlots:i}},vl=fi,xl=pn,Cl=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},Sl=({state:e},t={})=>{let r=pi({state:e}),n=hi({state:e}),o=fn({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:k(i)}:o,l=i?.animations&&n===null?{}:n,{sectionId:a}=fe({state:e}).pointer,{sceneId:c}=rn(e.projectData,a),u=un({state:e}),d=t?.activePersistentAnimations??[],f=t?.restoredPersistentAnimations??[],p=mt({state:e}),h=di({state:e}),g=dn({state:e}),{saveSlots:y}=pn({state:e}),b=Cl(e);return Mo({presentationState:r,previousPresentationState:l,currentLineActions:s,resources:e.projectData.resources,currentSceneId:c,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:xi({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:li({state:e}),saveSlots:y,variables:g,runtime:u,activePersistentAnimations:d,restoredPersistentAnimations:f})},_l=({state:e},t)=>(e.global.confirmDialog=jc(t),e.global.pendingEffects.push({name:"render"}),e),Rl=({state:e})=>(e.global.confirmDialog&&(et(e),e.global.pendingEffects.push({name:"render"})),e),Ol=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Ae(e,"pushOverlay",t),e),Ll=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Ae(e,"popOverlay",void 0),e),$l=({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),kl=({state:e})=>(e.global.overlayStack=[],et(e),tt(e),e.global.pendingEffects.push({name:"render"}),Ae(e,"clearOverlays",void 0),e),Tl=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"})},Kt=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,Fc(e,r),tt(e);let n=we({state:e},{pointer:t}),o=n?.source===en,i=n?.source===Wt;return n&&Tl(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},mi=({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),gt=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Dl=({state:e})=>{let t=e.global.autoMode;return we({state:e})&&!t||(t?gt({state:e}):mi({state:e})),e},gi=({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),Be=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Pl=({state:e})=>{let t=ai({state:e});return we({state:e})&&!t||(t?Be({state:e}):gi({state:e})),e},Jt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Ae(e,"showDialogueUI",void 0),e),yi=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Ae(e,"hideDialogueUI",void 0),e),Nl=({state:e})=>(ci({state:e})?Jt({state:e}):yi({state:e}),e),qe=(e,t,r)=>(ni(e,t,r),Xc(e),e.global.pendingEffects.push({name:"render"}),e),yt=(e,t,r,n)=>{let o=ni(e,t,r);return e.global.pendingEffects.push({name:"render"}),Ae(e,n,{value:o}),e},Vl=({state:e},t)=>qe(e,"dialogueTextSpeed",t?.value),jl=({state:e},t)=>qe(e,"autoForwardDelay",t?.value),Ml=({state:e},t)=>qe(e,"skipUnseenText",t?.value),Fl=({state:e},t)=>qe(e,"skipTransitionsAndAnimations",t?.value),Ul=({state:e},t)=>qe(e,"soundVolume",t?.value),Bl=({state:e},t)=>qe(e,"musicVolume",t?.value),zl=({state:e},t)=>qe(e,"muteAll",t?.value),Wl=({state:e},t)=>yt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),ql=({state:e})=>{let t=Ee(e,"saveLoadPagination")+1;return yt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},Hl=({state:e})=>{let t=Ee(e,"saveLoadPagination")-1;return yt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},Yl=({state:e},t)=>yt(e,"menuPage",t?.value,"setMenuPage"),Gl=({state:e},t)=>yt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Kl=({state:e})=>(e.global.pendingEffects=[],e),Jl=({state:e},t)=>(e.global.pendingEffects.push(t),e),bi=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!Xo(n),i=ee({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&&!el(e,{queueRender:!o}))return e;e.global.autoMode&&gt({state:e}),r&&e.global.skipMode&&Be({state:e});let l=e.contexts?.[e.contexts.length-1];if(l){let a=rt(l),c=a.read;r||ze(e,{sectionId:c?.sectionId,lineId:c?.lineId}),l.rollback||We(l,{compatibilityAnchor:!0}),a.read={sectionId:t,lineId:s.id},r?l.rollback=ht({pointer:a.read}):cn(e,{sectionId:t,lineId:s.id})}return Kt(e,l?.pointers?.read,{screenTransition:n}),e},Xl=({state:e},t)=>bi(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),Ii=e=>(e.global.accountViewedRegistry=Cc(e.global.accountViewedRegistry),e.global.accountViewedRegistry),hn=(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:k(r.value)}))}})},Ai=(e,t)=>{hn(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:[]}}])},Ql=(e,t,{sectionId:r,lineId:n})=>{if(!r||!n)return!1;let o=$(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=ee({state:e},{sectionId:r});if(s?.lines){let l=s.lines.findIndex(c=>c.id===i.lastLineId),a=s.lines.findIndex(c=>c.id===n);if(l===-1||a>l)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},ze=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;Ql(e,Ii(e),t)&&Ai(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},Zl=({state:e},t)=>(ze(e,t),e.global.pendingEffects.push({name:"render"}),e),eu=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=Ii(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),Ai(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},wi=({state:e},t)=>{let r=Oc(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=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,c=we({state:e});return!l&&!c&&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}}):!l&&a===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),Ae(e,"setNextLineConfig",t),e},tu=({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=Gt(r),s=k(e.contexts);s?.forEach(c=>{rt(c),ii(c.rollback),kc(c.rollback)});let l={contexts:s},a={formatVersion:Wo,slotId:Yo(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:l};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},ru=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=Gt(r),o=e.global.saveSlots[n];if(o){let i=Vc(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=Yt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,et(e),tt(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},nu=({state:e},t)=>{let{projectData:r}=t;Ho(r),e.projectData=r;let n=r?.resources?.variables??{};return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables=Ke(e.global.variables,n)),e.contexts?.forEach(o=>{Object.prototype.hasOwnProperty.call(o??{},"variables")&&(o.variables=Ke(o.variables,n))}),et(e),tt(e),e.global.pendingEffects.push({name:"render"}),e},ou=({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&&!ee({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=ee({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(c=>c.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let a=rt(o);return a.read={sectionId:i,lineId:n},Kt(e,a.read),e},iu=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return Jt({state:e}),e;let r=we({state:e});if(r?.source===en&&t?.bypassChoice!==!0||r?.source===Wt&&t?._interactionSource!==Wt)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=fe({state:e})?.pointer,d=u?.sectionId,f=u?.lineId;d&&f&&ze(e,{sectionId:d,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=ee({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],l=i?.lines||[],c=l.findIndex(u=>u.id===n?.lineId)+1;if(c<l.length){let u=l[c],d=!Ee(e,"skipUnseenText");if(e.global.skipMode&&d&&!ln({state:e},{sectionId:o,lineId:u.id}))return Be({state:e}),e;if(s&&!s.rollback&&We(s,{compatibilityAnchor:!0}),s){let h=rt(s),g=h.read?.lineId;g&&o&&ze(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:u.id}}cn(e,{sectionId:o,lineId:u.id}),tn(e);let{activeInteraction:f}=Kt(e,{sectionId:o,lineId:u.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&&gt({state:e}),e.global.skipMode&&Be({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&&ze(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},au=({state:e},t)=>bi(e,{sectionId:t?.sectionId,screen:t?.screen}),cu=({state:e})=>{if(e.global.dialogueUIHidden)return Jt({state:e}),e;if(we({state:e}))return e;let t=fe({state:e})?.pointer,r=t?.sectionId,n=ee({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],l=i.findIndex(a=>a.id===t?.lineId)+1;if(l<i.length){let a=i[l],c=!Ee(e,"skipUnseenText");if(e.global.skipMode&&c&&!ln({state:e},{sectionId:r,lineId:a.id}))return Be({state:e}),e;if(o&&!o.rollback&&We(o,{compatibilityAnchor:!0}),o){let d=rt(o),f=d.read?.lineId;f&&r&&ze(e,{sectionId:r,lineId:f}),d.read={sectionId:r,lineId:a.id}}cn(e,{sectionId:r,lineId:a.id}),tn(e);let{activeInteraction:u}=Kt(e,{sectionId:r,lineId:a.id});e.global.nextLineConfig.auto?.enabled&&!u&&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},mn=(e,t={})=>{let r=mt({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},lu=(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(Re(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return Dt(n,t.variableId),Pt(o,"set",t.variableId),{variableConfig:r,scope:n}},uu=(e,t)=>({id:e.id,key:e.key,valid:!0,values:k(t),fields:k(e.fields),fieldList:k(e.fieldList)}),du=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&&ze(e,{sectionId:r,lineId:n})},fu=({state:e},t={})=>{let r=mn(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=Zo(e,r.key),i=qt(t.value),s=r.fields[n],l=nn(s,i);return o.values[n]=i,o.touched[n]=!0,l?o.errors[n]=l:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},pu=({state:e},t={})=>{let r=mn(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=Zo(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([d,f])=>{let p=Object.prototype.hasOwnProperty.call(n.values,d)?n.values[d]:f.value,h=nn(f,p);n.touched[d]=!0,h&&(i[d]=h),o[d]=Qo(f,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:k(i),form:{id:r.id,key:r.key,values:k(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let l=!1,a=[],c=[];Object.entries(r.fields).forEach(([d,f])=>{let{scope:p}=lu(e,f),h=p==="context"?s.variables:e.global.variables,g=o[d];h[f.variableId]=Nt(h[f.variableId],"set",g),p==="context"&&(l=!0,c.push({variableId:f.variableId,op:"set",value:g})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${f.variableId}`,op:"set",value:k(h[f.variableId])})}),l&&Ae(e,"updateVariable",{id:"submitForm",operations:c}),hn(e,a);let u=uu(r,o);return du(e),delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},hu=({state:e},t={})=>{let r=mn(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:k(r.values),fields:k(r.fields),fieldList:k(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},mu=({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=[],l=[];return n.forEach(({variableId:a,op:c,value:u,roundTo:d})=>{let f=e.projectData.resources?.variables?.[a],p=f?.scope,h=f?.type;if(Re(f))throw new Error(`Cannot update computed variable: ${a}`);if(f?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);Dt(p,a),Pt(h,c,a),vr(h,c,u,a,{roundTo:d});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:a,op:c,value:u};d!==void 0&&(y.roundTo=d),l.push(y)}g[a]=Nt(g[a],c,u,{roundTo:d}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:k(g[a])})}),i&&Ae(e,"updateVariable",{id:r,operations:l}),hn(e,s),e.global.pendingEffects.push({name:"render"}),e},gu=e=>(t,r)=>e({state:t},r),yu=e=>({variables:Tt({variables:{...e.global?.variables??{},...an(e)?.variables??{}},runtime:Je(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:Je(e)}),bu=e=>{if(!$(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")},Iu=(e,t,r)=>{if(!$(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!$(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")},Au=(e,t)=>{bu(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(Iu(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!ct(n.when,yu(e)))){Object.entries(n.actions).forEach(([i,s])=>{Ei(e,i,s)});return}}},wu={conditional:{replayLine:Au},updateVariable:{recordSources:[on],replayLine:zo,replayRecorded:zo,persistInSaveSlot:!0},setNextLineConfig:{replayLine:gu(wi)}},Xt=e=>wu[e]??null,Eu=e=>Xt(e)?.persistInSaveSlot===!0,vu=(e,t)=>{let r=Xt(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},xu=(e,t,r)=>{Xt(t)?.replayRecorded?.(e,r)},Ei=(e,t,r)=>{Xt(t)?.replayLine?.(e,r)},vi=({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}},xi=({state:e})=>vi({state:e},{offset:-1})!==null,Cu=({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=We(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:si(e,i)},Su=({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=We(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===r&&a.lineId===n);if(l===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return l===i.currentIndex?e:si(e,l)},Ci=e=>{let t=al(e);return eo(t,{selectPendingEffects:ll,selectSkipMode:ai,selectAutoMode:ul,selectIsChoiceVisible:di,selectIsFormVisible:fl,selectActiveInteraction:we,selectActiveForm:mt,selectDialogueUIHidden:ci,selectDialogueHistory:li,selectConfirmDialog:dl,selectIsLineAccountViewed:ln,selectIsResourceAccountViewed:ml,selectNextLineConfig:gl,selectSystemState:yl,selectSaveSlotMap:fi,selectSaveSlots:vl,selectSaveSlot:bl,selectRuntime:un,selectRuntimeValue:Il,selectAllVariables:dn,selectCurrentPointer:fe,selectSection:ee,selectCurrentLine:fn,selectPresentationState:pi,selectPresentationChanges:Al,selectSectionLineChanges:El,selectSaveSlotPage:pn,selectCurrentPageSlots:xl,selectRenderState:Sl,selectOverlayStack:cl,selectLineIdByOffset:vi,selectCanRollback:xi,startAutoMode:mi,stopAutoMode:gt,toggleAutoMode:Dl,startSkipMode:gi,stopSkipMode:Be,toggleSkipMode:Pl,showDialogueUI:Jt,hideDialogueUI:yi,toggleDialogueUI:Nl,setDialogueTextSpeed:Vl,setAutoForwardDelay:jl,setSkipUnseenText:Ml,setSkipTransitionsAndAnimations:Fl,setSoundVolume:Ul,setMusicVolume:Bl,setMuteAll:zl,setSaveLoadPagination:Wl,incrementSaveLoadPagination:ql,decrementSaveLoadPagination:Hl,setMenuPage:Yl,setMenuEntryPoint:Gl,showConfirmDialog:_l,hideConfirmDialog:Rl,resetStoryAtSection:Xl,clearPendingEffects:Kl,appendPendingEffect:Jl,beginRollbackActionBatch:nl,endRollbackActionBatch:ol,addViewedLine:Zl,addViewedResource:eu,setNextLineConfig:wi,saveSlot:tu,loadSlot:ru,updateProjectData:nu,sectionTransition:au,jumpToLine:ou,nextLine:iu,markLineCompleted:su,rollbackToLine:Su,rollbackByOffset:Cu,pushOverlay:Ol,popOverlay:Ll,replaceLastOverlay:$l,clearOverlays:kl,updateFormField:fu,submitForm:pu,cancelForm:hu,updateVariable:mu,nextLineFromSystem:cu},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var _u="route-engine",Ru="projectPersistence";var _i=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),Q=e=>Object.prototype.toString.call(e)==="[object Object]",Si="variables.",Ou=(e={})=>{let t=Q(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!Q(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)}:!Q(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Lu=(e={})=>{let t=Q(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!Q(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)}:!Q(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},$u=(e,t)=>{let r=Lu(e),n=Ou(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let l=o.find(a=>a.sectionId===s.sectionId);if(!l){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(l.lastLineId!==void 0){if(s.lineId===void 0){delete l.lastLineId;return}l.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},Ri=(e={})=>{let t=Q(e)?e:{};return{saveSlots:Q(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:Q(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:Q(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:Q(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:Q(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},ku=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!Q(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(Si)?t.path.slice(Si.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}].`)})},Tu=(e,t)=>{let r={};return ku(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=$u(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},gn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},Du=e=>{let t=gn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Pu=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},Nu=({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}".`))}}),Vu=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.`))}})},bt=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),a=l.objectStore(t),c=a.get(r),u=!1,d=p=>{u||(u=!0,s(p))},f=()=>{u||(u=!0,i())};c.onerror=()=>{d(c.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},c.onsuccess=()=>{let p=Ri(c.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,..._i(),...p,...h},y=a.put(g);y.onerror=()=>{d(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},l.oncomplete=()=>{f()},l.onerror=()=>{d(l.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},l.onabort=()=>{d(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},ju=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),c=!1,u=f=>{c||(c=!0,i(f))},d=()=>{c||(c=!0,o())};a.onerror=()=>{u(a.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{d()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},yn=(e={})=>{let{indexedDB:t,databaseName:r=_u,objectStoreName:n=Ru,namespace:o}=e,i=Pu(t),s=Du(o),l=Nu({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let a=await Vu({databasePromise:l,objectStoreName:n,namespace:s});return{..._i(),...Ri(a)}},clear:async()=>ju({databasePromise:l,objectStoreName:n,namespace:s}),saveSlots:async a=>bt({databasePromise:l,objectStoreName:n,namespace:s,patch:{saveSlots:Q(a)?a:{}}}),saveGlobalDeviceVariables:async a=>bt({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:Q(a)?a:{}}}),saveGlobalAccountVariables:async a=>bt({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalAccountVariables:Q(a)?a:{}}}),saveGlobalRuntime:async a=>bt({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalRuntime:Q(a)?a:{}}}),applyScopedDataUpdates:async a=>bt({databasePromise:l,objectStoreName:n,namespace:s,patch:c=>Tu(c,a)})}},Mu=yn;var Fu=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Uu=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),Oi="conditional",bn="form",Bu=new Set(["submitForm","cancelForm"]),It=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function In(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:l}=e,a=(I=new Map,C=Date.now())=>new Map(Array.from(I.entries()).filter(([,R])=>C<R.expiresAt).map(([R,M])=>[R,{animation:structuredClone(M.animation),startedAt:M.startedAt,expiresAt:M.expiresAt}])),c=(I=new Map)=>Array.from(I.values()).map(C=>structuredClone(C.animation)),u=(I=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,C])=>I<C.expiresAt))},d=()=>{for(;t.selectPendingEffects().length>0;){let I=[...t.selectPendingEffects()];t.clearPendingEffects();try{l(I)}catch(C){throw t.clearPendingEffects(),I.forEach(R=>{t.appendPendingEffect(R)}),C}}},f=({initialState:I,namespace:C})=>{t=Ci(I),r=0,n=gn(C),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),d()},p=()=>n,h=()=>t.selectPresentationState(),g=()=>t.selectPresentationChanges(),y=I=>t.selectSectionLineChanges(I),b=(I={})=>{r+=1;let C=Date.now();u(C);let R=i.size>0,M=a(o,C),z=R?a(i,C):new Map,be={...t.selectRenderState({activePersistentAnimations:c(M),restoredPersistentAnimations:c(z)}),id:`render-${r}`};return s.set(be.id,{builtAt:C,persistentAnimationSessions:new Map([...z.entries(),...M.entries()]),usedRestoredPersistentAnimationSessions:R}),be},A=(I={})=>b(I),v=(I={})=>b(I),S=I=>{let C=typeof I?.id=="string"&&I.id.length>0?I.id:null,R=C?s.get(C):null;C&&s.delete(C);let M=new Map;So(I?.animations).forEach(z=>{let ue=Ft(z);if(!ue)return;let be=R?.persistentAnimationSessions?.get(ue)??o.get(ue),wt=Math.max(0,Ro(z)),En=be?.startedAt??R?.builtAt??Date.now();M.set(ue,{animation:structuredClone(z),startedAt:En,expiresAt:En+wt})}),o=M,R?.usedRestoredPersistentAnimationSessions&&(i=new Map)},T=()=>t.selectSystemState(),w=()=>t.selectSaveSlotMap(),D=I=>t.selectSaveSlot(I),F=I=>t.selectSaveSlotPage(I),V=()=>t.selectSkipMode(),N=()=>t.selectAutoMode(),j=()=>t.selectRuntime(),U=()=>t.selectIsChoiceVisible(),q=()=>t.selectIsFormVisible(),G=()=>t.selectActiveInteraction(),ie=(I,C,R={})=>I!=="nextLine"||!It(C)?C:R.bypassChoice===!0?{...C,bypassChoice:!0}:R.interactionSource===bn?{...C,_interactionSource:bn}:C,te=(I,C)=>{if(!t[I])return;Fu.has(I)&&(Uu.has(I)?i=a(o):i=new Map,o=new Map);let R=t[I](C);return d(),R},W=(I,C,R,M={})=>{if(I===Oi){let z=_(R),ue=Sr({[I]:C},z);H(ue[I],R,M);return}te(I,C)},x=(I,C)=>{W(I,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:C,...R}=I,M=t.selectAllVariables?t.selectAllVariables():void 0;return{...R,_event:C,variables:M,runtime:t.selectRuntime?t.selectRuntime():{}}},P=I=>{if(!It(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")},re=(I,C,R)=>{if(!It(I))throw new Error(`conditional branch at index ${C} must be an object`);if(!It(I.actions))throw new Error(`conditional branch at index ${C} requires actions object`);if(!Object.prototype.hasOwnProperty.call(I,"when")&&C!==R-1)throw new Error("conditional else branch must be the last branch")},H=(I,C,R)=>{P(I);for(let M=0;M<I.branches.length;M+=1){let z=I.branches[M];re(z,M,I.branches.length);let ue=_(C);if(!(Object.prototype.hasOwnProperty.call(z,"when")&&!ct(z.when,ue))){Zt(z.actions,C,R);return}}},K=(I,C)=>({...I??{},_form:C}),At=(I,C,R,M)=>{let z=te(I,C),ue=z?.submitted===!0&&z.valid===!0,be=z?.cancelled===!0;!ue&&!be||It(C.actions)&&Zt(C.actions,K(R,z.form),{...M,interactionSource:bn})},He=(I,C,R,M)=>{let z=_(R),be=Sr({[I]:C},z)[I];if(I===Oi){H(be,R,M);return}let wt=ie(I,be,M);if(Bu.has(I)){At(I,wt,R,M);return}te(I,wt)},Zt=(I,C,R)=>{Object.entries(I).forEach(([M,z])=>{He(M,z,C,R)})},wn=(I,C,R={})=>{t.beginRollbackActionBatch({source:R.rollbackSource});try{Zt(I,C,R)}finally{t.endRollbackActionBatch({})}};return{init:f,handleAction:W,handleInternalAction:x,handleActions:wn,selectRenderState:A,prepareRenderState:v,commitRenderState:S,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:T,selectSaveSlotMap:w,selectSaveSlot:D,selectSaveSlotPage:F,selectSaveSlots:w,selectRuntime:j,selectIsChoiceVisible:U,selectIsFormVisible:q,selectActiveInteraction:G,handleLineActions:()=>{let I=t.selectCurrentLine();return I?.actions?(wn(I.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var An=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},zu=80,$i=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},Wu=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&$i({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},qu=({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 l=n.delay??1e3;r.getElapsed()>=l&&(t.remove(i),r.setCallback(null),r.setElapsed(0),Qt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},Hu=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Yu=({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 l=n?.delay??zu;r.getElapsed()>=l&&(r.setElapsed(0),Qt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},Gu=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Ku=({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 l=n.delay??1e3;r.getElapsed()>=l&&(r.setElapsed(0),Qt(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},Ju=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Xu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},Qu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},Zu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},ed=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},td=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},Li={render:$i,saveSlots:Xu,saveGlobalDeviceVariables:Qu,saveGlobalAccountVariables:Zu,saveGlobalRuntime:ed,applyScopedDataUpdates:td,handleLineActions:Wu,startAutoNextTimer:qu,clearAutoNextTimer:Hu,startSkipNextTimer:Yu,clearSkipNextTimer:Gu,nextLineConfigTimer:Ku,clearNextLineConfigTimer:Ju},rd=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Qt=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},nd=(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(!rd.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},od=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let a=An(),c=An(),u=An(),d=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(d)return d;let x=e();return d=yn({indexedDB:i,namespace:l??x?.getNamespace?.()}),d},v=x=>{f=f.catch(()=>{}).then(()=>{let _=A();return x(_)}).catch(_=>{b(_)})},S=x=>{let _=typeof x?.id=="string"&&x.id.length>0?x.id:null;y+=1,p=_,g=!1},T=()=>y,w=(x={})=>{if(x?.aborted===!0)return!1;let _=typeof x?.id=="string"&&x.id.length>0?x.id:null;return _?_!==p||_===h?!1:(h=_,!0):p!==null||g?!1:(g=!0,!0)},D=(x,_={})=>{if(x!=="renderComplete"||!w(_))return!1;let P=e();return Qt(P,"markLineCompleted",{}),!0},F=new Set(["updateFormField","submitForm","cancelForm"]),V=x=>typeof x?.selectActiveInteraction=="function"?x.selectActiveInteraction():typeof x?.selectIsChoiceVisible=="function"&&x.selectIsChoiceVisible()?{source:"choice"}:null,N=x=>x?._formKey??x?.formKey,j=(x,_)=>N(x)===_?.formKey,U=(x,_)=>!x||typeof x!="object"||Array.isArray(x)||x._interactionSource!==_?.source?!1:_.source==="form"?j(x,_):!0,q=(x,_)=>!x||typeof x!="object"||Array.isArray(x)||_?.source!=="form"?!1:j(x,_),G=(x={},_)=>{let P=x?.actions;return _?.source==="form"?U(x,_)?!0:!P||typeof P!="object"||Array.isArray(P)?!1:Object.entries(P).some(([re,H])=>F.has(re)&&q(H,_)):U(x,_)?!0:!P||typeof P!="object"||Array.isArray(P)?!1:Object.values(P).some(re=>U(re,_))},ie=(x,_={})=>{if(!_?.actions)return!1;let P=V(x);return!P||P.source==="choice"?!1:!G(_,P)},te=({preprocessPayload:x,onEvent:_}={})=>async(P,re={})=>{let H=e();if(ie(H,re))return _?.(P,re);let K=await x?.(P,re)??re;if(ie(H,K))return _?.(P,K);if(D(P,K),K?.actions){let At=K?._event?{_event:K._event}:K?.event?{_event:K.event}:void 0,He;K?.bypassChoice===!0?He={bypassChoice:!0}:K?._interactionSource&&(He={interactionSource:K._interactionSource}),He?H.handleActions(K.actions,At,He):H.handleActions(K.actions,At)}return _?.(P,K)},W=x=>{let _=e(),P=nd(x);P.forEach(H=>{if(!Li[H.name]&&!n)throw new Error(`Unhandled pending effect "${H.name}".`)});let re={engine:_,routeGraphics:t,ticker:r,autoTimer:a,skipTimer:c,nextLineConfigTimerState:u,trackRenderDispatch:S,getRenderDispatchCount:T,enqueuePersistenceWrite:v};for(let H of P){let K=Li[H.name];if(K){K(re,H.payload);continue}n(H,re)}};return W.handleRouteGraphicsEvent=D,W.createRouteGraphicsEventHandler=te,W},id=od;var sd=(e,t={})=>{let{resources:r={}}=t;return Zr(e,r)};var Sf=In;export{Or as DEFAULT_VISUAL_LAYER,Xe as RENDER_LAYER,ve as VISUAL_LAYER,id as createEffectsHandler,Mu as createIndexedDbPersistence,Sf as default,js as resolveComputedVariables,sd as resolveLayoutReferences};
1
+ var Di=Object.defineProperty;var Pi=(e,t)=>{for(var r in t)Di(e,r,{get:t[r],enumerable:!0})};var _n=Symbol.for("immer-nothing"),vn=Symbol.for("immer-draftable"),ae=Symbol.for("immer-state");function pe(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Ye=Object.getPrototypeOf;function ce(e){return!!e&&!!e[ae]}function Te(e){return e?On(e)||Array.isArray(e)||!!e[vn]||!!e.constructor?.[vn]||St(e)||Rt(e):!1}var Ni=Object.prototype.constructor.toString();function On(e){if(!e||typeof e!="object")return!1;let t=Ye(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)===Ni}function Et(e,t){Ct(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function Ct(e){let t=e[ae];return t?t.type_:Array.isArray(e)?1:St(e)?2:Rt(e)?3:0}function nr(e,t){return Ct(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Ln(e,t,r){let n=Ct(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function Vi(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function St(e){return e instanceof Map}function Rt(e){return e instanceof Set}function ke(e){return e.copy_||e.base_}function or(e,t){if(St(e))return new Map(e);if(Rt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=On(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[ae];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(Ye(e),n)}else{let n=Ye(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function lr(e,t=!1){return _t(e)||ce(e)||!Te(e)||(Ct(e)>1&&(e.set=e.add=e.clear=e.delete=ji),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>lr(n,!0))),e}function ji(){pe(2)}function _t(e){return Object.isFrozen(e)}var Mi={};function De(e){let t=Mi[e];return t||pe(0,e),t}var nt;function $n(){return nt}function Fi(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function xn(e,t){t&&(De("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function ir(e){sr(e),e.drafts_.forEach(Ui),e.drafts_=null}function sr(e){e===nt&&(nt=e.parent_)}function Cn(e){return nt=Fi(nt,e)}function Ui(e){let t=e[ae];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Sn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[ae].modified_&&(ir(t),pe(4)),Te(e)&&(e=vt(t,e),t.parent_||xt(t,e)),t.patches_&&De("Patches").generateReplacementPatches_(r[ae].base_,e,t.patches_,t.inversePatches_)):e=vt(t,r,[]),ir(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==_n?e:void 0}function vt(e,t,r){if(_t(t))return t;let n=t[ae];if(!n)return Et(t,(o,i)=>Rn(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return xt(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),Et(i,(c,a)=>Rn(e,n,o,c,a,r,s)),xt(e,o,!1),r&&e.patches_&&De("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function Rn(e,t,r,n,o,i,s){if(ce(o)){let c=i&&t&&t.type_!==3&&!nr(t.assigned_,n)?i.concat(n):void 0,a=vt(e,o,c);if(Ln(r,n,a),ce(a))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(Te(o)&&!_t(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;vt(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&xt(e,o)}}function xt(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&lr(t,r)}function Bi(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:$n(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=ur;r&&(o=[n],i=ot);let{revoke:s,proxy:c}=Proxy.revocable(o,i);return n.draft_=c,n.revoke_=s,c}var ur={get(e,t){if(t===ae)return e;let r=ke(e);if(!nr(r,t))return zi(e,r,t);let n=r[t];return e.finalized_||!Te(n)?n:n===tr(e.base_,t)?(rr(e),e.copy_[t]=cr(n,e)):n},has(e,t){return t in ke(e)},ownKeys(e){return Reflect.ownKeys(ke(e))},set(e,t,r){let n=kn(ke(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=tr(ke(e),t),i=o?.[ae];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(Vi(r,o)&&(r!==void 0||nr(e.base_,t)))return!0;rr(e),ar(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 tr(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,rr(e),ar(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=ke(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){pe(11)},getPrototypeOf(e){return Ye(e.base_)},setPrototypeOf(){pe(12)}},ot={};Et(ur,(e,t)=>{ot[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ot.deleteProperty=function(e,t){return ot.set.call(this,e,t,void 0)};ot.set=function(e,t,r){return ur.set.call(this,e[0],t,r,e[0])};function tr(e,t){let r=e[ae];return(r?ke(r):e)[t]}function zi(e,t,r){let n=kn(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function kn(e,t){if(!(t in e))return;let r=Ye(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=Ye(r)}}function ar(e){e.modified_||(e.modified_=!0,e.parent_&&ar(e.parent_))}function rr(e){e.copy_||(e.copy_=or(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Wi=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"&&pe(6),n!==void 0&&typeof n!="function"&&pe(7);let o;if(Te(t)){let i=Cn(this),s=cr(t,void 0),c=!0;try{o=r(s),c=!1}finally{c?ir(i):sr(i)}return xn(i,n),Sn(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===_n&&(o=void 0),this.autoFreeze_&&lr(o,!0),n){let i=[],s=[];De("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else pe(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){Te(e)||pe(8),ce(e)&&(e=Pe(e));let t=Cn(this),r=cr(e,void 0);return r[ae].isManual_=!0,sr(t),r}finishDraft(e,t){let r=e&&e[ae];(!r||!r.isManual_)&&pe(9);let{scope_:n}=r;return xn(n,t),Sn(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=De("Patches").applyPatches_;return ce(e)?n(e,t):this.produce(e,o=>n(o,t))}};function cr(e,t){let r=St(e)?De("MapSet").proxyMap_(e,t):Rt(e)?De("MapSet").proxySet_(e,t):Bi(e,t);return(t?t.scope_:$n()).drafts_.push(r),r}function Pe(e){return ce(e)||pe(10,e),Tn(e)}function Tn(e){if(!Te(e)||_t(e))return e;let t=e[ae],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=or(e,t.scope_.immer_.useStrictShallowCopy_)}else r=or(e,!0);return Et(r,(n,o)=>{Ln(r,n,Tn(o))}),t&&(t.finalized_=!1),r}var le=new Wi,dr=le.produce,hd=le.produceWithPatches.bind(le),md=le.setAutoFreeze.bind(le),gd=le.setUseStrictShallowCopy.bind(le),yd=le.applyPatches.bind(le),bd=le.createDraft.bind(le),Id=le.finishDraft.bind(le);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},O={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},Ge={NOT:0};var E=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},ne=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var fr=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}')`)},Dn=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 Pn=(e,t,r=!1)=>{if(t===null)return new ne(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new ne(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new ne(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new ne(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},Nn=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new ne(`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=L(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},L=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return G(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return G(e.path,r,n);if(e.type===m.INTERPOLATION)return Yi(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return jn(e,t,r,n);case m.BINARY:return Mn(e,t,r,n);case m.UNARY:return Fn(e,t,r,n);case m.CONDITIONAL:return Ki(e,t,r,n);case m.LOOP:return es(e,t,r,n);case m.OBJECT:return rs(e,t,r,n);case m.ARRAY:return ns(e,t,r,n);case m.PARTIAL:return os(e,t,r,n);case m.PATH_REFERENCE:return is(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Vn=new Map,Hi=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},G=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=Vn.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=Hi(a.trim());n.push(...l)}Vn.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},Yi=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},jn=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Nn(e.name,o);let s=e.args.map(c=>L(c,t,r,n));return i(...s)},Ce=(e,t,r,n)=>{if(e.var&&!e.type)return G(e.var,r,n);switch(e.type){case m.VARIABLE:return G(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return Mn(e,t,r,n);case m.UNARY:return Fn(e,t,r,n);case m.FUNCTION:return jn(e,t,r,n);default:return L(e,t,r,n)}},Mn=(e,t,r,n)=>{if(e.op===O.AND||e.op===O.OR){let s=Ce(e.left,t,r,n),c=Ce(e.right,t,r,n);switch(e.op){case O.AND:return s&&c;case O.OR:return s||c}}let o=L(e.left,t,r,n),i=L(e.right,t,r,n);switch(e.op){case O.EQ:return o==i;case O.NEQ:return o!=i;case O.GT:return o>i;case O.LT:return o<i;case O.GTE:return o>=i;case O.LTE:return o<=i;case O.IN:return Array.isArray(i)?i.includes(o):!1;case O.ADD:if(typeof o!="number"||typeof i!="number")throw new ne(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case O.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new ne(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Fn=(e,t,r,n)=>{let o=e.op===Ge.NOT?Ce(e.operand,t,r,n):L(e.operand,t,r,n);if(e.op===Ge.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Gi=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(G(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?L(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]=G(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=G(f.path,r,n);u.push(p!=null?String(p):"")}else{let p=L(f,t,r,n);u.push(p!=null?String(p):"")}c[l]=u.join("")}else c[l]=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?L(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]=G(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=G(f.path,r,n);u.push(p!=null?String(p):"")}else{let p=L(f,t,r,n);u.push(p!=null?String(p):"")}c[l]=u.join("")}else c[l]=L(d,t,r,n)}return c}}}return null},Ki=(e,t,r,n)=>{let o=Gi(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||Ce(s,t,r,n))return L(e.bodies[i],t,r,n)}return Un},Ji=(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},Xi=(e,t)=>{let r=e.body,n=e.itemVar,o=Ji(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},Qi=(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?L(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]=G(b,r,{...n,[c]:d,...a&&{[a]:l}})}else u[g]=G(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,S;if(v===c)S=d;else if(v===a)S=l;else if(v.startsWith(c+".")){let P=v.substring(c.length+1);!P.includes(".")&&!P.includes("[")?S=d[P]:S=G(v,r,{...n,[c]:d,...a&&{[a]:l}})}else S=G(v,r,{...n,[c]:d,...a&&{[a]:l}});b.push(S!=null?String(S):"")}else{let v={...n,[c]:d,...a&&{[a]:l}},S=L(A,t,r,v);b.push(S!=null?String(S):"")}u[g]=b.join("")}else{let b={...n,[c]:d,...a&&{[a]:l}};u[g]=L(y,t,r,b)}}i.push(u)}return i}return null},Zi=(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},es=(e,t,r,n)=>{let o=L(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 Pn(u,o,d)}if(!e.indexVar){let l=Zi(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=Xi(e,o);if(l!==null)return l}let i=Qi(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=L(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},ts=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(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?L(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]=G(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=G(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]=G(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=G(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},rs=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!Ce(e.whenCondition,o,r,n))return;let i=ts(e,t,r,n);if(i!==null)return i;if(e.fast){let l={};for(let d of e.properties){let u=d.parsedKey?L(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]=G(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=G(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=L(h,t,r,n);p.push(g!=null?String(g):"")}l[u]=p.join("")}else l[u]=L(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(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(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=L(u.value,t,r,n);f!==void 0&&(s[l.key]=f)}else{let f=L(l.value,t,r,n);f!==void 0&&(s[l.key]=f)}}else{let u=l.parsedKey?L(l.parsedKey,t,r,n):l.key,f=L(l.value,t,r,n);f!==void 0&&(s[u]=f)}}return s},Un={},ns=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=L(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,r,n);s!==Un&&s!==void 0&&o.push(s)}return o},os=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,c=t.partials||{},a=t.functions||t;if(s&&!Ce(s,a,r,n))return;if(!c[o])throw new ne(`Partial '${o}' is not defined`);let l=n._partialStack||[];if(l.includes(o))throw new ne(`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=L(i,t,r,n);u={...u,...p}}return L(d,t,u,f)},is=(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 ne(`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 ne(`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 ne(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return c.length>0&&(a+="."+c.join(".")),a};var pr=qi;var ss=/\$\{([^}]*)\}/g,as=/#\{([^}]*)\}/g,zn=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=cs(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},cs=(e,t={})=>e.trim()?ls(e).map(n=>us(n.trim(),t)):[],ls=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},us=(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=zn(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=Ne(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 Q(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},Wn=/^\w+\(.*\)$/,ds=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,fs=e=>{if(!(!e||e.trim()===""||Wn.test(e))&&ds.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}"`)},Bn=e=>{let t=e.trim();if(Wn.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}},it=(e,t={})=>{let r=e.trim();fs(r);let n=zn(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}},hr=(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(ss)],i=[...r.matchAll(as)],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"?it(l[1],t):Bn(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=it(f.trim(),t):h=Bn(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 yr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Yn=e=>Object.keys(e),ee=e=>e.join("."),Se=(e,t,r)=>{let n=Yn(e).filter(o=>!t.has(o));if(n.length>0)throw new E(`Unexpected key '${n[0]}' in condition JSON at '${ee(r)}'`)},Re=(e,t)=>typeof e=="string"?hr(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?hs(e,t):ms(e,t):{type:m.LITERAL,value:e},ps=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}},hs=(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=ps(i),l=Object.keys(a);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let d=Hn(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=Hn(c[0],i[c[0]],t);r.push(a),n=!0;continue}}let s=Re(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}},ms=(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=Re(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=qn(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=qn(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=gs(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=Re(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=hr(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},gs=(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());fr(l);let d=Q(l,r);for(n.push(d),o.push(Re(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{fr(h);let g=Q(h,r);n.push(g)}if(o.push(Re(f,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:a},nextIndex:i}},mr={eq:O.EQ,neq:O.NEQ,gt:O.GT,gte:O.GTE,lt:O.LT,lte:O.LTE,in:O.IN,add:O.ADD,sub:O.SUBTRACT},gr={all:O.AND,any:O.OR},ys=new Set(["var","literal","call","not",...Object.keys(mr),...Object.keys(gr)]),bs=(e,t,r)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${ee(r)}' requires an array`);if(e.length!==2)throw new E(`Condition JSON operator '${t}' at '${ee(r)}' requires exactly 2 operands`);return e},Is=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${ee(o)}' requires an array`);if(e.length===0)throw new E(`Condition JSON operator '${t}' at '${ee(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}))},As=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],Se(e,new Set(["call","args"]),r);else if(yr(e.call))n=e.call.name,o=e.call.args??[],Se(e,new Set(["call"]),r),Se(e.call,new Set(["name","args"]),[...r,"call"]);else throw new E(`Condition JSON call at '${ee(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new E(`Condition JSON call at '${ee(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new E(`Invalid condition JSON function name '${n}' at '${ee(r)}'`);if(!Array.isArray(o))throw new E(`Condition JSON call '${n}' at '${ee(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 '${ee(r)}' must be wrapped in an operator or { literal: [...] }`);if(!yr(e))throw new E(`Invalid condition JSON value at '${ee(r)}'`);let n=Yn(e);if(n.length===0)throw new E(`Condition JSON object at '${ee(r)}' must contain an operator`);let o=n.filter(s=>ys.has(s));if(o.length===0)throw new E(`Unknown condition JSON operator '${n[0]}' at '${ee(r)}'`);if(o.length>1)throw new E(`Condition JSON at '${ee(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(Se(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new E(`Condition JSON var at '${ee(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return Se(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return As(e,t,r);if(i==="not")return Se(e,new Set(["not"]),r),{type:m.UNARY,op:Ge.NOT,operand:Ie(e.not,t,[...r,"not"])};if(i in gr)return Se(e,new Set([i]),r),Is(e[i],i,gr[i],t,[...r,i]);if(i in mr){Se(e,new Set([i]),r);let s=bs(e[i],i,[...r,i]);return{type:m.BINARY,op:mr[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 '${ee(r)}'`)},qn=(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 Q(e,t)}return yr(e)||Array.isArray(e)?Ie(e,t):{type:m.LITERAL,value:e}},Q=(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 Q(l,t)}let r=Ne(e,"||");if(r!==-1)return{type:m.BINARY,op:O.OR,left:Q(e.substring(0,r).trim(),t),right:Q(e.substring(r+2).trim(),t)};let n=Ne(e,"&&");if(n!==-1)return{type:m.BINARY,op:O.AND,left:Q(e.substring(0,n).trim(),t),right:Q(e.substring(n+2).trim(),t)};let o=[{op:">=",type:O.GTE},{op:"<=",type:O.LTE},{op:"==",type:O.EQ},{op:"!=",type:O.NEQ},{op:">",type:O.GT},{op:"<",type:O.LT},{op:" in ",type:O.IN}];for(let{op:l,type:d}of o){let u=Ne(e,l);if(u!==-1)return{type:m.BINARY,op:d,left:Q(e.substring(0,u).trim(),t),right:Q(e.substring(u+l.length).trim(),t)}}let i=-1,s=null,c=[{op:" + ",type:O.ADD},{op:" - ",type:O.SUBTRACT}];for(let{op:l,type:d}of c){let u=0;for(;u<e.length;){let f=Ne(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:Q(e.substring(0,i).trim(),t),right:Q(e.substring(i+s.op.length).trim(),t)};let a=[" * "," / "," % "];for(let l of a)if(Ne(e,l)!==-1)throw new E(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:m.UNARY,op:Ge.NOT,operand:Q(e.substring(1).trim(),t)}:Gn(e,t)},Ne=(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},ws=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}},Gn=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return it(r,t);let o=ws(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return it(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Es=(e,t=!1)=>{let r=t?"$each":"$for";try{Dn(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}},Hn=(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();Es(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=Gn(d,r),g=Re(t,r);return{type:m.LOOP,itemVar:u,indexVar:f,iterable:h,body:g,flatten:s!=="nested"}};var vs=(e,t={})=>{let{functions:r={}}=t;return Re(e,r)},Ot=vs;var st={};Pi(st,{now:()=>xs});var xs=()=>Date.now();var Cs=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...st,...n},s=Ot(e,{functions:i}),c={};for(let[a,l]of Object.entries(o))c[a]=Ot(l,{functions:i});return pr(s,t,{functions:i,partials:c})},se=Cs;var Ss=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Rs=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,_s=(e,t)=>{if(Ss(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression");return Q(e,t)}return Ie(e,t)},Os=(e,t={},r={})=>{let n=Rs(r),o={...st,...n},i=_s(e,o);return!!Ce(i,{functions:o,partials:{}},t,{})},br=Os;var ct=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return br(e,t)},eo=(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=dr(n,p=>{let h=l(c(p),...d);u=h!==void 0&&!ce(h)?h:void 0}),u});return{...o,...i}},kt=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return dr(n,i=>{o.forEach(s=>{t.forEach(c=>{c(i,s)})})})};var Ls=(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{}}},me=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),at=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),to=e=>{let t=ce(e)?Pe(e):e;return structuredClone(t)},_e=e=>me(e,"computed"),Ke=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!_e(t[r]))),$s=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),Ir=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},ks=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=$s(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 Ir(s,i)}return n==="runtime"?Ir(t.runtime,r.slice(1)):Ir(t,r)},Ts=(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)`)},Kn=(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`)},Ds=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},he=(e,t,r,n)=>(Ts(e,t,n),t.map(o=>$t(o,r))),de=(e,t,r,n)=>{let o=he(e,t,r,n);return o.forEach(i=>Ds(e,i)),o},Ps=(e,t,r)=>{switch(e){case"var":return ks(t,r);case"add":{let[n,o]=de(e,t,r,2);return n+o}case"sub":{let[n,o]=de(e,t,r,2);return n-o}case"mul":{let[n,o]=de(e,t,r,2);return n*o}case"div":{let[n,o]=de(e,t,r,2);return n/o}case"mod":{let[n,o]=de(e,t,r,2);return n%o}case"neg":{let[n]=de(e,t,r,1);return-n}case"round":{let[n]=de(e,t,r,1);return Math.round(n)}case"floor":{let[n]=de(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=de(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=de(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=de(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=de(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=he(e,t,r,2);return n==o}case"neq":{let[n,o]=he(e,t,r,2);return n!=o}case"gt":{let[n,o]=he(e,t,r,2);return n>o}case"gte":{let[n,o]=he(e,t,r,2);return n>=o}case"lt":{let[n,o]=he(e,t,r,2);return n<o}case"lte":{let[n,o]=he(e,t,r,2);return n<=o}case"in":{let[n,o]=he(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return Kn(e,t),t.every(n=>!!$t(n,r));case"or":case"any":return Kn(e,t),t.some(n=>!!$t(n,r));case"not":{let[n]=he(e,t,r,1);return!n}case"length":{let[n]=he(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:at(n)?Object.keys(n).length:0}case"includes":{let[n,o]=he(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return to(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},$t=(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 Ps(n,o,t)},Ns=(e,t={})=>ct(e,{variables:t.variables,runtime:t.runtime}),Vs=(e,t)=>{if(!at(e))throw new Error(`${t} must be an object`);let r=me(e,"expr"),n=me(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},Ar=(e,t,r)=>(Vs(e,t),me(e,"value")?to(e.value):$t(e.expr,r)),js=(e,t={},r="unknown")=>{if(!at(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=me(e,"expr"),o=me(e,"value");if(me(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(!at(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(!at(c))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!me(c,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(Ns(c.when,t))return Ar(c,`Computed variable "${r}" branch ${s}`,t)}return Ar(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 Ar(e,`Computed variable "${r}"`,t)},Ms=(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}`)}},Tt=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=Ke(e,r),i=Object.entries(r).filter(([,u])=>_e(u)).map(([u])=>u),s={},c=[],a=u=>{if(me(s,u))return s[u];let f=r[u];if(!_e(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=js(f.computed,d,u);return Ms(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"&&(me(o,f)||i.includes(f)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(u,f)=>{if(!(typeof f!="string"||!me(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},Fs=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>Tt({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),vr=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(_e(o))return;let i=Ls(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},Dt=(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(", ")}`)},Pt=(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(", ")}`)},Us=2,Jn=12,ro=(e=Us)=>{if(!Number.isInteger(e)||e<0||e>Jn)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${Jn}.`);return e},Bs=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},Lt=e=>typeof e=="number"&&Number.isFinite(e),xr=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!Lt(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!Lt(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!Lt(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}".`);ro(o.roundTo)}}},Nt=(e,t,r,n={})=>{let o=(s,c,a)=>{let l=s??c;if(!Lt(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 Bs(o(e,0,"current value")/i(r),ro(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 no=(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()))},zs=(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},Xn=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},Qn=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},Zn=(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,Ws=(e,t)=>{let r={},n=Zn(Xn(e),Xn(t)),o=Zn(Qn(e),Qn(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},Cr=(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=Ws(e.background,t.background);i&&(r.background=i),o("screen"),o("bgm"),o("voice");let s=zs(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},Sr=(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},qs=(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},Hs=(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=qs(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},Ys={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"])},oo=(e,t)=>{let r=e[e.length-1];return r?Ys[r]?.has(t)===!0:!1},wr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>wr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,oo(r,n)?o:wr(o,t,[...r,n])])):Hs(e,t),Er=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Er(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,oo(r,n)?o:Er(o,t,[...r,n])])):typeof e=="string"?se(e,t):e,Rr=(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=wr(e,t._event);return Er(r,t)};var oe=e=>structuredClone(ce(e)?Pe(e):e),W=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),io=e=>e?.animations?.playback?.continuity==="persistent",V=(e,t)=>W(e??{},t)&&e[t]!==void 0,lt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:oe(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Gs=e=>V(e,"opacity")||V(e,"blur"),co=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],lo=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Ks=e=>co.some(t=>V(e,t)),so=e=>lo.some(t=>V(e,t)),Js=(e,t)=>{if(!t)return e;for(let r of lo)!V(e,r)&&V(t,r)&&(e[r]=t[r]),W(e,r)&&e[r]===void 0&&delete e[r];return e},Xs=(e,t,r)=>{let n=e[r];return n?.id===t?.id?n:e.find(o=>o.id===t?.id)},Qs=(e,t)=>{if(!t)return e;for(let r of co)!V(e,r)&&V(t,r)&&(e[r]=t[r]),W(e,r)&&e[r]===void 0&&delete e[r];return e},Zs=(e,t)=>(t&&(!V(e,"opacity")&&V(t,"opacity")&&(e.opacity=t.opacity),!V(e,"blur")&&V(t,"blur")&&(e.blur=oe(t.blur)),W(e,"opacity")&&e.opacity===void 0&&delete e.opacity,W(e,"blur")&&e.blur===void 0&&delete e.blur),e),uo=(e,t,r=[])=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let n=e.map((o,i)=>{let s=Xs(r,o,i),c=t(o),a=Gs(o),l=Ks(o),d=W(o,"animations"),u=oe(o);return!c&&(a||l)&&s&&(u={...oe(s),...u},d||delete u.animations),Zs(Qs(u,s),s)}).filter(o=>t(o)||o.animations);return{hasValidItems:n.length>0,processedItems:n}},ea=e=>{if(e){if(e.character&&W(e.character,"name"))return e.character.name;if(W(e,"characterName"))return e.characterName}},fo=e=>!!e?.character&&W(e.character,"sprite"),ta=e=>{let t={},r=!1,n=ea(e);return n!==void 0&&(t.name=n,r=!0),fo(e)&&(t.sprite=oe(e.character.sprite),r=!0),r?t:void 0},ao=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},ra=({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=>oe(o)):delete e.initialRevealedContent,e.content=[...n,...t]},na=()=>({}),oa=(e,t)=>{if(!t.screen)return;let r=V(t.screen,"opacity"),n=V(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:V(i,"opacity")&&(s.opacity=i.opacity),n?s.blur=oe(t.screen.blur):V(i,"blur")&&(s.blur=oe(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},ia=(e,t)=>{if(t.background){let r=V(t.background,"resourceId"),n=V(t.background,"colorId"),o=V(t.background,"opacity"),i=V(t.background,"blur"),s=V(t.background,"transformId"),c=so(t.background),{animationsOnly:a,state:l}=lt(t.background,f=>V(f,"resourceId")||V(f,"colorId")||V(f,"opacity")||V(f,"blur")||V(f,"transformId")||so(f));if(a){e.background=e.background?{...oe(e.background),...l}:l;return}if(!r&&!n&&!o&&!i&&!s&&!c){delete e.background;return}let d=e.background,u=oe(t.background);if(!r&&d?.resourceId&&(u.resourceId=d.resourceId,!W(u,"transformId")&&d.transformId&&(u.transformId=d.transformId)),Js(u,d),!n&&d?.colorId&&(u.colorId=d.colorId),!o&&V(d,"opacity")&&(u.opacity=d.opacity),!i&&V(d,"blur")&&(u.blur=oe(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")&&io(d)&&(u.animations=oe(d.animations)),e.background=u}else e.background?.animations&&!io(e.background)&&(e.background.animations={})},sa=(e,t)=>{if(!t.dialogue){e.dialogue&&(ao(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}=lt(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&&ra({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=ta(t.dialogue),c=s!==void 0,a=fo(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?{...oe(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,a||ao(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=oe(e.dialogue.character)),e.dialogue.lines.push(l)}},aa=(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},ca=(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}}},la=(e,t)=>{if(t.visual){let{hasValidItems:r,processedItems:n}=uo(t.visual.items,o=>!!o.resourceId,e.visual?.items||[]);r?e.visual={items:n}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(r=>r.animations?{...r,animations:{}}:r))},ua=(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}=uo(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},da=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},fa=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=lt(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},pa=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=lt(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},ha=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=lt(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=oe(t.form)}else e.form&&delete e.form},ma=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},ga=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},ya=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},Ve=e=>kt(na,[ya,oa,ia,aa,ca,la,sa,ua,da,fa,pa,ha,ma,ga])(e);var ba=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"}}),je=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),ut=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),po=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"]),Or=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Ia=(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]}},Je=e=>Object.fromEntries(Object.entries(ba).map(([t,r])=>{let n=Ia(e,r.source),o=n!==void 0?n:je[t]??ut[t];return[t,o]})),Ee=(e,t)=>Je(e)[t],ho=(e={})=>Object.fromEntries(_r.map(t=>[t,e[t]??je[t]]));var Xe=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:Xe.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:Xe.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:Xe.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:Xe.VISUAL_BEHIND_CHOICE,FOREGROUND:Xe.VISUAL_FOREGROUND}),Lr=ve.BEHIND_DIALOGUE,$r=Object.freeze(Object.values(ve).sort((e,t)=>e-t));var Oe={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:no},Aa=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,wa=(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},jt=(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=Aa.exec(s);if(c){let[,a,l,d]=c,u=wa(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=jt(y,g,r),A=se(b,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(jt(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=jt(i,t,r)}),n},Kr=({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".`)},Ea=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);if(Kr({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n!==void 0){let s=Sa(n,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},va=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Kr({animationType:e.type,animationId:t,animationPath:r}),e.type},xa=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Ca=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Sa=(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},Ra=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},Bt=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ro=e=>e?.playback?.continuity==="persistent",jr=e=>Array.isArray(e)?e.map(jr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=jr(e[r]),t),{}),Ft=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(jr(t))},_o=(e=[])=>e.filter(t=>Ro(t)).map(t=>structuredClone(t)),Oo=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,kr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,Oo(r)),0),Lo=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(kr(e.tween),kr(e.prev?.tween),kr(e.next?.tween),Oo(e.mask?.progress))/Ra(e),mo=({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(Ft).filter(Boolean));return e.some(n=>{if(!Ro(n))return!1;let o=Ft(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||mo({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:mo({animationInstances:e,activePersistentAnimations:o}),_a=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Oa=(e,t)=>{if(_a(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},La=({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?Ea({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},$a=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Kr({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},Jr=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push($a(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Mr=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=se(e,t);return r&&typeof r=="object"?e:r},Fr=(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},ka=({content:e,path:t,variables:r})=>Fr(e,t).reduce((n,o)=>{let i=Mr(o.text,{variables:r});return n+`${i??""}`.length},0),go=(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))},Vt=(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("-")}`},Tr=(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},Ta=(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},Da=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Pa=(e={})=>Da.some(t=>Bt(e,t)),Na=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},Ur=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Va=(e={})=>e.textStyles||{},ja=(e={})=>e.images||{},Ma=(e={})=>e.colors||{},Fa=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,dt=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,Ze=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},yo=(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},Xr=(e,t)=>{if(typeof e!="string"||!Fa.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},bo=(e,t,r)=>{let n=Xr(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})`},Ua=(e={},t)=>{let r=Va(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=yo(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:bo(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=yo(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=bo(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},Br=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Br(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]=Br(i,t,dt(r,o)));return e.textStyleId!==void 0&&(Ze(e.textStyleId,r,"textStyleId"),n.textStyle=Ua(t,e.textStyleId)),n},Qr=(e={},t)=>{let r=Ma(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return Xr(r.hex,`Color "${t}"`)},$o=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Dr=(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 ${$o(`${t}.fill`)} instead`)},Ba=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>ft(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]=ft(i,t,dt(r,o)));return e.colorId!==void 0&&(Ze(e.colorId,r,"colorId"),n.fill=Qr(t,e.colorId)),n},ft=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>ft(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 ${$o("fill")} instead`);Dr(e,"hover",r),Dr(e,"click",r),Dr(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]=Ba(i,t,dt(r,o));continue}n[o]=ft(i,t,dt(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(Ze(e.colorId,r,"colorId"),n.fill=Qr(t,e.colorId)),n},Pr=(e={},t)=>{let r=ja(e)?.[t];return r||null},ko=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",Io=(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 ${ko(`${t}.${n}`)} instead`)},Ao=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},zr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>zr(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 ${ko(o)} instead`);Io(e,"hover",r,"src"),Io(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]=zr(i,t,dt(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){Ze(e.imageId,r,"imageId");let o=Pr(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&&(Ze(e.hoverImageId,r,"hoverImageId"),Ao(n,"hover",Pr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(Ze(e.clickImageId,r,"clickImageId"),Ao(n,"click",Pr(t,e.clickImageId)?.fileId??e.clickImageId)),n},Zr=(e,t={},r="root")=>zr(ft(Br(e,t,r),t,r),t,r),Le=Zr,Fe=(e=[])=>e.find(t=>t.id==="story"),za="#000000",Wr="bg-cg-background-color",Wa=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?Xr(r?.backgroundColor??za,"screen.backgroundColor"):Qr(e,t.colorId),To=(e={})=>{if(Bt(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},qa=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},wo=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=To(e),n=qa(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},Ha=(e={})=>{if(Bt(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Ya=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Do=(e={})=>{let t=Ha(e),r=Ya(e),n={};return t!==void 0&&(n.alpha=t),r&&(n.blur=r),n},Mt=(e={})=>Do(e),Me=(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},Ga=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:Wr,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:Wa({resources:e,background:t,screen:r})};if(n){let i=To(t);i!==void 0&&(o.alpha=i)}return o},Ka=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.layouts?.[t]):!1,Eo=({resources:e={},resourceId:t,colorId:r})=>{let n=Na(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:Ur({resourceId:t,kind:n})}:r!==void 0?{resourceId:Wr,targetId:Wr}:{resourceId:void 0,targetId:void 0}},Po=100,zt=Po,No=(e,t)=>e*t/Po,Ja=(e={},t=zt)=>e?.muteAll?0:No(t,e?.soundVolume??je.soundVolume),Xa=(e={},t=zt)=>e?.muteAll?0:No(t,e?.musicVolume??je.musicVolume),Qa=({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=nc({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e}),S={variables:e,runtime:A,saveSlots:r,isChoiceVisible:a,isFormVisible:l,canRollback:d,confirmDialog:u,form:f,historyDialogue:p,characters:h};return v&&(S.dialogue=v,S.dialogueLines=v.lines),S},vo=100,Ut=(e,t)=>{if(Array.isArray(e))return e.map(n=>Ut(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=Ut(r[n],t)}),r.type==="text-revealing"?t(r):r},Za=e=>Ut(e,t=>({...t,revealEffect:"none"})),ec=e=>Ut(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,vo):vo;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),$e=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?Za(e):r?ec(e):e,Vo=({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:{}}}}),qr=e=>{if(Array.isArray(e))return e.map(qr);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=qr(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}}:{}}}}},tc=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),xo="submit",Nr=(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}}},Hr=(e,t,r={})=>{if(Array.isArray(e))return e.map(l=>Hr(l,t,r));if(!e||typeof e!="object")return e;let n=typeof e.type=="string",o=n&&e.formRole===xo,i=n&&r.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},c={};for(let[l,d]of Object.entries(e))c[l]=Hr(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:Nr(a.change,d),submit:Nr(a.submit,t.submitActions)}}}return a.formRole===xo||i?{...a,click:Nr(a.click,t.submitActions,{replaceActions:!0})}:a},Yr=(e,t)=>{if(Array.isArray(e))return e.map(n=>Yr(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Yr(o,t);for(let n of tc){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form"}})}return r},Gr=({characterId:e,character:t,characterName:r,characters:n={}}={})=>{let o=e?n?.[e]:void 0,i=t?.name!==void 0?t.name:r!==void 0?r:o?.name||"";return{...o||{},...t||{},name:i}},jo=(e=[],t={})=>e.map(r=>{let n=Gr({characterId:r.characterId,character:r.character,characterName:r.characterName,characters:t}),o=typeof r.text=="string"?r.text:Array.isArray(r.content)?r.content.map(i=>i?.text??"").join(""):"";return{...r,text:o,character:n,characterName:n.name}}),rc=e=>!(!e||e.mode==="adv"&&e.content===void 0),nc=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n}={})=>{if(!t&&!rc(e))return;let o=e.content===void 0?[{text:""}]:Fr(e.content,"dialogue.content"),i=e.content===void 0?0:ka({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),s=(e.lines||[]).map((a,l)=>{let d=Fr(a.content,`dialogue.lines[${l}].content`),u=Gr({characterId:a.characterId,character:a.character,characterName:a.characterName,characters:r});return{...a,content:d.map(f=>({...f,text:Mr(f.text,{variables:n})})),character:u,characterName:u.name}}),c=Gr({characterId:e.characterId,character:e.character,characters:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:c,content:o.map(a=>({...a,text:Mr(a.text,{variables:n})})),initialRevealedCharacters:i,lines:s}},Mo=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=se(e,r,{functions:Oe});return Le($e(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},Vr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),Co=({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:Vr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:Vr(o.keyup)});return}e[n]={...i,[r]:{payload:Vr(o)}}})},oc=(e={},t={})=>{let r={};return Co({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),Co({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},xe=({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=La({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;Oa(e,s);let p=xa(e),h=Ca(e),g=t?.animations?.[p],y=va(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},ic=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),sc=(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:S}=e;if(t.background){let P=n===void 0?!0:Bt(n?.background??{},"animations"),w=v.find(x=>x.id==="story");if(!w)return e;let N=Ta(o,t.background),F=N||Pa(t.background),j=r?.background?.resourceId,H=r?.background?.colorId,k=t.background.resourceId??(t.background.animations?j:void 0),U=t.background.colorId??(t.background.animations?H:void 0),q=Ka(o,k),K={...t.background,colorId:U};if((U!==void 0||q)&&w.children.push(Ga({resources:o,background:K,screen:i,includeOpacity:!q})),k){let{images:x={},videos:R={}}=o,$=x[k]||R[k];if($){let Y=R[k]!==void 0,X={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...N},B={id:Ur({resourceId:k,kind:Y?"video":"sprite"}),type:Y?"video":"sprite",src:$.fileId,width:$.width,height:$.height,...wo(t.background,{includeDefaultAlpha:!0}),...Me(X,t.background)};Y&&(B.loop=t.background.loop??!1,B.volume=$.volume??50),w.children.push(B)}}if(k){let{layouts:x={}}=o,R=x[k];if(R){let $={id:Ur({resourceId:k,kind:"container"}),type:"container",children:R.elements,...wo(t.background)};F&&Object.assign($,Me({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...N},t.background));let Y=se($,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:Oe});w.children.push(Le($e(Y,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:c}),o))}}let ie=Eo({resources:o,resourceId:j,colorId:H}),re=Eo({resources:o,resourceId:k,colorId:U}),J=xe({animationsDef:t.background.animations,resources:o,previousResourceId:ie.resourceId,currentResourceId:re.resourceId,previousTargetId:ie.targetId,currentTargetId:re.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});ge({animationInstances:J,isLineCompleted:s,skipTransitionsAndAnimations:c,activePersistentAnimations:d,restoredPersistentAnimations:u,isAuthoredOnCurrentLine:P})&&S.push(...J)}return e},ac=(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=go(d),p=go(u);for(let h=0;h<d.length;h++){let g=d[h],{transformId:y,sprites:b}=g,A=u.find(k=>k.id===g.id),v=u.findIndex(k=>k.id===g.id),S=A?.sprites&&A.sprites.length>0,P=b&&b.length>0,w=v>=0?Vt(A,v,p):void 0,N=xe({animationsDef:g.animations,resources:n,previousResourceId:w,currentResourceId:P?Vt(g,h,f):void 0,previousTargetId:w,currentTargetId:P?Vt(g,h,f):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&S&&ge({animationInstances:N,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...N);continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let F=Vt(g,h,f),j=n.transforms[y];if(!j){console.warn("Transform not found:",y);continue}let H={type:"container",id:F,...Me(j,g),...Mt(g),children:[]};for(let k of b){let U=n.images[k.resourceId];if(!U){console.warn(`Image resource not found: ${k.resourceId}`);continue}H.children.push({type:"sprite",id:`${F}-${k.id}`,src:U.fileId,width:U.width,height:U.height,x:0,y:0})}l.children.push(H),ge({animationInstances:N,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...N)}}return e},Fo=(e,t)=>{if(!$r.includes(e))throw new Error(`${t} must be one of: ${$r.join(", ")}.`)},cc=(e,t)=>{let r=e.layer??(e.resourceId?void 0:t?.layer)??Lr;return Fo(r,`Visual item "${e.id}" layer`),r},lc=(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 S=t.visual.items,P=r?.visual?.items||[];y!==void 0&&Fo(y,"visualLayer");for(let w of S){let N=P.find(H=>H.id===w.id),F=cc(w,N);if(y!==void 0&&F!==y)continue;if(w.resourceId){let{images:H={},videos:k={},spritesheets:U={}}=n,q=U[w.resourceId];if(q){let K=Tr(n,w),ie=w.animationName;if(ie){let re=q.animations?.[ie];if(!re)throw new Error(`Animation '${ie}' not found in spritesheet resource '${w.resourceId}'`);let J=Mt(w),x={id:`visual-${w.id}`,type:"animated-sprite",...Me(K,w),width:w.width??q.width,height:w.height??q.height,alpha:J.alpha??w.alpha??1,spritesheetSrc:q.fileId,spritesheetData:q.jsonData,animation:{frames:re.frames,animationSpeed:w.animationSpeed??re.animationSpeed??.5,loop:w.loop??re.loop??!0}};J.blur&&(x.blur=J.blur),v.children.push(structuredClone(x))}}else{let K=H[w.resourceId]||k[w.resourceId];if(K){let ie=k[w.resourceId]!==void 0,re=Tr(n,w),J={id:`visual-${w.id}`,type:ie?"video":"sprite",src:K.fileId,width:K.width,height:K.height,...Me(re,w)};Object.assign(J,Mt(w)),ie&&(J.loop=K.loop??!1,J.volume=K.volume??50),v.children.push(J)}}}if(w.resourceId){let{layouts:H={}}=n,k=H[w.resourceId];if(k){let U=Tr(n,w),q={id:`visual-${w.id}`,type:"container",children:structuredClone(k.elements),...Me(U,w)};Object.assign(q,Mt(w));let K=se(q,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}),{functions:Oe});v.children.push(Le($e(K,{isLineCompleted:o,skipMode:d,skipTransitionsAndAnimations:i}),n))}}let j=xe({animationsDef:w.animations,resources:n,previousResourceId:N?.resourceId,currentResourceId:w.resourceId,previousTargetId:N?.resourceId?`visual-${w.id}`:void 0,currentTargetId:w.resourceId?`visual-${w.id}`:void 0,animationPath:`visual.items[${w.id}].animations`,idPrefix:w.id});ge({animationInstances:j,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:a})&&A.push(...j)}}return e},Qe="dialogue-character-sprite",So=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,uc=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=Fe(e.elements);if(!a)return e;let l=t.dialogue?.character?.sprite,d=r?.dialogue?.character?.sprite,u=So(l),f=So(d),p=xe({animationsDef:l?.animations,resources:n,previousResourceId:f?Qe:void 0,currentResourceId:u?Qe:void 0,previousTargetId:f?Qe:void 0,currentTargetId:u?Qe: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:Qe,...Me(h),children:[]};for(let y of l.items){let b=n.images?.[y.resourceId];if(!b){console.warn(`Image resource not found: ${y.resourceId}`);continue}g.children.push({type:"sprite",id:`${Qe}-${y.id}`,src:b.fileId,width:b.width,height:b.height,x:0,y:0})}return a.children.push(g),ge({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e},dc=(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 S=A.find(w=>w.id==="story");if(!S)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:w={}}=n,N=w[t.dialogue.ui.resourceId];if(N){let F={elements:N.elements},j=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}),H={functions:Oe},k=jt(F,j,H),U=se(k,j,H),q=Le($e(U?.elements,{isLineCompleted:f,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(q))for(let K of q)S.children.push(K);else q&&S.children.push(q)}}uc(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let P=xe({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},fc=(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=Fe(b);if(!v)return e;let S=n?.layouts[t.choice.resourceId];if(S&&S.elements){let w={elements:S.elements},N=se(w,{...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:Oe}),F=qr(Le($e(N?.elements,{isLineCompleted:i,skipMode:d,skipTransitionsAndAnimations:s}),n));if(Array.isArray(F))for(let j of F)v.children.push(j);else F&&v.children.push(F)}let P=xe({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},pc=(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=Fe(b);if(!v)return e;let S=n?.layouts?.[y.resourceId];if(!S)return console.warn(`Form layout not found: ${y.resourceId}`),e;let P={id:"form-container",type:"container",x:0,y:0,children:S.elements||[]},w={...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},N=se(P,w,{functions:Oe}),F=Yr(Le($e(Hr(N,y),{isLineCompleted:i,skipMode:d,skipTransitionsAndAnimations:s}),n),y);F&&v.children.push(F);let j=xe({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:j,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(...j),e},hc=(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=oc(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=Fe(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(Mo({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},mc=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Fe(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:Xa(l,t.bgm.volume??a.volume??zt),startDelayMs:t.bgm.startDelayMs??null})}return e},gc=(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:Qa({item:c,index:s}),type:"sound",src:a.fileId,loop:c.loop??a.loop??!1,volume:Ja(n,c.volume??a.volume??zt),startDelayMs:c.startDelayMs??a.startDelayMs??null})}}return e},yc=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},bc=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,Ic=(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=yc(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:bc(c,f),loop:l??!1,startDelayMs:d??null}),e},Ac=(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=Fe(y);if(!P)return e;let w=n.layouts[t.layout.resourceId];if(!w)return e;Array.isArray(w.transitions)&&!p&&!h&&Jr({animations:b,transitions:w.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let N={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:w.elements||[]};P.children.push(Mo({container:N,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,S=xe({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:S,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(...S),e},wc=(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=xe({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},Ec=(e,{presentationState:t})=>{let r=Fe(e.elements);return!r||!t?.screen||Object.assign(r,Do(t.screen)),e},vc=(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,S)=>{let P=r.layouts[v.resourceId];if(!P){console.warn(`Overlay layout not found: ${v.resourceId}`);return}Array.isArray(P.transitions)&&(y||Jr({animations:A,transitions:P.transitions,defaultTargetId:`overlayStack-${S}`,idPrefix:`overlayStack-${S}`,animationPathPrefix:`overlayStack[${S}]`}));let w={id:`overlayStack-${S}`,type:"container",x:0,y:0,children:[Vo({id:`overlayStack-${S}-blocker`,screen:h}),...P.elements||[]]},N=jo(f,r.characters),F=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:N,characters:r.characters||{},skipTransitionsAndAnimations:y}),j=se(w,F,{functions:Oe}),[H,...k]=j.children||[],U=Le($e({...j,children:k},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...U,children:H?[H,...U.children||[]]:U.children})}),e},xc=(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&&Jr({animations:A,transitions:v.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let S={id:"confirmDialog",type:"container",x:0,y:0,children:[Vo({id:"confirmDialog-blocker",screen:h}),...v.elements||[]]},P=jo(p,r.characters),w=se(S,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:Oe}),[N,...F]=w.children||[],j=Le($e({...w,children:F},{isLineCompleted:g,skipMode:c,skipTransitionsAndAnimations:y}),r);return b.push({...j,children:N?[N,...j.children||[]]:j.children}),e},pt=e=>(t,r)=>lc(t,{...r,visualLayer:e}),Cc=pt(ve.BEHIND_BACKGROUND),Sc=pt(ve.BEHIND_CHARACTER),Rc=pt(ve.BEHIND_DIALOGUE),_c=pt(ve.BEHIND_CHOICE),Oc=pt(ve.FOREGROUND),Uo=e=>kt(ic,[hc,Cc,sc,Sc,ac,Rc,dc,_c,fc,pc,Ac,Oc,Ec,wc,mc,gc,Ic,vc,xc])(e);var Wt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Ho=1,en="choice",qt="form",Gt=()=>({manual:{...Wt.manual},auto:{...Wt.auto},applyMode:Wt.applyMode}),tn=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...Gt()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},D=e=>{let t=ce(e)?Pe(e):e;return structuredClone(t)},T=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Kt=e=>String(e),Yo=()=>({sections:[],resources:[]}),Lc=e=>T(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Yo(),$c=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",kc=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:$c(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),Tc=()=>({resourceId:void 0}),Dc=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},rn=(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}},Go=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)}}},Ko=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Jo=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Ho)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Pc=(e,t={})=>{let r;try{r=Jo(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:Ko(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},Nc=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Pc(t,r)])),Xo=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Ru(r));return t.length>0?t:void 0},Vc=e=>{!T(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!T(t))return;let r=Xo(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},Bo=(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}},jc=(e,t="viewedRegistry")=>{if(e===void 0)return Yo();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=Bo(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Bo(o,"resources",i,t);return[s.resourceId,s]})))}},Qo=(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}=rn(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}},Mc=(e,t,r)=>{if(!T(e)||!Array.isArray(e.timeline))return ht({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((c,a)=>{if(!T(c))return[];try{let l=Qo(c,r,`rollback.timeline[${a}]`),d=Yt({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:c.rollbackPolicy}),u=Xo(D(c.executedActions));return u&&(d.executedActions=u),[d]}catch{return[]}});if(n.length===0)return ht({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(Yt({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}},Fc=(e,t,r)=>{if(!T(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=sn(t),o=Qo(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?Ke(D(e.variables),t.resources?.variables??{}):{},s=Zc({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:Mc(e.rollback,o,t)};return s&&(c.runtime=s),c},Uc=(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)=>Fc(r,t,n))}},Bc=(e,t)=>{if(!T(e))throw new Error("Malformed save slot.");let r=Jo(e.formatVersion);return{...e,formatVersion:r,state:Uc(e.state,t)}},zo=(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},zc=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:zo(e.confirmActions,"confirmActions",{required:!0}),cancelActions:zo(e.cancelActions,"cancelActions")}},et=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Wc=e=>(T(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),tt=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},Zo=e=>{if(!(!T(e)||!e.animations))return{animations:D(e.animations)}},qc=(e,t)=>{let r=Zo(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},Hc=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},Yc=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},Ht=e=>String(e??""),ei=(e,t)=>{let r=Ht(t);return e?.trim===!0?r.trim():r},Gc=e=>T(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>T(t)).map(([t,r])=>[t,{id:t,...D(r)}])):{},Kc=(e,t)=>{if(!t||!T(e.global.formDrafts))return;let r=e.global.formDrafts[t];return T(r)?r:void 0},ti=(e,t)=>{let r=Wc(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},nn=(e,t)=>{let r=ei(e,t);return e?.required===!0&&r.length===0?"required":null},Jc=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=te({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:Ve(n.slice(0,o+1).map(i=>i.actions||{}))},Xc=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=Hc(t),o=Yc(r,n);if(!n||!o)return null;let i=Kc(e,o),s=Gc(t),c=dn({state:e}),a={},l=[],d={},u=!0;return Object.entries(s).forEach(([f,p])=>{let h=Ht(c?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},f)?Ht(i.values[f]):h,y=i?.touched?.[f]===!0,b=nn(p,g),A=i?.submitted||y?b:null,v=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,S={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]=S,l.push(S),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??{})}}}},Ue=[],Wo="line",on="interaction",Yt=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),sn=e=>{let{contextVariableDefaultValues:t}=vr(e??{});return D(t)},ri=()=>({...D(ut)}),ni=({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]=oi(s,D(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Qc=({loadedGlobalRuntime:e={}})=>ni({loadedRuntime:e,runtimeIds:_r,defaults:je,path:"global.runtime"}).runtimeState,Zc=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=ni({loadedRuntime:e,runtimeIds:Or,defaults:ri(),path:"context.runtime"});return r?t:void 0},an=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},el=e=>e.runtime?(Or.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=D(ut[t]))}),e.runtime):(e.runtime=ri(),e.runtime),tl=e=>ho(e.global),rl=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:tl(e)}})},nl=e=>po[e],ol=(e,t)=>{let r=nl(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}"`)},oi=(e,t)=>(ol(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),ii=(e,t,r)=>{let n=oi(t,r);if(t in ut){let o=an(e);if(!o)return n;let i=el(o);return i[t]=n,n}return e.global[t]=n,n},si=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:D(e)},configuration:{},views:[],bgm:Tc(),variables:sn(t),rollback:ht({pointer:e})}),rt=e=>e?(e.currentPointerMode="read",T(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,il=(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=si({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,sl(e,{queueRender:t}),o},sl=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,et(e),tt(e),e.global.nextLineConfig=Gt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},ai=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},ht=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[Yt({sectionId:e.sectionId,lineId:e.lineId})]:[]}},We=(e,t={})=>{if(e?.rollback)return ai(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=ht({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},cn=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=We(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(Yt(t)),n.currentIndex=n.timeline.length-1},al=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=Ue[Ue.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)},cl=({state:e},t={})=>{let r=t?.source===Wo?Wo:on,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?(Ue.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Ue.push({checkpointIndex:o.currentIndex,source:r}),e)},ll=({state:e})=>(Ue.pop(),e),Ae=(e,t,r)=>{let o=Ue[Ue.length-1]?.source??on;if(!_u(t,o))return;let i=al(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(_e(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Dt(l,o),Pt(d,i,o),xr(d,i,s,o,{roundTo:c}),l==="context"&&(r.variables[o]=Nt(r.variables[o],i,s,{roundTo:c}))}},ul=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{Ou(e,r,n)})},dl=(e,t)=>{let{sectionId:r,lineId:n}=t,s=te({state:e},{sectionId:r})?.lines?.find(c=>c.id===n)?.actions;s&&Object.entries(s).forEach(([c,a])=>{xi(e,c,a)})},ci=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=We(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&gt({state:e}),e.global.skipMode&&Be({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=sn(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=D(Wt),e.global.overlayStack=[],et(e),tt(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let c=i;c<=t;c++)c>i&&tn(e),dl(e,n.timeline[c]),ul(e,n.timeline[c]);let s=rt(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},fl=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;Go(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}=vr(t),p={...f,...Ke(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:jc(s,"accountViewedRegistry"),nextLineConfig:Gt(),saveSlots:Nc(n),overlayStack:[],variables:p,...Qc({loadedGlobalRuntime:i})},contexts:[si({pointer:u,projectData:t})]}},pl=({state:e})=>e.global.overlayStack||[],hl=({state:e})=>e.global.pendingEffects,li=({state:e})=>e.global.skipMode,ml=({state:e})=>e.global.autoMode,ui=({state:e})=>e.global.dialogueUIHidden,di=({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=te({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(d=>d.id===o),c=i.lines.slice(0,s+1),a=[],l={};for(let d of c){let u=d.actions||{};if(l=Ve([l,u]),!u.dialogue)continue;let f=l.dialogue||{},p="";f.character?.name!==void 0?p=f.character.name:f.characterId&&(p=e.projectData.resources?.characters?.[f.characterId]?.name||"");let h=kc({sectionId:n,lineId:d.id,content:u.dialogue.append===!0?f.content:u.dialogue.content,dialogueState:f,characterName:p});if(u.dialogue.append===!0&&a.length>0){a[a.length-1]={...a[a.length-1],content:h.content,text:h.text,characterId:h.characterId,character:h.character,characterName:h.characterName};continue}a.push(h)}return a},gl=({state:e})=>e.global.confirmDialog??null,mt=({state:e},{pointer:t}={})=>{let r=t??fe({state:e})?.pointer,n=Jc({state:e,pointer:r});return Xc({state:e,form:n.form,pointer:r})},yl=({state:e},{pointer:t}={})=>!!mt({state:e},{pointer:t}),we=({state:e},{pointer:t}={})=>{let r=mt({state:e},{pointer:t});if(r)return{source:qt,formId:r.id,formKey:r.key};let n=fi({state:e,pointer:t});return n?{source:en,resourceId:n}:null},bl=({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=te({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},Il=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},ln=({state:e},t)=>bl({state:e,registry:e.global.accountViewedRegistry},t),Al=({state:e},t)=>Il({registry:e.global.accountViewedRegistry},t),wl=({state:e})=>e.global.nextLineConfig,fi=({state:e,pointer:t}={})=>{let r=t??fe({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=te({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},pi=({state:e})=>!!fi({state:e}),El=({state:e})=>structuredClone(e),hi=({state:e})=>e.global.saveSlots,vl=({state:e},t)=>{let r=t?.slotId,n=Kt(r);return e.global.saveSlots[n]},un=({state:e})=>Je(e),xl=({state:e},t)=>Ee(e,t?.runtimeId),dn=({state:e})=>{let t={...e.global?.variables??{},...an(e)?.variables??{}};return Tt({variables:t,runtime:Je(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}},te=({state:e},t)=>{let{sectionId:r}=t;return rn(e.projectData,r).section},fn=({state:e})=>{let t=fe({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=te({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},mi=({state:e})=>{let{sectionId:t,lineId:r}=fe({state:e}).pointer,o=te({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 Ve(c)},Cl=({state:e})=>{let t=gi({state:e}),n=fn({state:e})?.actions??{},o=Ve([t??{},n]);return Cr(t??{},o??{})},Sl=({state:e},{sectionId:t})=>{let r=te({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},c=Ve([o,s]),a=Cr(o,c);n.push({id:i.id,changes:a,presentationState:c}),o=Sr(c)}return n},Rl=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=Sl({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},gi=({state:e})=>{let{sectionId:t,lineId:r}=fe({state:e}).pointer,o=te({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 Sr(Ve(c))},pn=({state:e},{slotsPerPage:t=6}={})=>{let o=((un({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[Kt(c)]||{};i.push({...a,slotId:c})}return{saveSlots:i}},_l=hi,Ol=pn,Ll=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},$l=({state:e},t={})=>{let r=mi({state:e}),n=gi({state:e}),o=fn({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}=rn(e.projectData,a),d=un({state:e}),u=t?.activePersistentAnimations??[],f=t?.restoredPersistentAnimations??[],p=mt({state:e}),h=pi({state:e}),g=dn({state:e}),{saveSlots:y}=pn({state:e}),b=Ll(e);return Uo({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:Si({state:e}),skipOnlyViewedLines:!d.skipUnseenText,isLineCompleted:d.isLineCompleted,skipTransitionsAndAnimations:!!d.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:di({state:e}),saveSlots:y,variables:g,runtime:d,activePersistentAnimations:u,restoredPersistentAnimations:f})},kl=({state:e},t)=>(e.global.confirmDialog=zc(t),e.global.pendingEffects.push({name:"render"}),e),Tl=({state:e})=>(e.global.confirmDialog&&(et(e),e.global.pendingEffects.push({name:"render"})),e),Dl=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Ae(e,"pushOverlay",t),e),Pl=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Ae(e,"popOverlay",void 0),e),Nl=({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),Vl=({state:e})=>(e.global.overlayStack=[],et(e),tt(e),e.global.pendingEffects.push({name:"render"}),Ae(e,"clearOverlays",void 0),e),jl=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"})},Jt=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,qc(e,r),tt(e);let n=we({state:e},{pointer:t}),o=n?.source===en,i=n?.source===qt;return n&&jl(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},yi=({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),gt=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Ml=({state:e})=>{let t=e.global.autoMode;return we({state:e})&&!t||(t?gt({state:e}):yi({state:e})),e},bi=({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),Be=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Fl=({state:e})=>{let t=li({state:e});return we({state:e})&&!t||(t?Be({state:e}):bi({state:e})),e},Xt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Ae(e,"showDialogueUI",void 0),e),Ii=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Ae(e,"hideDialogueUI",void 0),e),Ul=({state:e})=>(ui({state:e})?Xt({state:e}):Ii({state:e}),e),qe=(e,t,r)=>(ii(e,t,r),rl(e),e.global.pendingEffects.push({name:"render"}),e),yt=(e,t,r,n)=>{let o=ii(e,t,r);return e.global.pendingEffects.push({name:"render"}),Ae(e,n,{value:o}),e},Bl=({state:e},t)=>qe(e,"dialogueTextSpeed",t?.value),zl=({state:e},t)=>qe(e,"autoForwardDelay",t?.value),Wl=({state:e},t)=>qe(e,"skipUnseenText",t?.value),ql=({state:e},t)=>qe(e,"skipTransitionsAndAnimations",t?.value),Hl=({state:e},t)=>qe(e,"soundVolume",t?.value),Yl=({state:e},t)=>qe(e,"musicVolume",t?.value),Gl=({state:e},t)=>qe(e,"muteAll",t?.value),Kl=({state:e},t)=>yt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),Jl=({state:e})=>{let t=Ee(e,"saveLoadPagination")+1;return yt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},Xl=({state:e})=>{let t=Ee(e,"saveLoadPagination")-1;return yt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},Ql=({state:e},t)=>yt(e,"menuPage",t?.value,"setMenuPage"),Zl=({state:e},t)=>yt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),eu=({state:e})=>(e.global.pendingEffects=[],e),tu=({state:e},t)=>(e.global.pendingEffects.push(t),e),Ai=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!Zo(n),i=te({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&&!il(e,{queueRender:!o}))return e;e.global.autoMode&&gt({state:e}),r&&e.global.skipMode&&Be({state:e});let c=e.contexts?.[e.contexts.length-1];if(c){let a=rt(c),l=a.read;r||ze(e,{sectionId:l?.sectionId,lineId:l?.lineId}),c.rollback||We(c,{compatibilityAnchor:!0}),a.read={sectionId:t,lineId:s.id},r?c.rollback=ht({pointer:a.read}):cn(e,{sectionId:t,lineId:s.id})}return Jt(e,c?.pointers?.read,{screenTransition:n}),e},ru=({state:e},t)=>Ai(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),wi=e=>(e.global.accountViewedRegistry=Lc(e.global.accountViewedRegistry),e.global.accountViewedRegistry),hn=(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)}))}})},Ei=(e,t)=>{hn(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:[]}}])},nu=(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=te({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},ze=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;nu(e,wi(e),t)&&Ei(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},ou=({state:e},t)=>(ze(e,t),e.global.pendingEffects.push({name:"render"}),e),iu=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=wi(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),Ei(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},vi=({state:e},t)=>{let r=Dc(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},su=({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=Kt(r),s=D(e.contexts);s?.forEach(l=>{rt(l),ai(l.rollback),Vc(l.rollback)});let c={contexts:s},a={formatVersion:Ho,slotId:Ko(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},au=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=Kt(r),o=e.global.saveSlots[n];if(o){let i=Bc(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=Gt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,et(e),tt(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},cu=({state:e},t)=>{let{projectData:r}=t;Go(r),e.projectData=r;let n=r?.resources?.variables??{};return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables=Ke(e.global.variables,n)),e.contexts?.forEach(o=>{Object.prototype.hasOwnProperty.call(o??{},"variables")&&(o.variables=Ke(o.variables,n))}),et(e),tt(e),e.global.pendingEffects.push({name:"render"}),e},lu=({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&&!te({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=te({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=rt(o);return a.read={sectionId:i,lineId:n},Jt(e,a.read),e},uu=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return Xt({state:e}),e;let r=we({state:e});if(r?.source===en&&t?.bypassChoice!==!0||r?.source===qt&&t?._interactionSource!==qt)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&&ze(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=te({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&&!ln({state:e},{sectionId:o,lineId:d.id}))return Be({state:e}),e;if(s&&!s.rollback&&We(s,{compatibilityAnchor:!0}),s){let h=rt(s),g=h.read?.lineId;g&&o&&ze(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:d.id}}cn(e,{sectionId:o,lineId:d.id}),tn(e);let{activeInteraction:f}=Jt(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&&gt({state:e}),e.global.skipMode&&Be({state:e});return e},du=({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&&ze(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},fu=({state:e},t)=>Ai(e,{sectionId:t?.sectionId,screen:t?.screen}),pu=({state:e})=>{if(e.global.dialogueUIHidden)return Xt({state:e}),e;if(we({state:e}))return e;let t=fe({state:e})?.pointer,r=t?.sectionId,n=te({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&&!ln({state:e},{sectionId:r,lineId:a.id}))return Be({state:e}),e;if(o&&!o.rollback&&We(o,{compatibilityAnchor:!0}),o){let u=rt(o),f=u.read?.lineId;f&&r&&ze(e,{sectionId:r,lineId:f}),u.read={sectionId:r,lineId:a.id}}cn(e,{sectionId:r,lineId:a.id}),tn(e);let{activeInteraction:d}=Jt(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},mn=(e,t={})=>{let r=mt({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},hu=(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(_e(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return Dt(n,t.variableId),Pt(o,"set",t.variableId),{variableConfig:r,scope:n}},mu=(e,t)=>({id:e.id,key:e.key,valid:!0,values:D(t),fields:D(e.fields),fieldList:D(e.fieldList)}),gu=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&&ze(e,{sectionId:r,lineId:n})},yu=({state:e},t={})=>{let r=mn(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=ti(e,r.key),i=Ht(t.value),s=r.fields[n],c=nn(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},bu=({state:e},t={})=>{let r=mn(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=ti(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=nn(f,p);n.touched[u]=!0,h&&(i[u]=h),o[u]=ei(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}=hu(e,f),h=p==="context"?s.variables:e.global.variables,g=o[u];h[f.variableId]=Nt(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}),hn(e,a);let d=mu(r,o);return gu(e),delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:d}},Iu=({state:e},t={})=>{let r=mn(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"}},Au=({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(_e(f))throw new Error(`Cannot update computed variable: ${a}`);if(f?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);Dt(p,a),Pt(h,l,a),xr(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]=Nt(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}),hn(e,s),e.global.pendingEffects.push({name:"render"}),e},wu=e=>(t,r)=>e({state:t},r),Eu=e=>({variables:Tt({variables:{...e.global?.variables??{},...an(e)?.variables??{}},runtime:Je(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:Je(e)}),vu=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")},xu=(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")},Cu=(e,t)=>{vu(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(xu(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!ct(n.when,Eu(e)))){Object.entries(n.actions).forEach(([i,s])=>{xi(e,i,s)});return}}},Su={conditional:{replayLine:Cu},updateVariable:{recordSources:[on],replayLine:qo,replayRecorded:qo,persistInSaveSlot:!0},setNextLineConfig:{replayLine:wu(vi)}},Qt=e=>Su[e]??null,Ru=e=>Qt(e)?.persistInSaveSlot===!0,_u=(e,t)=>{let r=Qt(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},Ou=(e,t,r)=>{Qt(t)?.replayRecorded?.(e,r)},xi=(e,t,r)=>{Qt(t)?.replayLine?.(e,r)},Ci=({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}},Si=({state:e})=>Ci({state:e},{offset:-1})!==null,Lu=({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=We(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:ci(e,i)},$u=({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=We(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:ci(e,c)},Ri=e=>{let t=fl(e);return eo(t,{selectPendingEffects:hl,selectSkipMode:li,selectAutoMode:ml,selectIsChoiceVisible:pi,selectIsFormVisible:yl,selectActiveInteraction:we,selectActiveForm:mt,selectDialogueUIHidden:ui,selectDialogueHistory:di,selectConfirmDialog:gl,selectIsLineAccountViewed:ln,selectIsResourceAccountViewed:Al,selectNextLineConfig:wl,selectSystemState:El,selectSaveSlotMap:hi,selectSaveSlots:_l,selectSaveSlot:vl,selectRuntime:un,selectRuntimeValue:xl,selectAllVariables:dn,selectCurrentPointer:fe,selectSection:te,selectCurrentLine:fn,selectPresentationState:mi,selectPresentationChanges:Cl,selectSectionLineChanges:Rl,selectSaveSlotPage:pn,selectCurrentPageSlots:Ol,selectRenderState:$l,selectOverlayStack:pl,selectLineIdByOffset:Ci,selectCanRollback:Si,startAutoMode:yi,stopAutoMode:gt,toggleAutoMode:Ml,startSkipMode:bi,stopSkipMode:Be,toggleSkipMode:Fl,showDialogueUI:Xt,hideDialogueUI:Ii,toggleDialogueUI:Ul,setDialogueTextSpeed:Bl,setAutoForwardDelay:zl,setSkipUnseenText:Wl,setSkipTransitionsAndAnimations:ql,setSoundVolume:Hl,setMusicVolume:Yl,setMuteAll:Gl,setSaveLoadPagination:Kl,incrementSaveLoadPagination:Jl,decrementSaveLoadPagination:Xl,setMenuPage:Ql,setMenuEntryPoint:Zl,showConfirmDialog:kl,hideConfirmDialog:Tl,resetStoryAtSection:ru,clearPendingEffects:eu,appendPendingEffect:tu,beginRollbackActionBatch:cl,endRollbackActionBatch:ll,addViewedLine:ou,addViewedResource:iu,setNextLineConfig:vi,saveSlot:su,loadSlot:au,updateProjectData:cu,sectionTransition:fu,jumpToLine:lu,nextLine:uu,markLineCompleted:du,rollbackToLine:$u,rollbackByOffset:Lu,pushOverlay:Dl,popOverlay:Pl,replaceLastOverlay:Nl,clearOverlays:Vl,updateFormField:yu,submitForm:bu,cancelForm:Iu,updateVariable:Au,nextLineFromSystem:pu},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var ku="route-engine",Tu="projectPersistence";var Oi=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),Z=e=>Object.prototype.toString.call(e)==="[object Object]",_i="variables.",Du=(e={})=>{let t=Z(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!Z(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)}:!Z(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Pu=(e={})=>{let t=Z(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!Z(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)}:!Z(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Nu=(e,t)=>{let r=Pu(e),n=Du(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}},Li=(e={})=>{let t=Z(e)?e:{};return{saveSlots:Z(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:Z(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:Z(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:Z(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:Z(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Vu=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!Z(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(_i)?t.path.slice(_i.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}].`)})},ju=(e,t)=>{let r={};return Vu(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=Nu(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},gn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},Mu=e=>{let t=gn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Fu=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},Uu=({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}".`))}}),Bu=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.`))}})},bt=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=Li(l.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...Oi(),...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}".`))}})},zu=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}".`))}})},yn=(e={})=>{let{indexedDB:t,databaseName:r=ku,objectStoreName:n=Tu,namespace:o}=e,i=Fu(t),s=Mu(o),c=Uu({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let a=await Bu({databasePromise:c,objectStoreName:n,namespace:s});return{...Oi(),...Li(a)}},clear:async()=>zu({databasePromise:c,objectStoreName:n,namespace:s}),saveSlots:async a=>bt({databasePromise:c,objectStoreName:n,namespace:s,patch:{saveSlots:Z(a)?a:{}}}),saveGlobalDeviceVariables:async a=>bt({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:Z(a)?a:{}}}),saveGlobalAccountVariables:async a=>bt({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalAccountVariables:Z(a)?a:{}}}),saveGlobalRuntime:async a=>bt({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalRuntime:Z(a)?a:{}}}),applyScopedDataUpdates:async a=>bt({databasePromise:c,objectStoreName:n,namespace:s,patch:l=>ju(l,a)})}},Wu=yn;var qu=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Hu=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),$i="conditional",bn="form",Yu=new Set(["submitForm","cancelForm"]),It=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function In(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:c}=e,a=(I=new Map,C=Date.now())=>new Map(Array.from(I.entries()).filter(([,_])=>C<_.expiresAt).map(([_,M])=>[_,{animation:structuredClone(M.animation),startedAt:M.startedAt,expiresAt:M.expiresAt}])),l=(I=new Map)=>Array.from(I.values()).map(C=>structuredClone(C.animation)),d=(I=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,C])=>I<C.expiresAt))},u=()=>{for(;t.selectPendingEffects().length>0;){let I=[...t.selectPendingEffects()];t.clearPendingEffects();try{c(I)}catch(C){throw t.clearPendingEffects(),I.forEach(_=>{t.appendPendingEffect(_)}),C}}},f=({initialState:I,namespace:C})=>{t=Ri(I),r=0,n=gn(C),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 C=Date.now();d(C);let _=i.size>0,M=a(o,C),z=_?a(i,C):new Map,be={...t.selectRenderState({activePersistentAnimations:l(M),restoredPersistentAnimations:l(z)}),id:`render-${r}`};return s.set(be.id,{builtAt:C,persistentAnimationSessions:new Map([...z.entries(),...M.entries()]),usedRestoredPersistentAnimationSessions:_}),be},A=(I={})=>b(I),v=(I={})=>b(I),S=I=>{let C=typeof I?.id=="string"&&I.id.length>0?I.id:null,_=C?s.get(C):null;C&&s.delete(C);let M=new Map;_o(I?.animations).forEach(z=>{let ue=Ft(z);if(!ue)return;let be=_?.persistentAnimationSessions?.get(ue)??o.get(ue),wt=Math.max(0,Lo(z)),En=be?.startedAt??_?.builtAt??Date.now();M.set(ue,{animation:structuredClone(z),startedAt:En,expiresAt:En+wt})}),o=M,_?.usedRestoredPersistentAnimationSessions&&(i=new Map)},P=()=>t.selectSystemState(),w=()=>t.selectSaveSlotMap(),N=I=>t.selectSaveSlot(I),F=I=>t.selectSaveSlotPage(I),j=()=>t.selectSkipMode(),H=()=>t.selectAutoMode(),k=()=>t.selectRuntime(),U=()=>t.selectIsChoiceVisible(),q=()=>t.selectIsFormVisible(),K=()=>t.selectActiveInteraction(),ie=(I,C,_={})=>I!=="nextLine"||!It(C)?C:_.bypassChoice===!0?{...C,bypassChoice:!0}:_.interactionSource===bn?{...C,_interactionSource:bn}:C,re=(I,C)=>{if(!t[I])return;qu.has(I)&&(Hu.has(I)?i=a(o):i=new Map,o=new Map);let _=t[I](C);return u(),_},J=(I,C,_,M={})=>{if(I===$i){let z=R(_),ue=Rr({[I]:C},z);X(ue[I],_,M);return}re(I,C)},x=(I,C)=>{J(I,C)},R=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:C,..._}=I,M=t.selectAllVariables?t.selectAllVariables():void 0;return{..._,_event:C,variables:M,runtime:t.selectRuntime?t.selectRuntime():{}}},$=I=>{if(!It(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")},Y=(I,C,_)=>{if(!It(I))throw new Error(`conditional branch at index ${C} must be an object`);if(!It(I.actions))throw new Error(`conditional branch at index ${C} requires actions object`);if(!Object.prototype.hasOwnProperty.call(I,"when")&&C!==_-1)throw new Error("conditional else branch must be the last branch")},X=(I,C,_)=>{$(I);for(let M=0;M<I.branches.length;M+=1){let z=I.branches[M];Y(z,M,I.branches.length);let ue=R(C);if(!(Object.prototype.hasOwnProperty.call(z,"when")&&!ct(z.when,ue))){er(z.actions,C,_);return}}},B=(I,C)=>({...I??{},_form:C}),At=(I,C,_,M)=>{let z=re(I,C),ue=z?.submitted===!0&&z.valid===!0,be=z?.cancelled===!0;!ue&&!be||It(C.actions)&&er(C.actions,B(_,z.form),{...M,interactionSource:bn})},He=(I,C,_,M)=>{let z=R(_),be=Rr({[I]:C},z)[I];if(I===$i){X(be,_,M);return}let wt=ie(I,be,M);if(Yu.has(I)){At(I,wt,_,M);return}re(I,wt)},er=(I,C,_)=>{Object.entries(I).forEach(([M,z])=>{He(M,z,C,_)})},wn=(I,C,_={})=>{t.beginRollbackActionBatch({source:_.rollbackSource});try{er(I,C,_)}finally{t.endRollbackActionBatch({})}};return{init:f,handleAction:J,handleInternalAction:x,handleActions:wn,selectRenderState:A,prepareRenderState:v,commitRenderState:S,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:P,selectSaveSlotMap:w,selectSaveSlot:N,selectSaveSlotPage:F,selectSaveSlots:w,selectRuntime:k,selectIsChoiceVisible:U,selectIsFormVisible:q,selectActiveInteraction:K,handleLineActions:()=>{let I=t.selectCurrentLine();return I?.actions?(wn(I.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var An=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},Gu=80,Ti=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},Ku=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&Ti({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},Ju=({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),Zt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},Xu=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Qu=({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??Gu;r.getElapsed()>=c&&(r.setElapsed(0),Zt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},Zu=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},ed=({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),Zt(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},td=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},rd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},nd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},od=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},id=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},sd=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},ki={render:Ti,saveSlots:rd,saveGlobalDeviceVariables:nd,saveGlobalAccountVariables:od,saveGlobalRuntime:id,applyScopedDataUpdates:sd,handleLineActions:Ku,startAutoNextTimer:Ju,clearAutoNextTimer:Xu,startSkipNextTimer:Qu,clearSkipNextTimer:Zu,nextLineConfigTimer:ed,clearNextLineConfigTimer:td},ad=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Zt=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},cd=(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(!ad.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},ld=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:c})=>{let a=An(),l=An(),d=An(),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=yn({indexedDB:i,namespace:c??x?.getNamespace?.()}),u},v=x=>{f=f.catch(()=>{}).then(()=>{let R=A();return x(R)}).catch(R=>{b(R)})},S=x=>{let R=typeof x?.id=="string"&&x.id.length>0?x.id:null;y+=1,p=R,g=!1},P=()=>y,w=(x={})=>{if(x?.aborted===!0)return!1;let R=typeof x?.id=="string"&&x.id.length>0?x.id:null;return R?R!==p||R===h?!1:(h=R,!0):p!==null||g?!1:(g=!0,!0)},N=(x,R={})=>{if(x!=="renderComplete"||!w(R))return!1;let $=e();return Zt($,"markLineCompleted",{}),!0},F=new Set(["updateFormField","submitForm","cancelForm"]),j=x=>typeof x?.selectActiveInteraction=="function"?x.selectActiveInteraction():typeof x?.selectIsChoiceVisible=="function"&&x.selectIsChoiceVisible()?{source:"choice"}:null,H=x=>x?._formKey??x?.formKey,k=(x,R)=>H(x)===R?.formKey,U=(x,R)=>!x||typeof x!="object"||Array.isArray(x)||x._interactionSource!==R?.source?!1:R.source==="form"?k(x,R):!0,q=(x,R)=>!x||typeof x!="object"||Array.isArray(x)||R?.source!=="form"?!1:k(x,R),K=(x={},R)=>{let $=x?.actions;return R?.source==="form"?U(x,R)?!0:!$||typeof $!="object"||Array.isArray($)?!1:Object.entries($).some(([Y,X])=>F.has(Y)&&q(X,R)):U(x,R)?!0:!$||typeof $!="object"||Array.isArray($)?!1:Object.values($).some(Y=>U(Y,R))},ie=(x,R={})=>{if(!R?.actions)return!1;let $=j(x);return!$||$.source==="choice"?!1:!K(R,$)},re=({preprocessPayload:x,onEvent:R}={})=>async($,Y={})=>{let X=e();if(ie(X,Y))return R?.($,Y);let B=await x?.($,Y)??Y;if(ie(X,B))return R?.($,B);if(N($,B),B?.actions){let At=B?._event?{_event:B._event}:B?.event?{_event:B.event}:void 0,He;B?.bypassChoice===!0?He={bypassChoice:!0}:B?._interactionSource&&(He={interactionSource:B._interactionSource}),He?X.handleActions(B.actions,At,He):X.handleActions(B.actions,At)}return R?.($,B)},J=x=>{let R=e(),$=cd(x);$.forEach(X=>{if(!ki[X.name]&&!n)throw new Error(`Unhandled pending effect "${X.name}".`)});let Y={engine:R,routeGraphics:t,ticker:r,autoTimer:a,skipTimer:l,nextLineConfigTimerState:d,trackRenderDispatch:S,getRenderDispatchCount:P,enqueuePersistenceWrite:v};for(let X of $){let B=ki[X.name];if(B){B(Y,X.payload);continue}n(X,Y)}};return J.handleRouteGraphicsEvent=N,J.createRouteGraphicsEventHandler=re,J},ud=ld;var dd=(e,t={})=>{let{resources:r={}}=t;return Zr(e,r)};var $f=In;export{Lr as DEFAULT_VISUAL_LAYER,Xe as RENDER_LAYER,ve as VISUAL_LAYER,ud as createEffectsHandler,Wu as createIndexedDbPersistence,$f as default,Fs as resolveComputedVariables,dd as resolveLayoutReferences};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "route-engine-js",
3
- "version": "1.21.0",
3
+ "version": "1.22.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",