route-engine-js 1.14.2 → 1.14.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var ui=Object.defineProperty;var fi=(e,t)=>{for(var r in t)ui(e,r,{get:t[r],enumerable:!0})};var fn=Symbol.for("immer-nothing"),sn=Symbol.for("immer-draftable"),ee=Symbol.for("immer-state");function ie(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Ne=Object.getPrototypeOf;function te(e){return!!e&&!!e[ee]}function Se(e){return e?dn(e)||Array.isArray(e)||!!e[sn]||!!e.constructor?.[sn]||gt(e)||yt(e):!1}var di=Object.prototype.constructor.toString();function dn(e){if(!e||typeof e!="object")return!1;let t=Ne(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 dt(e,t){mt(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function mt(e){let t=e[ee];return t?t.type_:Array.isArray(e)?1:gt(e)?2:yt(e)?3:0}function Yt(e,t){return mt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function pn(e,t,r){let n=mt(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 gt(e){return e instanceof Map}function yt(e){return e instanceof Set}function Ce(e){return e.copy_||e.base_}function Kt(e,t){if(gt(e))return new Map(e);if(yt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=dn(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[ee];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],a=n[s];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(n[s]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[s]})}return Object.create(Ne(e),n)}else{let n=Ne(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function Qt(e,t=!1){return bt(e)||te(e)||!Se(e)||(mt(e)>1&&(e.set=e.add=e.clear=e.delete=hi),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>Qt(n,!0))),e}function hi(){ie(2)}function bt(e){return Object.isFrozen(e)}var mi={};function _e(e){let t=mi[e];return t||ie(0,e),t}var He;function hn(){return He}function gi(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function an(e,t){t&&(_e("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Ht(e){Jt(e),e.drafts_.forEach(yi),e.drafts_=null}function Jt(e){e===He&&(He=e.parent_)}function cn(e){return He=gi(He,e)}function yi(e){let t=e[ee];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function ln(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[ee].modified_&&(Ht(t),ie(4)),Se(e)&&(e=pt(t,e),t.parent_||ht(t,e)),t.patches_&&_e("Patches").generateReplacementPatches_(r[ee].base_,e,t.patches_,t.inversePatches_)):e=pt(t,r,[]),Ht(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==fn?e:void 0}function pt(e,t,r){if(bt(t))return t;let n=t[ee];if(!n)return dt(t,(o,i)=>un(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return ht(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),dt(i,(a,c)=>un(e,n,o,a,c,r,s)),ht(e,o,!1),r&&e.patches_&&_e("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function un(e,t,r,n,o,i,s){if(te(o)){let a=i&&t&&t.type_!==3&&!Yt(t.assigned_,n)?i.concat(n):void 0,c=pt(e,o,a);if(pn(r,n,c),te(c))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(Se(o)&&!bt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;pt(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&ht(e,o)}}function ht(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Qt(t,r)}function bi(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:hn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=Zt;r&&(o=[n],i=Je);let{revoke:s,proxy:a}=Proxy.revocable(o,i);return n.draft_=a,n.revoke_=s,a}var Zt={get(e,t){if(t===ee)return e;let r=Ce(e);if(!Yt(r,t))return Ii(e,r,t);let n=r[t];return e.finalized_||!Se(n)?n:n===Wt(e.base_,t)?(qt(e),e.copy_[t]=Xt(n,e)):n},has(e,t){return t in Ce(e)},ownKeys(e){return Reflect.ownKeys(Ce(e))},set(e,t,r){let n=mn(Ce(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=Wt(Ce(e),t),i=o?.[ee];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(pi(r,o)&&(r!==void 0||Yt(e.base_,t)))return!0;qt(e),Gt(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 Wt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,qt(e),Gt(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Ce(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){ie(11)},getPrototypeOf(e){return Ne(e.base_)},setPrototypeOf(){ie(12)}},Je={};dt(Zt,(e,t)=>{Je[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Je.deleteProperty=function(e,t){return Je.set.call(this,e,t,void 0)};Je.set=function(e,t,r){return Zt.set.call(this,e[0],t,r,e[0])};function Wt(e,t){let r=e[ee];return(r?Ce(r):e)[t]}function Ii(e,t,r){let n=mn(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function mn(e,t){if(!(t in e))return;let r=Ne(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=Ne(r)}}function Gt(e){e.modified_||(e.modified_=!0,e.parent_&&Gt(e.parent_))}function qt(e){e.copy_||(e.copy_=Kt(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(c=i,...l){return s.produce(c,u=>r.call(this,u,...l))}}typeof r!="function"&&ie(6),n!==void 0&&typeof n!="function"&&ie(7);let o;if(Se(t)){let i=cn(this),s=Xt(t,void 0),a=!0;try{o=r(s),a=!1}finally{a?Ht(i):Jt(i)}return an(i,n),ln(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===fn&&(o=void 0),this.autoFreeze_&&Qt(o,!0),n){let i=[],s=[];_e("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else ie(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...a)=>this.produceWithPatches(s,c=>t(c,...a));let n,o;return[this.produce(t,r,(s,a)=>{n=s,o=a}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Se(e)||ie(8),te(e)&&(e=$e(e));let t=cn(this),r=Xt(e,void 0);return r[ee].isManual_=!0,Jt(t),r}finishDraft(e,t){let r=e&&e[ee];(!r||!r.isManual_)&&ie(9);let{scope_:n}=r;return an(n,t),ln(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=_e("Patches").applyPatches_;return te(e)?n(e,t):this.produce(e,o=>n(o,t))}};function Xt(e,t){let r=gt(e)?_e("MapSet").proxyMap_(e,t):yt(e)?_e("MapSet").proxySet_(e,t):bi(e,t);return(t?t.scope_:hn()).drafts_.push(r),r}function $e(e){return te(e)||ie(10,e),gn(e)}function gn(e){if(!Se(e)||bt(e))return e;let t=e[ee],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=Kt(e,t.scope_.immer_.useStrictShallowCopy_)}else r=Kt(e,!0);return dt(r,(n,o)=>{pn(r,n,gn(o))}),t&&(t.finalized_=!1),r}var re=new wi,er=re.produce,yu=re.produceWithPatches.bind(re),bu=re.setAutoFreeze.bind(re),Iu=re.setUseStrictShallowCopy.bind(re),wu=re.applyPatches.bind(re),Au=re.createDraft.bind(re),vu=re.finishDraft.bind(re);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},Ve={NOT:0};var v=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},Q=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var tr=e=>{if(!e||e.trim()==="")throw new v("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new v(`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 v(`Incomplete comparison expression - missing right operand (got: '${e}')`)},yn=e=>{if(e.trim().endsWith(" in"))throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new v(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new v(`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 v(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new v(`Invalid loop syntax (got: '$for ${e}')`)}};var bn=(e,t,r=!1)=>{if(t===null)return new Q(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new Q(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new Q(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new Q(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},In=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new Q(`Unknown function '${e}' (${r})`)};var Ai=(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=k(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},k=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return Y(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return Y(e.path,r,n);if(e.type===m.INTERPOLATION)return Ei(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return An(e,t,r,n);case m.BINARY:return vn(e,t,r,n);case m.UNARY:return En(e,t,r,n);case m.CONDITIONAL:return Ci(e,t,r,n);case m.LOOP:return Ri(e,t,r,n);case m.OBJECT:return ki(e,t,r,n);case m.ARRAY:return Pi(e,t,r,n);case m.PARTIAL:return Ti(e,t,r,n);case m.PATH_REFERENCE:return Di(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},wn=new Map,vi=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 a=s.slice(1,-1);t.push({type:"property",value:a})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},Y=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=wn.get(e);if(!n){let i=[],s="",a=0;for(let c=0;c<e.length;c++){let l=e[c];l==="["?(a++,s+=l):l==="]"?(a--,s+=l):l==="."&&a===0?s&&(i.push(s),s=""):s+=l}s&&i.push(s),n=[];for(let c of i){let l=vi(c.trim());n.push(...l)}wn.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},Ei=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=k(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},An=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw In(e.name,o);let s=e.args.map(a=>k(a,t,r,n));return i(...s)},be=(e,t,r,n)=>{if(e.var&&!e.type)return Y(e.var,r,n);switch(e.type){case m.VARIABLE:return Y(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return vn(e,t,r,n);case m.UNARY:return En(e,t,r,n);case m.FUNCTION:return An(e,t,r,n);default:return k(e,t,r,n)}},vn=(e,t,r,n)=>{if(e.op===O.AND||e.op===O.OR){let s=be(e.left,t,r,n),a=be(e.right,t,r,n);switch(e.op){case O.AND:return s&&a;case O.OR:return s||a}}let o=k(e.left,t,r,n),i=k(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 Q(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case O.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new Q(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},En=(e,t,r,n)=>{let o=e.op===Ve.NOT?be(e.operand,t,r,n):k(e.operand,t,r,n);if(e.op===Ve.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},xi=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(Y(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?k(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)a[l]=u.value;else if(u.type===m.VARIABLE)a[l]=Y(u.path,r,n);else if(u.type===m.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===m.VARIABLE){let p=Y(d.path,r,n);f.push(p!=null?String(p):"")}else{let p=k(d,t,r,n);f.push(p!=null?String(p):"")}a[l]=f.join("")}else a[l]=k(u,t,r,n)}return a}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?k(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)a[l]=u.value;else if(u.type===m.VARIABLE)a[l]=Y(u.path,r,n);else if(u.type===m.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===m.VARIABLE){let p=Y(d.path,r,n);f.push(p!=null?String(p):"")}else{let p=k(d,t,r,n);f.push(p!=null?String(p):"")}a[l]=f.join("")}else a[l]=k(u,t,r,n)}return a}}}return null},Ci=(e,t,r,n)=>{let o=xi(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||be(s,t,r,n))return k(e.bodies[i],t,r,n)}return xn},Si=(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 c of i.properties)if(c.parsedKey)return null;let a=[];for(let c=0;c<t.length;c++){let l=t[c];if(l[s]){let u={};for(let f of i.properties){let d=f.key,p=f.value;if(p.type===m.LITERAL)u[d]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)u[d]=l;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);u[d]=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 I=y.path;if(I===n)h.push(l!=null?String(l):"");else if(I.startsWith(n+".")){let A=I.substring(n.length+1),x=l[A];h.push(x!=null?String(x):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[d]=h.join("")}else return null}a.push(u)}}return a}}}return null},_i=(e,t)=>{let r=e.body,n=e.itemVar,o=Si(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let a of r.properties)if(a.parsedKey)return null;let i=[],s=!0;for(let a of r.properties){let c=a.key,l=a.value;if(l.type===m.LITERAL)i.push({key:c,type:"literal",value:l.value});else if(l.type===m.VARIABLE){let u=l.path;if(u===n)i.push({key:c,type:"item"});else if(u.startsWith(n+".")){let f=u.substring(n.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(l.type===m.INTERPOLATION&&l.parts.length===1){let u=l.parts[0];if(u.type===m.VARIABLE){let f=u.path;if(f===n)i.push({key:c,type:"item_string"});else if(f.startsWith(n+".")){let d=f.substring(n.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let a=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let l=t[c];a[c]={id:l.id,title:l.title!=null?String(l.title):"",completed:l.completed}}else for(let c=0;c<t.length;c++){let l=t[c],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=l;else if(f.type==="prop")u[f.key]=l[f.prop];else if(f.type==="item_string")u[f.key]=l!=null?String(l):"";else if(f.type==="prop_string"){let d=l[f.prop];u[f.key]=d!=null?String(d):""}a[c]=u}return a}}return null},$i=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let a=e.itemVar,c=e.indexVar;for(let l=0;l<o.length;l++){let u=o[l],f={},d={...n,[a]:u,...c&&{[c]:l}};d.__paths__||(d.__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(".")))}d.__paths__={...d.__paths__,[a]:`${p}[${l}]`,...c&&{[c]:l}};for(let h of s.properties){let g=h.parsedKey?k(h.parsedKey,t,r,d):h.key,y=h.value;if(y.type===m.LITERAL)f[g]=y.value;else if(y.type===m.VARIABLE){let I=y.path;if(I===a)f[g]=u;else if(I===c)f[g]=l;else if(I.startsWith(a+".")){let A=I.substring(a.length+1);!A.includes(".")&&!A.includes("[")?f[g]=u[A]:f[g]=Y(I,r,{...n,[a]:u,...c&&{[c]:l}})}else f[g]=Y(I,r,{...n,[a]:u,...c&&{[c]:l}})}else if(y.type===m.INTERPOLATION){let I=[];for(let A of y.parts)if(typeof A=="string")I.push(A);else if(A.type===m.VARIABLE){let x=A.path,b;if(x===a)b=u;else if(x===c)b=l;else if(x.startsWith(a+".")){let R=x.substring(a.length+1);!R.includes(".")&&!R.includes("[")?b=u[R]:b=Y(x,r,{...n,[a]:u,...c&&{[c]:l}})}else b=Y(x,r,{...n,[a]:u,...c&&{[c]:l}});I.push(b!=null?String(b):"")}else{let x={...n,[a]:u,...c&&{[c]:l}},b=k(A,t,r,x);I.push(b!=null?String(b):"")}f[g]=I.join("")}else{let I={...n,[a]:u,...c&&{[c]:l}};f[g]=k(y,t,r,I)}}i.push(f)}return i}return null},Oi=(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 a=s.properties[0],c=s.properties[1];if(a.key==="id"&&a.value.type===m.VARIABLE&&a.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===m.CONDITIONAL){let l=[];for(let u=0;u<t.length;u++){let f=t[u];if(f.visible){let d={id:f.id};f.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${f.name}`):(d.highlight=!1,d.message=f.name),l.push(d)}}return l}}}}return null},Ri=(e,t,r,n)=>{let o=k(e.iterable,t,r,n);if(!Array.isArray(o)){let l,u=!1;if(e.iterable.type===m.FUNCTION){u=!0;let d=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}(${d})`}else l=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw bn(f,o,u)}if(!e.indexVar){let l=Oi(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=_i(e,o);if(l!==null)return l}let i=$i(e,t,r,n,o);if(i!==null)return i;let s=[],a=e.iterable.path||"";if(n&&n.__paths__&&a){let l=a.split("."),u=l[0];u in n.__paths__&&(a=n.__paths__[u],l.length>1&&(a+="."+l.slice(1).join(".")))}let c=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(l=>l.type===m.OBJECT&&l.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let l=0;l<o.length;l++){let u=e.indexVar?{...n,[e.itemVar]:o[l],[e.indexVar]:l}:{...n,[e.itemVar]:o[l]};u.__paths__||(u.__paths__=n.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${a}[${l}]`},e.indexVar&&(u.__paths__[e.indexVar]=l);let f=k(e.body,t,r,u);if(Array.isArray(f)&&f.length===1&&!c){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},Li=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?k(o.parsedKey,t,r,n):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let a={},c={},l=!0;for(let u of s.properties){let f=u.parsedKey?k(u.parsedKey,t,r,n):u.key,d=u.value;if(d.type===m.LITERAL)c[f]=d.value;else if(d.type===m.VARIABLE)c[f]=Y(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=Y(h.path,r,n);p.push(g!=null?String(g):"")}else{l=!1;break}if(!l)break;c[f]=p.join("")}else if(d.type===m.OBJECT&&d.properties.length<=5){let p={};for(let h of d.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]=Y(y.path,r,n);else if(y.type===m.INTERPOLATION){let I=[];for(let A of y.parts)if(typeof A=="string")I.push(A);else if(A.type===m.VARIABLE){let x=Y(A.path,r,n);I.push(x!=null?String(x):"")}else{l=!1;break}if(!l)break;p[g]=I.join("")}else{l=!1;break}}if(!l)break;c[f]=p}else{l=!1;break}}if(l)return a[i]=c,a}}return null},ki=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!be(e.whenCondition,o,r,n))return;let i=Li(e,t,r,n);if(i!==null)return i;if(e.fast){let l={};for(let u of e.properties){let f=u.parsedKey?k(u.parsedKey,t,r,n):u.key,d=u.value;if(d.type===m.LITERAL)l[f]=d.value;else if(d.type===m.VARIABLE)l[f]=Y(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=Y(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=k(h,t,r,n);p.push(g!=null?String(g):"")}l[f]=p.join("")}else l[f]=k(d,t,r,n)}return l}let s={},a=null,c=!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 ")){c=!0;break}for(let l of e.properties)if(l.key.startsWith("$if ")||l.key.match(/^\$if\s+\w+.*:?$/)){let u=k(l.value,t,r,n);if(!c&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(l.key.startsWith("$for ")){if(e.properties.length===1)return k(l.value,t,r,n)}else{let u=l.value;if(u&&u.type===m.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=k(f.value,t,r,n);d!==void 0&&(s[l.key]=d)}else{let d=k(l.value,t,r,n);d!==void 0&&(s[l.key]=d)}}else{let f=l.parsedKey?k(l.parsedKey,t,r,n):l.key,d=k(l.value,t,r,n);d!==void 0&&(s[f]=d)}}return s},xn={},Pi=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=k(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=k(i,t,r,n);s!==xn&&s!==void 0&&o.push(s)}return o},Ti=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,a=t.partials||{},c=t.functions||t;if(s&&!be(s,c,r,n))return;if(!a[o])throw new Q(`Partial '${o}' is not defined`);let l=n._partialStack||[];if(l.includes(o))throw new Q(`Circular partial reference detected: ${o}`);let u=a[o],f=r,d={...n,_partialStack:[...l,o]};if(n){f={...r};for(let p of Object.keys(n))p.startsWith("_")||(f[p]=n[p])}if(i){let p=k(i,t,r,n);f={...f,...p}}return k(u,t,f,d)},Di=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],a=i.slice(1);if(!n||!(s in n))throw new Q(`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 Q(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=n.__paths__[s];if(typeof c=="number"){if(a.length>0)throw new Q(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return a.length>0&&(c+="."+a.join(".")),c};var rr=Ai;var Ni=/\$\{([^}]*)\}/g,Vi=/#\{([^}]*)\}/g,Sn=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=ji(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},ji=(e,t={})=>e.trim()?Mi(e).map(n=>Fi(n.trim(),t)):[],Mi=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let a=e[s],c=s>0?e[s-1]:"";!o&&(a==='"'||a==="'")?(o=!0,i=a,r+=a):o&&a===i&&c!=="\\"?(o=!1,i="",r+=a):!o&&a==="("?(n++,r+=a):!o&&a===")"?(n--,r+=a):!o&&a===","&&n===0?(t.push(r),r=""):r+=a}return r&&t.push(r),t},Fi=(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=Sn(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:a,type:c}of o){let l=0;for(;l<n.length;){let u=Oe(n.substring(l),a);if(u===-1)break;let f=l+u;f>i&&(i=f,s={op:a,type:c}),l=f+a.length}}if(i!==-1)try{return K(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},_n=/^\w+\(.*\)$/,Ui=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Bi=e=>{if(!(!e||e.trim()===""||_n.test(e))&&Ui.test(e))throw e.includes("?")&&e.includes(":")?new v(`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 v(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new v(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Cn=e=>{let t=e.trim();if(_n.test(t))throw new v(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new v(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new v(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new v(`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 v(`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}},Ge=(e,t={})=>{let r=e.trim();Bi(r);let n=Sn(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}},nr=(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,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\(#\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(Ni)],i=[...r.matchAll(Vi)],s=[...o.map(l=>({match:l,type:"variable"})),...i.map(l=>({match:l,type:"pathref"}))].sort((l,u)=>l.match.index-u.match.index);if(s.length===0){let l=r;for(let u=0;u<n.length;u++)l=l.replace(`__ESCAPED_${u}__`,n[u]);return{type:m.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:l,type:u}=s[0];try{return u==="variable"?Ge(l[1],t):Cn(l[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw f}}let a=[],c=0;for(let{match:l,type:u}of s){let[f,d]=l,p=l.index;if(p>c){let h=r.substring(c,p);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&a.push(h)}try{let h;u==="variable"?h=Ge(d.trim(),t):h=Cn(d.trim()),a.push(h)}catch(h){if(h.message==="Invalid array index syntax")a.push(f);else throw h}c=p+f.length}if(c<r.length){let l=r.substring(c);for(let u=0;u<n.length;u++)l=l.replace(`__ESCAPED_${u}__`,n[u]);l&&a.push(l)}return{type:m.INTERPOLATION,parts:a}};var sr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Rn=e=>Object.keys(e),G=e=>e.join("."),Ie=(e,t,r)=>{let n=Rn(e).filter(o=>!t.has(o));if(n.length>0)throw new v(`Unexpected key '${n[0]}' in condition JSON at '${G(r)}'`)},we=(e,t)=>typeof e=="string"?nr(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Wi(e,t):qi(e,t):{type:m.LITERAL,value:e},zi=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new v("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new v("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new v("Empty $each body not allowed");if(r.$partial!==void 0)throw new v("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${n}`]:r}},Wi=(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 c=zi(i),l=Object.keys(c);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let u=On(l[0],c[l[0]],t,!0);r.push(u),n=!0;continue}}catch(c){throw c instanceof v?c:new v(c.message)}let a=Object.keys(i);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let c=On(a[0],i[a[0]],t);r.push(c),n=!0;continue}}let s=we(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}},qi=(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 v("$partial value must be a string");if(e.$partial.trim()==="")throw new v("$partial value cannot be an empty string");let c=["$if","$elif","$else","$for"],l=[];for(let[I]of i)for(let A of c)if(I===A||I.startsWith(A+" ")||I.startsWith(A+"#")){l.push(A);break}if(l.length>0)throw new v(`Cannot use $partial with ${l.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...d}=e,p={},h=!1;for(let[I,A]of Object.entries(d)){let x=I;(I.startsWith("\\$")||I.startsWith("$$"))&&(x=I.slice(1)),p[x]=A,h=!0}let g=null;if(h&&(g=we(p,t),g.type===m.OBJECT)){let I=!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){I=!0;break}I&&(g.fast=!1)}let y={type:m.PARTIAL,name:u,data:g};return f!==void 0&&(y.whenCondition=$n(f,t)),y}for(let[c,l]of i)if(c==="$when"){if(o!==null)throw new v("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new v("Missing condition expression after '$when'");o=$n(l,t),n=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new v("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[c,l]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new v("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=Yi(i,s,t);r.push({key:c,value:u.node}),n=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(c)){let u=c.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new v(`$for loops must be inside arrays - use '- $for${f} item in items:' instead of '$for${f} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(c.startsWith("$elif ")||c.startsWith("$else"))throw new v(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new v("Missing condition expression after '$if'");{let u=we(l,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 f=nr(c,t),d={key:c,value:u};(f.type!==m.LITERAL||f.value!==c)&&(d.parsedKey=f),r.push(d),s++}}}let a={type:m.OBJECT,properties:r,fast:!n};return o&&(a.whenCondition=o),a},Yi=(e,t,r={})=>{let n=[],o=[],i=t,[s,a]=e[i],c=null,l;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=f[1],l=f[2];else throw new v(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());tr(l);let u=K(l,r);for(n.push(u),o.push(we(a,r)),i++;i<e.length;){let[f,d]=e[i],p=!1,h;if(c?f.startsWith(`$elif#${c} `)?(h=f.substring(`$elif#${c} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f===`$else#${c}`||f===`$else#${c}:`)&&(p=!0,h=null):f.startsWith("$elif ")?(h=f.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f==="$else"||f==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{tr(h);let g=K(h,r);n.push(g)}if(o.push(we(d,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:c},nextIndex:i}},or={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},ir={all:O.AND,any:O.OR},Ki=new Set(["var","literal","call","not",...Object.keys(or),...Object.keys(ir)]),Hi=(e,t,r)=>{if(!Array.isArray(e))throw new v(`Condition JSON operator '${t}' at '${G(r)}' requires an array`);if(e.length!==2)throw new v(`Condition JSON operator '${t}' at '${G(r)}' requires exactly 2 operands`);return e},Ji=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new v(`Condition JSON operator '${t}' at '${G(o)}' requires an array`);if(e.length===0)throw new v(`Condition JSON operator '${t}' at '${G(o)}' requires at least 1 condition`);return e.map((s,a)=>de(s,n,[...o,a])).reduce((s,a)=>({type:m.BINARY,op:r,left:s,right:a}))},Gi=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],Ie(e,new Set(["call","args"]),r);else if(sr(e.call))n=e.call.name,o=e.call.args??[],Ie(e,new Set(["call"]),r),Ie(e.call,new Set(["name","args"]),[...r,"call"]);else throw new v(`Condition JSON call at '${G(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new v(`Condition JSON call at '${G(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new v(`Invalid condition JSON function name '${n}' at '${G(r)}'`);if(!Array.isArray(o))throw new v(`Condition JSON call '${n}' at '${G(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>de(i,t,[...r,"args",s]))}},de=(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 v(`Condition JSON array at '${G(r)}' must be wrapped in an operator or { literal: [...] }`);if(!sr(e))throw new v(`Invalid condition JSON value at '${G(r)}'`);let n=Rn(e);if(n.length===0)throw new v(`Condition JSON object at '${G(r)}' must contain an operator`);let o=n.filter(s=>Ki.has(s));if(o.length===0)throw new v(`Unknown condition JSON operator '${n[0]}' at '${G(r)}'`);if(o.length>1)throw new v(`Condition JSON at '${G(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(Ie(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new v(`Condition JSON var at '${G(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return Ie(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return Gi(e,t,r);if(i==="not")return Ie(e,new Set(["not"]),r),{type:m.UNARY,op:Ve.NOT,operand:de(e.not,t,[...r,"not"])};if(i in ir)return Ie(e,new Set([i]),r),Ji(e[i],i,ir[i],t,[...r,i]);if(i in or){Ie(e,new Set([i]),r);let s=Hi(e[i],i,[...r,i]);return{type:m.BINARY,op:or[i],left:de(s[0],t,[...r,i,0]),right:de(s[1],t,[...r,i,1])}}throw new v(`Unknown condition JSON operator '${i}' at '${G(r)}'`)},$n=(e,t={})=>{if(e==null)throw new v("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new v("Empty condition expression after '$when'");return K(e,t)}return sr(e)||Array.isArray(e)?de(e,t):{type:m.LITERAL,value:e}},K=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let l=e.slice(1,-1),u=0,f=!0;for(let d=0;d<l.length;d++)if(l[d]==="("?u++:l[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return K(l,t)}let r=Oe(e,"||");if(r!==-1)return{type:m.BINARY,op:O.OR,left:K(e.substring(0,r).trim(),t),right:K(e.substring(r+2).trim(),t)};let n=Oe(e,"&&");if(n!==-1)return{type:m.BINARY,op:O.AND,left:K(e.substring(0,n).trim(),t),right:K(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:u}of o){let f=Oe(e,l);if(f!==-1)return{type:m.BINARY,op:u,left:K(e.substring(0,f).trim(),t),right:K(e.substring(f+l.length).trim(),t)}}let i=-1,s=null,a=[{op:" + ",type:O.ADD},{op:" - ",type:O.SUBTRACT}];for(let{op:l,type:u}of a){let f=0;for(;f<e.length;){let d=Oe(e.substring(f),l);if(d===-1)break;let p=f+d;p>i&&(i=p,s={op:l,type:u}),f=p+l.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:K(e.substring(0,i).trim(),t),right:K(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let l of c)if(Oe(e,l)!==-1)throw new v(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:m.UNARY,op:Ve.NOT,operand:K(e.substring(1).trim(),t)}:Ln(e,t)},Oe=(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},Xi=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}},Ln=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return Ge(r,t);let o=Xi(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return Ge(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Qi=(e,t=!1)=>{let r=t?"$each":"$for";try{yn(e)}catch(n){if(n instanceof v&&t){let o=n.message.replace(/\$for/g,"$each");throw new v(o.replace("Parse Error: ",""))}throw n}},On=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new v(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],a=i[2].trim();Qi(a,n);let c=a.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let y=n?"$each":"$for";throw new v(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${a}')`)}let l=c[1].trim(),u=c[2].trim(),f,d=null;if(l.includes(",")){let y=l.split(",").map(I=>I.trim());if(y.length!==2)throw new v(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);f=y[0],d=y[1]}else f=l;let p=["this","undefined","null","true","false"];if(p.includes(f))throw new v(`Reserved variable name: ${f}`);if(d&&p.includes(d))throw new v(`Reserved variable name: ${d}`);let h=Ln(u,r),g=we(t,r);return{type:m.LOOP,itemVar:f,indexVar:d,iterable:h,body:g,flatten:s!=="nested"}};var Zi=(e,t={})=>{let{functions:r={}}=t;return we(e,r)},It=Zi;var Xe={};fi(Xe,{now:()=>es});var es=()=>Date.now();var ts=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...Xe,...n},s=It(e,{functions:i}),a={};for(let[c,l]of Object.entries(o))a[c]=It(l,{functions:i});return rr(s,t,{functions:i,partials:a})},Z=ts;var rs=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",ns=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,os=(e,t)=>{if(rs(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new v("Empty condition expression");return K(e,t)}return de(e,t)},is=(e,t={},r={})=>{let n=ns(r),o={...Xe,...n},i=os(e,o);return!!be(i,{functions:o,partials:{}},t,{})},ar=is;var Ze=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return ar(e,t)},Tn=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:a=c=>c}=r;for(let[c,l]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>l(s(n),...u):i[c]=(...u)=>{let f;return n=er(n,p=>{let h=l(a(p),...u);f=h!==void 0&&!te(h)?h:void 0}),f});return{...o,...i}},vt=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return er(n,i=>{o.forEach(s=>{t.forEach(a=>{a(i,s)})})})};var ss=(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{}}},ae=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),Qe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Dn=e=>{let t=te(e)?$e(e):e;return structuredClone(t)},Ae=e=>ae(e,"computed"),je=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Ae(t[r]))),as=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),cr=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},cs=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=as(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 cr(s,i)}return n==="runtime"?cr(t.runtime,r.slice(1)):cr(t,r)},ls=(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`)},us=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},se=(e,t,r,n)=>(ls(e,t,n),t.map(o=>At(o,r))),oe=(e,t,r,n)=>{let o=se(e,t,r,n);return o.forEach(i=>us(e,i)),o},fs=(e,t,r)=>{switch(e){case"var":return cs(t,r);case"add":{let[n,o]=oe(e,t,r,2);return n+o}case"sub":{let[n,o]=oe(e,t,r,2);return n-o}case"mul":{let[n,o]=oe(e,t,r,2);return n*o}case"div":{let[n,o]=oe(e,t,r,2);return n/o}case"mod":{let[n,o]=oe(e,t,r,2);return n%o}case"neg":{let[n]=oe(e,t,r,1);return-n}case"round":{let[n]=oe(e,t,r,1);return Math.round(n)}case"floor":{let[n]=oe(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=oe(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=oe(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=oe(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=oe(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=se(e,t,r,2);return n==o}case"neq":{let[n,o]=se(e,t,r,2);return n!=o}case"gt":{let[n,o]=se(e,t,r,2);return n>o}case"gte":{let[n,o]=se(e,t,r,2);return n>=o}case"lt":{let[n,o]=se(e,t,r,2);return n<o}case"lte":{let[n,o]=se(e,t,r,2);return n<=o}case"in":{let[n,o]=se(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return kn(e,t),t.every(n=>!!At(n,r));case"or":case"any":return kn(e,t),t.some(n=>!!At(n,r));case"not":{let[n]=se(e,t,r,1);return!n}case"length":{let[n]=se(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:Qe(n)?Object.keys(n).length:0}case"includes":{let[n,o]=se(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return Dn(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},At=(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 fs(n,o,t)},ds=(e,t={})=>Ze(e,{variables:t.variables,runtime:t.runtime}),ps=(e,t)=>{if(!Qe(e))throw new Error(`${t} must be an object`);let r=ae(e,"expr"),n=ae(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},lr=(e,t,r)=>(ps(e,t),ae(e,"value")?Dn(e.value):At(e.expr,r)),hs=(e,t={},r="unknown")=>{if(!Qe(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=ae(e,"expr"),o=ae(e,"value");if(ae(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(!Qe(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let a=e.branches[s];if(!Qe(a))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!ae(a,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(ds(a.when,t))return lr(a,`Computed variable "${r}" branch ${s}`,t)}return lr(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 lr(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}`)}},Et=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=je(e,r),i=Object.entries(r).filter(([,f])=>Ae(f)).map(([f])=>f),s={},a=[],c=f=>{if(ae(s,f))return s[f];let d=r[f];if(!Ae(d))return o[f];let p=a.indexOf(f);if(p>=0){let h=[...a.slice(p),f].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}a.push(f);try{let h=hs(d.computed,u,f);return ms(f,d.type,h),s[f]=h,h}finally{a.pop()}},l=new Proxy({},{get:(f,d)=>{if(typeof d=="string")return c(d)},has:(f,d)=>typeof d=="string"&&(ae(o,d)||i.includes(d)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(f,d)=>{if(!(typeof d!="string"||!ae(o,d)&&!i.includes(d)))return{enumerable:!0,configurable:!0}}}),u={variables:l,runtime:t,resolveVariable:c};return n?(i.forEach(f=>{c(f)}),{...o,...s}):l},gs=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>Et({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),dr=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(Ae(o))return;let i=ss(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},xt=(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(", ")}`)},Ct=(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(", ")}`)},ys=2,Pn=12,Nn=(e=ys)=>{if(!Number.isInteger(e)||e<0||e>Pn)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${Pn}.`);return e},bs=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},wt=e=>typeof e=="number"&&Number.isFinite(e),pr=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!wt(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!wt(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!wt(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}".`);Nn(o.roundTo)}}},St=(e,t,r,n={})=>{let o=(s,a,c)=>{let l=s??a;if(!wt(l))throw new Error(`Operation "${t}" requires ${c} to be a number.`);return l},i=s=>{let a=o(s,void 0,"value");if(a===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return a};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),Nn(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 Vn=(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()))},Is=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let a=i.character?.sprite;return a&&Object.keys(a).length>0&&(s.sprite=a),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},hr=(e={},t={})=>{let r={},n=["sfx","voice"],o=s=>{let a=e[s],c=t[s];c&&!a?r[s]={changeType:"add",data:c}:a&&!c?n.includes(s)||(r[s]={changeType:"delete",data:a}):a&&c&&JSON.stringify(a)!==JSON.stringify(c)&&(r[s]={changeType:"update",data:c})};o("background"),o("bgm"),o("voice");let i=Is(e.dialogue,t.dialogue);return i&&(r.dialogue=i),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),r},mr=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,t.background.resourceId||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"),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(a=>{let c={...a};return delete c.animations,i(c)?c: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},ws=(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},As=(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=ws(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},vs={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"])},jn=(e,t)=>{let r=e[e.length-1];return r?vs[r]?.has(t)===!0:!1},ur=(e,t,r=[])=>Array.isArray(e)?e.map(n=>ur(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,jn(r,n)?o:ur(o,t,[...r,n])])):As(e,t),fr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>fr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,jn(r,n)?o:fr(o,t,[...r,n])])):typeof e=="string"?Z(e,t):e,gr=(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=ur(e,t._event);return fr(r,t)};var pe=e=>structuredClone(te(e)?$e(e):e),et=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:pe(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Un=(e,t)=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let r=e.map(n=>pe(n)).filter(n=>t(n)||n.animations);return{hasValidItems:r.length>0,processedItems:r}},Me=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Mn=e=>e?.animations?.playback?.continuity==="persistent",Es=e=>{if(e){if(e.character&&Me(e.character,"name"))return e.character.name;if(Me(e,"characterName"))return e.characterName}},Bn=e=>!!e?.character&&Me(e.character,"sprite"),xs=e=>{let t={},r=!1,n=Es(e);return n!==void 0&&(t.name=n,r=!0),Bn(e)&&(t.sprite=pe(e.character.sprite),r=!0),r?t:void 0},Fn=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Cs=({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=>pe(o)):delete e.initialRevealedContent,e.content=[...n,...t]},Ss=()=>({}),_s=(e,t)=>{if(t.background){let{animationsOnly:r,state:n}=et(t.background,s=>!!s.resourceId);if(r){e.background=e.background?.resourceId?{...pe(e.background),...n}:n;return}if(!t.background.resourceId){delete e.background;return}let o=pe(t.background),i=e.background;i?.resourceId===o.resourceId&&i?.transformId===o.transformId&&!Me(o,"animations")&&Mn(i)&&(o.animations=pe(i.animations)),e.background=o}else e.background?.animations&&!Mn(e.background)&&(e.background.animations={})},$s=(e,t)=>{if(!t.dialogue){e.dialogue&&(Fn(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:u}=et(t.dialogue.ui,f=>!!f.resourceId);l?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&&Cs({dialogueState:e.dialogue,content:t.dialogue.content,append:n});let o=Me(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=Me(t.dialogue,"characterId"),s=xs(t.dialogue),a=s!==void 0,c=Bn(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,a?e.dialogue.character=!i&&o&&e.dialogue.character?{...pe(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,c||Fn(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=pe(e.dialogue.character)),e.dialogue.lines.push(l)}},Os=(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},Rs=(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}}},Ls=(e,t)=>{if(t.visual){let{hasValidItems:r,processedItems:n}=Un(t.visual.items,o=>!!o.resourceId);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))},ks=(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}=Un(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);r?e.character={items:n}:delete e.character},Ps=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Ts=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=et(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},Ds=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=et(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},Ns=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=et(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=pe(t.form)}else e.form&&delete e.form},Vs=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},js=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},Ms=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},Re=e=>vt(Ss,[Ms,_s,Os,Rs,Ls,$s,ks,Ps,Ts,Ds,Ns,Vs,js])(e);var ve={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:Vn},Fs=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,Us=(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},Ot=(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),a=Fs.exec(s);if(a){let[,c,l,u]=a,f=Us(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((p,h)=>{let g={...t,[c]:p};l&&(g[l]=h),d.forEach(y=>{let I=Ot(y,g,r),A=Z(I,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(Ot(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=Ot(i,t,r)}),n},Lr=({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".`)},Bs=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);return Lr({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n&&(i.playback=structuredClone(n)),i},zs=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Lr({animationType:e.type,animationId:t,animationPath:r}),e.type},Ws=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},qs=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Ys=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),eo=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),{}),Rt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify(vr(t))},to=(e=[])=>e.filter(t=>eo(t)).map(t=>structuredClone(t)),ro=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,yr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,ro(r)),0),no=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(yr(e.tween),yr(e.prev?.tween),yr(e.next?.tween),ro(e.mask?.progress)),zn=({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(Rt).filter(Boolean));return e.some(n=>{if(!eo(n))return!1;let o=Rt(n);return o?r.has(o):!1})},ce=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||zn({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:zn({animationInstances:e,activePersistentAnimations:o}),Ks=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Hs=(e,t)=>{if(Ks(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},Js=({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?Bs({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},Gs=({hasPrevious:e,hasCurrent:t,previousResourceId:r,currentResourceId:n,sharedTarget:o})=>!e&&t?"enter":e&&!t?"exit":e&&t?r===n&&o?"update":"replace":"none",Xs=({animationType:e,animationId:t,animationPath:r,lifecycle:n})=>{if(!(e!=="update"||n==="update"))throw new Error(`[${r}] Animation "${t}" has type "update", but update animations can only be used when the same target persists across the state change. Use type "transition" for enter, exit, and replace.`)},Qs=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Lr({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},kr=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(Qs(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Er=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=Z(e,t);return r&&typeof r=="object"?e:r},xr=(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},Zs=({content:e,path:t,variables:r})=>xr(e,t).reduce((n,o)=>{let i=Er(o.text,{variables:r});return n+`${i??""}`.length},0),Wn=(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))},_t=(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("-")}`},br=(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},ea=(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},qn=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},$t=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},ta=(e={})=>e.textStyles||{},ra=(e={})=>e.images||{},na=(e={})=>e.colors||{},oa=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,tt=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,Ue=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},Yn=(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},oo=(e,t)=>{if(typeof e!="string"||!oa.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},Kn=(e,t,r)=>{let n=oo(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})`},ia=(e={},t)=>{let r=ta(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=Yn(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:Kn(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 a=e.colors?.[r.strokeColorId];if(!a)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let c=Yn(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=Kn(a.hex,c,`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},Cr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Cr(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]=Cr(i,t,tt(r,o)));return e.textStyleId!==void 0&&(Ue(e.textStyleId,r,"textStyleId"),n.textStyle=ia(t,e.textStyleId)),n},io=(e={},t)=>{let r=na(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return oo(r.hex,`Color "${t}"`)},so=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Ir=(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 ${so(`${t}.fill`)} instead`)},sa=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>rt(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]=rt(i,t,tt(r,o)));return e.colorId!==void 0&&(Ue(e.colorId,r,"colorId"),n.fill=io(t,e.colorId)),n},rt=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>rt(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 ${so("fill")} instead`);Ir(e,"hover",r),Ir(e,"click",r),Ir(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]=sa(i,t,tt(r,o));continue}n[o]=rt(i,t,tt(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(Ue(e.colorId,r,"colorId"),n.fill=io(t,e.colorId)),n},wr=(e={},t)=>{let r=ra(e)?.[t];return r||null},ao=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",Hn=(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 ${ao(`${t}.${n}`)} instead`)},Jn=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},Sr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Sr(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 ${ao(o)} instead`);Hn(e,"hover",r,"src"),Hn(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]=Sr(i,t,tt(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){Ue(e.imageId,r,"imageId");let o=wr(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&&(Ue(e.hoverImageId,r,"hoverImageId"),Jn(n,"hover",wr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(Ue(e.clickImageId,r,"clickImageId"),Jn(n,"click",wr(t,e.clickImageId)?.fileId??e.clickImageId)),n},Pr=(e,t={},r="root")=>Sr(rt(Cr(e,t,r),t,r),t,r),Ee=Pr,Be=(e=[])=>e.find(t=>t.id==="story");var aa=(e={})=>e?.muteAll?0:e?.musicVolume??50,le=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,confirmDialog:f,form:d,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:I}={})=>{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??a??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},x=da({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e}),b={variables:e,runtime:A,saveSlots:r,isChoiceVisible:c,isFormVisible:l,canRollback:u,confirmDialog:f,form:d,historyDialogue:p,characters:h};return x&&(b.dialogue=x,b.dialogueLines=x.lines),b},Gn=100,Lt=(e,t)=>{if(Array.isArray(e))return e.map(n=>Lt(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=Lt(r[n],t)}),r.type==="text-revealing"?t(r):r},ca=e=>Lt(e,t=>({...t,revealEffect:"none"})),la=e=>Lt(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,Gn):Gn;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),xe=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?ca(e):r?la(e):e,co=({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:{}}}}),_r=e=>{if(Array.isArray(e))return e.map(_r);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=_r(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}}:{}}}}},ua=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),Xn=(e,t)=>{let r=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},n=r.actions&&typeof r.actions=="object"?r.actions:{};return{...e||{},payload:{...r,actions:{...n,...t}}}},$r=(e,t)=>{if(Array.isArray(e))return e.map(i=>$r(i,t));if(!e||typeof e!="object")return e;let r={};for(let[i,s]of Object.entries(e))r[i]=$r(s,t);if(r.type!=="input"||typeof r.field!="string")return r;let n=t?.fields?.[r.field];if(!n)return r;let o={updateFormField:{formId:t.id,formKey:t.key,field:n.id,value:"_event.value",_interactionSource:"form"}};return{...r,value:n.value,placeholder:r.placeholder===void 0?n.placeholder:r.placeholder,multiline:r.multiline===void 0?n.multiline:r.multiline,...r.maxLength===void 0&&n.maxLength!==void 0?{maxLength:n.maxLength}:{},change:Xn(r.change,o),submit:Xn(r.submit,t.submitActions)}},Or=(e,t)=>{if(Array.isArray(e))return e.map(n=>Or(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Or(o,t);for(let n of ua){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form",_formId:t.id,_formKey:t.key}})}return r},Rr=({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}},lo=(e=[],t={})=>e.map(r=>{let n=Rr({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}}),fa=e=>!(!e||e.mode==="adv"&&e.content===void 0),da=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n}={})=>{if(!t&&!fa(e))return;let o=e.content===void 0?[{text:""}]:xr(e.content,"dialogue.content"),i=e.content===void 0?0:Zs({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),s=(e.lines||[]).map((c,l)=>{let u=xr(c.content,`dialogue.lines[${l}].content`),f=Rr({characterId:c.characterId,character:c.character,characterName:c.characterName,characters:r});return{...c,content:u.map(d=>({...d,text:Er(d.text,{variables:n})})),character:f,characterName:f.name}}),a=Rr({characterId:e.characterId,character:e.character,characters:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:a,content:o.map(c=>({...c,text:Er(c.text,{variables:n})})),initialRevealedCharacters:i,lines:s}},uo=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=Z(e,r,{functions:ve});return Ee(xe(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},Ar=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),Qn=({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:Ar(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:Ar(o.keyup)});return}e[n]={...i,[r]:{payload:Ar(o)}}})},pa=(e={},t={})=>{let r={};return Qn({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),Qn({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},ge=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:a,allowIncomingUpdateFallback:c=!1})=>{if(!e)return[];let l=[],u=({instanceId:b,targetId:R})=>{let L=Js({resources:t,animationId:g,playback:y,instanceId:b,targetId:R,animationPath:s});L&&l.push(L)},f=r!=null&&r!==!1,d=n!=null&&n!==!1,p=o&&i&&o===i,h=Gs({hasPrevious:f,hasCurrent:d,previousResourceId:r,currentResourceId:n,sharedTarget:p});Hs(e,s);let g=Ws(e),y=qs(e),I=t?.animations?.[g],A=zs(I,{animationId:g,animationPath:s}),x=c&&A==="update"&&h!=="update"&&d&&i;if(x||Xs({animationType:A,animationId:g,animationPath:s,lifecycle:h}),A==="update")return f&&d&&r===n&&p?u({instanceId:`${a}-animation-update`,targetId:i}):x&&u({instanceId:`${a}-animation-update`,targetId:i}),l;if(A==="transition"){let b=`${a}-animation-transition`,R=y?.continuity==="persistent"?b:`${a}-animation-in`;if(f&&d&&p)return u({instanceId:b,targetId:i}),l;f&&u({instanceId:`${a}-animation-out`,targetId:o}),d&&u({instanceId:R,targetId:i})}return l},ha=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),ma=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:a,variables:c,runtime:l,activePersistentAnimations:u,restoredPersistentAnimations:f,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:I,saveSlots:A=[]})=>{let{elements:x,animations:b}=e;if(t.background){let R=n===void 0?!0:Ys(n?.background??{},"animations"),L=x.find(B=>B.id==="story");if(!L)return e;let V=ea(o,t.background),N=r?.background?.resourceId,_=t.background.resourceId??(t.background.animations?N:void 0),U=qn(o,N),M=qn(o,_);if(_){let{images:B={},videos:E={}}=o,S=B[_]||E[_];if(S){let j=E[_]!==void 0,q={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...V},H={id:$t({resourceId:_,kind:j?"video":"sprite"}),type:j?"video":"sprite",x:q.x,y:q.y,src:S.fileId,width:S.width,height:S.height,alpha:1,anchorX:q.anchorX,anchorY:q.anchorY,rotation:q.rotation,scaleX:q.scaleX,scaleY:q.scaleY};j&&(H.loop=t.background.loop??!1,H.volume=S.volume??50),L.children.push(H)}}if(_){let{layouts:B={}}=o,E=B[_];if(E){let S={id:$t({resourceId:_,kind:"container"}),type:"container",children:E.elements};V&&Object.assign(S,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...V});let j=Z(S,le({variables:c,runtime:l,saveSlots:A,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:I,characters:o.characters||{},skipTransitionsAndAnimations:a}),{functions:ve});L.children.push(Ee(xe(j,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:a}),o))}}let P=ge({animationsDef:t.background.animations,resources:o,previousResourceId:N,currentResourceId:_,previousTargetId:$t({resourceId:N,kind:U}),currentTargetId:$t({resourceId:_,kind:M}),animationPath:"background.animations",idPrefix:"bg-cg",allowIncomingUpdateFallback:!0});ce({animationInstances:P,isLineCompleted:s,skipTransitionsAndAnimations:a,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:R})&&b.push(...P)}return e},ga=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:a,animations:c}=e;if(t.character&&n){let l=a.find(h=>h.id==="story");if(!l)return e;let u=t.character.items||[],f=r?.character?.items||[],d=Wn(u),p=Wn(f);for(let h=0;h<u.length;h++){let g=u[h],{transformId:y,sprites:I}=g,A=f.find(M=>M.id===g.id),x=f.findIndex(M=>M.id===g.id),b=A?.sprites&&A.sprites.length>0,R=I&&I.length>0,L=x>=0?_t(A,x,p):void 0,V=ge({animationsDef:g.animations,resources:n,previousResourceId:L,currentResourceId:R?_t(g,h,d):void 0,previousTargetId:L,currentTargetId:R?_t(g,h,d):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!I&&!y&&b&&ce({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){c.push(...V);continue}if(g.animations&&!I&&!y)continue;if(!I||I.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let N=_t(g,h,d),_=n.transforms[y];if(!_){console.warn("Transform not found:",y);continue}let U={type:"container",id:N,x:g.x??_.x,y:g.y??_.y,anchorX:_.anchorX,anchorY:_.anchorY,rotation:_.rotation,scaleX:_.scaleX,scaleY:_.scaleY,children:[]};for(let M of I){let P=n.images[M.resourceId];if(!P){console.warn(`Image resource not found: ${M.resourceId}`);continue}U.children.push({type:"sprite",id:`${N}-${M.id}`,src:P.fileId,width:P.width,height:P.height,x:0,y:0})}l.children.push(U),ce({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...V)}}return e},ya=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:a,activePersistentAnimations:c,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,saveSlots:g=[]})=>{let{elements:y,animations:I}=e;if(t.visual&&n){let A=y.find(b=>b.id==="story");if(!A)return e;let x=t.visual.items;for(let b of x){if(b.resourceId){let{images:N={},videos:_={},spritesheets:U={}}=n,M=U[b.resourceId];if(M){let P=br(n,b),B=b.animationName;if(B){let E=M.animations?.[B];if(!E)throw new Error(`Animation '${B}' not found in spritesheet resource '${b.resourceId}'`);let S={id:`visual-${b.id}`,type:"animated-sprite",x:b.x??P.x,y:b.y??P.y,width:b.width??M.width,height:b.height??M.height,alpha:b.alpha??1,anchorX:P.anchorX,anchorY:P.anchorY,rotation:P.rotation,scaleX:P.scaleX,scaleY:P.scaleY,spritesheetSrc:M.fileId,spritesheetData:M.jsonData,animation:{frames:E.frames,animationSpeed:b.animationSpeed??E.animationSpeed??.5,loop:b.loop??E.loop??!0}};A.children.push(structuredClone(S))}}else{let P=N[b.resourceId]||_[b.resourceId];if(P){let B=_[b.resourceId]!==void 0,E=br(n,b),S={id:`visual-${b.id}`,type:B?"video":"sprite",src:P.fileId,width:P.width,height:P.height,x:E.x,y:E.y,anchorX:E.anchorX,anchorY:E.anchorY,rotation:E.rotation,scaleX:E.scaleX,scaleY:E.scaleY};B&&(S.loop=P.loop??!1,S.volume=P.volume??50),A.children.push(S)}}}if(b.resourceId){let{layouts:N={}}=n,_=N[b.resourceId];if(_){let U=br(n,b),M={id:`visual-${b.id}`,type:"container",children:structuredClone(_.elements),x:U.x,y:U.y,anchorX:U.anchorX,anchorY:U.anchorY,rotation:U.rotation,scaleX:U.scaleX,scaleY:U.scaleY},P=Z(M,le({variables:s,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i}),{functions:ve});A.children.push(Ee(xe(P,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),n))}}let L=(r?.visual?.items||[]).find(N=>N.id===b.id),V=ge({animationsDef:b.animations,resources:n,previousResourceId:L?.resourceId,currentResourceId:b.resourceId,previousTargetId:L?.resourceId?`visual-${b.id}`:void 0,currentTargetId:b.resourceId?`visual-${b.id}`:void 0,animationPath:`visual.items[${b.id}].animations`,idPrefix:b.id});ce({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:c})&&I.push(...V)}}return e},Fe="dialogue-character-sprite",Zn=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,ba=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:a}=e,c=Be(e.elements);if(!c)return e;let l=t.dialogue?.character?.sprite,u=r?.dialogue?.character?.sprite,f=Zn(l),d=Zn(u),p=ge({animationsDef:l?.animations,resources:n,previousResourceId:d?Fe:void 0,currentResourceId:f?Fe:void 0,previousTargetId:d?Fe:void 0,currentTargetId:f?Fe:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!f)return l?.animations&&d&&ce({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.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:Fe,x:h.x,y:h.y,anchorX:h.anchorX,anchorY:h.anchorY,rotation:h.rotation,scaleX:h.scaleX,scaleY:h.scaleY,children:[]};for(let y of l.items){let I=n.images?.[y.resourceId];if(!I){console.warn(`Image resource not found: ${y.resourceId}`);continue}g.children.push({type:"sprite",id:`${Fe}-${y.id}`,src:I.fileId,width:I.width,height:I.height,x:0,y:0})}return c.children.push(g),ce({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...p),e},Ia=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:u,skipOnlyViewedLines:f,isLineCompleted:d,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:y,saveSlots:I=[]})=>{let{elements:A,animations:x}=e;if(!t.dialogue||o)return e;let b=A.find(L=>L.id==="story");if(!b)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:L={}}=n,V=L[t.dialogue.ui.resourceId];if(V){let N={elements:V.elements},_=le({variables:h,runtime:g,saveSlots:I,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:d,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:u,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:f,skipTransitionsAndAnimations:p}),U={functions:ve},M=Ot(N,_,U),P=Z(M,_,U),B=Ee(xe(P?.elements,{isLineCompleted:d,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(B))for(let E of B)b.children.push(E);else B&&b.children.push(B)}}ba(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let R=ge({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 ce({animationInstances:R,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&x.push(...R),e},wa=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,runtime:c,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:I,animations:A}=e;if(t.choice&&n){let x=Be(I);if(!x)return e;let b=n?.layouts[t.choice.resourceId];if(b&&b.elements){let L={elements:b.elements},V=Z(L,{...le({variables:a,runtime:c,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:u,isChoiceVisible:f??!!t.choice,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:ve}),N=_r(Ee(xe(V?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n));if(Array.isArray(N))for(let _ of N)x.children.push(_);else N&&x.children.push(N)}let R=ge({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"});ce({animationInstances:R,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&A.push(...R)}return e},Aa=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,runtime:c,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:I,animations:A}=e;if(!y?.resourceId||!n)return e;let x=Be(I);if(!x)return e;let b=n?.layouts?.[y.resourceId];if(!b)return console.warn(`Form layout not found: ${y.resourceId}`),e;let R={id:"form-container",type:"container",x:0,y:0,children:b.elements||[]},L={...le({variables:a,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},V=Z(R,L,{functions:ve}),N=Or(Ee(xe($r(V,y),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n),y);N&&x.children.push(N);let _=ge({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 ce({animationInstances:_,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(..._),e},va=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,saveSlots:d=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=pa(h.keyboard,h.keyup);if(g&&Object.keys(g).length>0&&(e.global.keyboard=g),!Array.isArray(h.elements)||h.elements.length===0)return e;let y=Be(e.elements);if(!y)return e;let I={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(uo({container:I,resources:r,templateData:le({variables:n,runtime:o,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:a,skipTransitionsAndAnimations:p})),e},Ea=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Be(i))return e;let c=r.sounds[t.bgm.resourceId];if(!c)return e;let l=le({variables:o,runtime:n}).runtime;s.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:aa(l),startDelayMs:t.bgm.startDelayMs??null})}return e},xa=(e,{presentationState:t,resources:r})=>{let{audio:n}=e;if(t.sfx&&r){let o=t.sfx.items;for(let i of o){let s=r.sounds?.[i.resourceId];s&&n.push({id:i.id,type:"sound",src:s.fileId,loop:i.loop??s.loop??!1,volume:i.volume??s.volume??50,startDelayMs:i.startDelayMs??s.startDelayMs??null})}}return e},Ca=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},Sa=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,_a=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let a=t.voice,{resourceId:c,loop:l,startDelayMs:u}=a,f=Ca(r,n,c);if(!f)return e;let d=le({variables:i,runtime:o}).runtime;return s.push({id:`voice-${n}-${c}`,type:"sound",src:f.fileId,volume:Sa(a,d),loop:l??!1,startDelayMs:u??null}),e},$a=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,saveSlots:d=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:I}=e;if(t.layout){let R=Be(y);if(!R)return e;let L=n.layouts[t.layout.resourceId];if(!L)return e;Array.isArray(L.transitions)&&!p&&!h&&kr({animations:I,transitions:L.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let V={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:L.elements||[]};R.children.push(uo({container:V,resources:n,templateData:le({variables:o,runtime:i,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:a,skipTransitionsAndAnimations:h}))}let A=r?.layout?.resourceId,x=t.layout?.resourceId,b=ge({animationsDef:t.layout?.animations,resources:n,previousResourceId:A,currentResourceId:x,previousTargetId:A?`layout-${A}`:void 0,currentTargetId:x?`layout-${x}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return ce({animationInstances:b,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&I.push(...b),e},Oa=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:a}=e,c=t?.screen?.animations;if(!c)return e;let l=r!=null,u=ge({animationsDef:c,resources:n,previousResourceId:l?"story":void 0,currentResourceId:"story",previousTargetId:l?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return ce({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...u),e},Ra=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:u,overlayStack:f=[],dialogueHistory:d=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:I,animations:A}=e;return f&&f.length>0&&f.forEach((x,b)=>{let R=r.layouts[x.resourceId];if(!R){console.warn(`Overlay layout not found: ${x.resourceId}`);return}Array.isArray(R.transitions)&&(y||kr({animations:A,transitions:R.transitions,defaultTargetId:`overlayStack-${b}`,idPrefix:`overlayStack-${b}`,animationPathPrefix:`overlayStack[${b}]`}));let L={id:`overlayStack-${b}`,type:"container",x:0,y:0,children:[co({id:`overlayStack-${b}-blocker`,screen:h}),...R.elements||[]]},V=lo(d,r.characters),N=le({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:u,historyDialogue:V,characters:r.characters||{},skipTransitionsAndAnimations:y}),_=Z(L,N,{functions:ve}),[U,...M]=_.children||[],P=Ee(xe({..._,children:M},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);I.push({...P,children:U?[U,...P.children||[]]:P.children})}),e},La=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,confirmDialog:d,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:I,animations:A}=e;if(!d?.resourceId)return e;let x=r.layouts?.[d.resourceId];if(!x)return console.warn(`ConfirmDialog layout not found: ${d.resourceId}`),e;Array.isArray(x.transitions)&&!y&&kr({animations:A,transitions:x.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let b={id:"confirmDialog",type:"container",x:0,y:0,children:[co({id:"confirmDialog-blocker",screen:h}),...x.elements||[]]},R=lo(p,r.characters),L=Z(b,le({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,confirmDialog:d,historyDialogue:R,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:ve}),[V,...N]=L.children||[],_=Ee(xe({...L,children:N},{isLineCompleted:g,skipMode:a,skipTransitionsAndAnimations:y}),r);return I.push({..._,children:V?[V,..._.children||[]]:_.children}),e},fo=e=>vt(ha,[va,ma,ga,ya,Ia,wa,Aa,$a,Oa,Ea,xa,_a,Ra,La])(e);var ka=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"}}),kt=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),nt=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"}),Tr=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Dr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Pa=(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]}},ze=e=>Object.fromEntries(Object.entries(ka).map(([t,r])=>{let n=Pa(e,r.source),o=n!==void 0?n:kt[t]??nt[t];return[t,o]})),ye=(e,t)=>ze(e)[t],ho=(e={})=>Object.fromEntries(Tr.map(t=>[t,e[t]??kt[t]]));var Pt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Io=1,Nr="choice",Tt="form",Vt=()=>({manual:{...Pt.manual},auto:{...Pt.auto},applyMode:Pt.applyMode}),Vr=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...Vt()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},D=e=>{let t=te(e)?$e(e):e;return structuredClone(t)},T=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),jt=e=>String(e),wo=()=>({sections:[],resources:[]}),Ta=e=>T(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):wo(),Da=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Na=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:Da(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),Va=()=>({resourceId:void 0}),ja=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},jr=(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}},Ao=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 a=r.get(s);if(a!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${a}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},vo=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Eo=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Io)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Ma=(e,t={})=>{let r;try{r=Eo(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:vo(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},Fa=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Ma(t,r)])),xo=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Rl(r));return t.length>0?t:void 0},Ua=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})},mo=(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}},Ba=(e,t="viewedRegistry")=>{if(e===void 0)return wo();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=mo(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=mo(o,"resources",i,t);return[s.resourceId,s]})))}},Co=(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}=jr(t,n);if(!s)throw new Error(`Malformed save slot ${r}: section "${n}" does not exist in projectData.`);if(!s.lines?.some(c=>c.id===o))throw new Error(`Malformed save slot ${r}: line "${o}" does not exist in section "${n}".`);return{sceneId:i,sectionId:n,lineId:o}},za=(e,t,r)=>{if(!T(e)||!Array.isArray(e.timeline))return ot({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((a,c)=>{if(!T(a))return[];try{let l=Co(a,r,`rollback.timeline[${c}]`),u=Nt({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:a.rollbackPolicy}),f=xo(D(a.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(n.length===0)return ot({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 a=n.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);a>=0?o=a:(n.push(Nt({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}},Wa=(e,t,r)=>{if(!T(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=Ur(t),o=Co(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?je(D(e.variables),t.resources?.variables??{}):{},s=nc({loadedContextRuntime:T(e.runtime)?D(e.runtime):{}}),a={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:za(e.rollback,o,t)};return s&&(a.runtime=s),a},qa=(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)=>Wa(r,t,n))}},Ya=(e,t)=>{if(!T(e))throw new Error("Malformed save slot.");let r=Eo(e.formatVersion);return{...e,formatVersion:r,state:qa(e.state,t)}},go=(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},Ka=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:go(e.confirmActions,"confirmActions",{required:!0}),cancelActions:go(e.cancelActions,"cancelActions")}},qe=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Ha=e=>(T(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),Ye=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},So=e=>{if(!(!T(e)||!e.animations))return{animations:D(e.animations)}},Ja=(e,t)=>{let r=So(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},Ga=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},Xa=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},Dt=e=>String(e??""),_o=(e,t)=>{let r=Dt(t);return e?.trim===!0?r.trim():r},Qa=e=>T(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>T(t)).map(([t,r])=>[t,{id:t,...D(r)}])):{},Za=(e,t)=>{if(!t||!T(e.global.formDrafts))return;let r=e.global.formDrafts[t];return T(r)?r:void 0},$o=(e,t)=>{let r=Ha(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},Mr=(e,t)=>{let r=_o(e,t);return e?.required===!0&&r.length===0?"required":null},ec=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=X({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:Re(n.slice(0,o+1).map(i=>i.actions||{}))},tc=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=Ga(t),o=Xa(r,n);if(!n||!o)return null;let i=Za(e,o),s=Qa(t),a=Yr({state:e}),c={},l=[],u={},f=!0;return Object.entries(s).forEach(([d,p])=>{let h=Dt(a?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},d)?Dt(i.values[d]):h,y=i?.touched?.[d]===!0,I=Mr(p,g),A=i?.submitted||y?I:null,x=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,b={id:d,variableId:p.variableId,value:g,initialValue:h,valid:!I,error:A,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...x!==void 0?{maxLength:x}:{}};I&&(f=!1),c[d]=b,l.push(b),u[d]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:f,submitted:i?.submitted===!0,fields:c,fieldList:l,values:u,submitActions:{submitForm:{formId:n,formKey:o,actions:D(t.submitActions??{})}},cancelActions:{cancelForm:{formId:n,formKey:o,actions:D(t.cancelActions??{})}}}},Le=[],yo="line",Fr="interaction",Nt=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),Ur=e=>{let{contextVariableDefaultValues:t}=dr(e??{});return D(t)},Oo=()=>({...D(nt)}),Ro=({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]=Lo(s,D(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},rc=({loadedGlobalRuntime:e={}})=>Ro({loadedRuntime:e,runtimeIds:Tr,defaults:kt,path:"global.runtime"}).runtimeState,nc=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=Ro({loadedRuntime:e,runtimeIds:Dr,defaults:Oo(),path:"context.runtime"});return r?t:void 0},Br=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},oc=e=>e.runtime?(Dr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=D(nt[t]))}),e.runtime):(e.runtime=Oo(),e.runtime),ic=e=>ho(e.global),sc=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:ic(e)}})},ac=e=>po[e],cc=(e,t)=>{let r=ac(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}"`)},Lo=(e,t)=>(cc(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),ko=(e,t,r)=>{let n=Lo(t,r);if(t in nt){let o=Br(e);if(!o)return n;let i=oc(o);return i[t]=n,n}return e.global[t]=n,n},Po=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:D(e)},configuration:{},views:[],bgm:Va(),variables:Ur(t),rollback:ot({pointer:e})}),Ke=e=>e?(e.currentPointerMode="read",T(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,lc=(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=Po({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,uc(e,{queueRender:t}),o},uc=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,qe(e),Ye(e),e.global.nextLineConfig=Vt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},To=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},ot=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[Nt({sectionId:e.sectionId,lineId:e.lineId})]:[]}},Pe=(e,t={})=>{if(e?.rollback)return To(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=ot({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},zr=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=Pe(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(Nt(t)),n.currentIndex=n.timeline.length-1},fc=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=Le[Le.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)},dc=({state:e},t={})=>{let r=t?.source===yo?yo:Fr,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?(Le.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Le.push({checkpointIndex:o.currentIndex,source:r}),e)},pc=({state:e})=>(Le.pop(),e),he=(e,t,r)=>{let o=Le[Le.length-1]?.source??Fr;if(!Ll(t,o))return;let i=fc(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:D(r)}))},bo=(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:a}of n){let c=e.projectData.resources?.variables?.[o],l=c?.scope,u=c?.type;if(Ae(c))throw new Error(`Cannot update computed variable: ${o}`);if(c?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);xt(l,o),Ct(u,i,o),pr(u,i,s,o,{roundTo:a}),l==="context"&&(r.variables[o]=St(r.variables[o],i,s,{roundTo:a}))}},hc=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{kl(e,r,n)})},mc=(e,t)=>{let{sectionId:r,lineId:n}=t,s=X({state:e},{sectionId:r})?.lines?.find(a=>a.id===n)?.actions;s&&Object.entries(s).forEach(([a,c])=>{Xo(e,a,c)})},Do=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=Pe(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&st({state:e}),e.global.skipMode&&ke({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=Ur(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=D(Pt),e.global.overlayStack=[],qe(e),Ye(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let a=i;a<=t;a++)a>i&&Vr(e),mc(e,n.timeline[a]),hc(e,n.timeline[a]);let s=Ke(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(a=>a?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},gc=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;Ao(t);let a=t.story.initialSceneId,c=t.story.scenes[a],l=c.initialSectionId,u=c.sections[l],f={sceneId:a,sectionId:l,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:d}=dr(t),p={...d,...je(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:Ba(s,"accountViewedRegistry"),nextLineConfig:Vt(),saveSlots:Fa(n),overlayStack:[],variables:p,...rc({loadedGlobalRuntime:i})},contexts:[Po({pointer:f,projectData:t})]}},yc=({state:e})=>e.global.overlayStack||[],bc=({state:e})=>e.global.pendingEffects,No=({state:e})=>e.global.skipMode,Ic=({state:e})=>e.global.autoMode,Vo=({state:e})=>e.global.dialogueUIHidden,jo=({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=X({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),a=i.lines.slice(0,s+1),c=[],l={};for(let u of a){let f=u.actions||{};if(l=Re([l,f]),!f.dialogue)continue;let d=l.dialogue||{},p="";d.character?.name!==void 0?p=d.character.name:d.characterId&&(p=e.projectData.resources?.characters?.[d.characterId]?.name||"");let h=Na({sectionId:n,lineId:u.id,content:f.dialogue.append===!0?d.content:f.dialogue.content,dialogueState:d,characterName:p});if(f.dialogue.append===!0&&c.length>0){c[c.length-1]={...c[c.length-1],content:h.content,text:h.text,characterId:h.characterId,character:h.character,characterName:h.characterName};continue}c.push(h)}return c},wc=({state:e})=>e.global.confirmDialog??null,it=({state:e},{pointer:t}={})=>{let r=t??ue({state:e})?.pointer,n=ec({state:e,pointer:r});return tc({state:e,form:n.form,pointer:r})},Ac=({state:e},{pointer:t}={})=>!!it({state:e},{pointer:t}),me=({state:e},{pointer:t}={})=>{let r=it({state:e},{pointer:t});if(r)return{source:Tt,formId:r.id,formKey:r.key};let n=Mo({state:e,pointer:t});return n?{source:Nr,resourceId:n}:null},vc=({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 a=X({state:e},{sectionId:n});if(!a||!a.lines||!Array.isArray(a.lines))return s.lastLineId===o;let c=a.lines.findIndex(u=>u.id===s.lastLineId),l=a.lines.findIndex(u=>u.id===o);return c===-1||l===-1?s.lastLineId===o:l<=c},Ec=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},Wr=({state:e},t)=>vc({state:e,registry:e.global.accountViewedRegistry},t),xc=({state:e},t)=>Ec({registry:e.global.accountViewedRegistry},t),Cc=({state:e})=>e.global.nextLineConfig,Mo=({state:e,pointer:t}={})=>{let r=t??ue({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=X({state:e},{sectionId:n})?.lines||[],a=s.findIndex(l=>l.id===o);if(a<0)return;let c;for(let l of s.slice(0,a+1)){let u=l?.actions;if(u?.cleanAll&&(c=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){c=void 0;continue}let f=u.choice;if(f?.resourceId){c=f.resourceId;continue}f?.animations||(c=void 0)}return c},Fo=({state:e})=>!!Mo({state:e}),Sc=({state:e})=>structuredClone(e),Uo=({state:e})=>e.global.saveSlots,_c=({state:e},t)=>{let r=t?.slotId,n=jt(r);return e.global.saveSlots[n]},qr=({state:e})=>ze(e),$c=({state:e},t)=>ye(e,t?.runtimeId),Yr=({state:e})=>{let t={...e.global?.variables??{},...Br(e)?.variables??{}};return Et({variables:t,runtime:ze(e),variableConfigs:e.projectData.resources?.variables??{}})},ue=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},X=({state:e},t)=>{let{sectionId:r}=t;return jr(e.projectData,r).section},Kr=({state:e})=>{let t=ue({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=X({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},Bo=({state:e})=>{let{sectionId:t,lineId:r}=ue({state:e}).pointer,o=X({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===r),a=o.slice(0,i+1).map(l=>{let u=l.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return Re(a)},Oc=({state:e})=>{let t=zo({state:e}),n=Kr({state:e})?.actions??{},o=Re([t??{},n]);return hr(t??{},o??{})},Rc=({state:e},{sectionId:t})=>{let r=X({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},a=Re([o,s]),c=hr(o,a);n.push({id:i.id,changes:c,presentationState:a}),o=mr(a)}return n},Lc=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=Rc({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},zo=({state:e})=>{let{sectionId:t,lineId:r}=ue({state:e}).pointer,o=X({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===r);if(i<=0)return null;let a=o.slice(0,i).map(c=>{let l=c.actions||{},u={};return Object.keys(l).forEach(f=>{u[f]=l[f]}),u});return mr(Re(a))},Hr=({state:e},{slotsPerPage:t=6}={})=>{let o=((qr({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let a=o+s,c=e.global.saveSlots&&e.global.saveSlots[jt(a)]||{};i.push({...c,slotId:a})}return{saveSlots:i}},kc=Uo,Pc=Hr,Tc=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},Dc=({state:e},t={})=>{let r=Bo({state:e}),n=zo({state:e}),o=Kr({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:D(i)}:o,a=i?.animations&&n===null?{}:n,{sectionId:c}=ue({state:e}).pointer,{sceneId:l}=jr(e.projectData,c),u=qr({state:e}),f=t?.activePersistentAnimations??[],d=t?.restoredPersistentAnimations??[],p=it({state:e}),h=Fo({state:e}),g=Yr({state:e}),{saveSlots:y}=Hr({state:e}),I=Tc(e);return fo({presentationState:r,previousPresentationState:a,currentLineActions:s,resources:e.projectData.resources,currentSceneId:l,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:Zo({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||I,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:jo({state:e}),saveSlots:y,variables:g,runtime:u,activePersistentAnimations:f,restoredPersistentAnimations:d})},Nc=({state:e},t)=>(e.global.confirmDialog=Ka(t),e.global.pendingEffects.push({name:"render"}),e),Vc=({state:e})=>(e.global.confirmDialog&&(qe(e),e.global.pendingEffects.push({name:"render"})),e),jc=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),he(e,"pushOverlay",t),e),Mc=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),he(e,"popOverlay",void 0),e),Fc=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),he(e,"replaceLastOverlay",t),e),Uc=({state:e})=>(e.global.overlayStack=[],qe(e),Ye(e),e.global.pendingEffects.push({name:"render"}),he(e,"clearOverlays",void 0),e),Bc=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"})},Mt=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,Ja(e,r),Ye(e);let n=me({state:e},{pointer:t}),o=n?.source===Nr,i=n?.source===Tt;return n&&Bc(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},Wo=({state:e})=>(me({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:ye(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),st=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),zc=({state:e})=>{let t=e.global.autoMode;return me({state:e})&&!t||(t?st({state:e}):Wo({state:e})),e},qo=({state:e})=>(me({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),ke=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Wc=({state:e})=>{let t=No({state:e});return me({state:e})&&!t||(t?ke({state:e}):qo({state:e})),e},Ft=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),he(e,"showDialogueUI",void 0),e),Yo=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),he(e,"hideDialogueUI",void 0),e),qc=({state:e})=>(Vo({state:e})?Ft({state:e}):Yo({state:e}),e),Te=(e,t,r)=>(ko(e,t,r),sc(e),e.global.pendingEffects.push({name:"render"}),e),at=(e,t,r,n)=>{let o=ko(e,t,r);return e.global.pendingEffects.push({name:"render"}),he(e,n,{value:o}),e},Yc=({state:e},t)=>Te(e,"dialogueTextSpeed",t?.value),Kc=({state:e},t)=>Te(e,"autoForwardDelay",t?.value),Hc=({state:e},t)=>Te(e,"skipUnseenText",t?.value),Jc=({state:e},t)=>Te(e,"skipTransitionsAndAnimations",t?.value),Gc=({state:e},t)=>Te(e,"soundVolume",t?.value),Xc=({state:e},t)=>Te(e,"musicVolume",t?.value),Qc=({state:e},t)=>Te(e,"muteAll",t?.value),Zc=({state:e},t)=>at(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),el=({state:e})=>{let t=ye(e,"saveLoadPagination")+1;return at(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},tl=({state:e})=>{let t=ye(e,"saveLoadPagination")-1;return at(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},rl=({state:e},t)=>at(e,"menuPage",t?.value,"setMenuPage"),nl=({state:e},t)=>at(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),ol=({state:e})=>(e.global.pendingEffects=[],e),il=({state:e},t)=>(e.global.pendingEffects.push(t),e),Ko=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!So(n),i=X({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&&!lc(e,{queueRender:!o}))return e;e.global.autoMode&&st({state:e}),r&&e.global.skipMode&&ke({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let c=Ke(a),l=c.read;r||We(e,{sectionId:l?.sectionId,lineId:l?.lineId}),a.rollback||Pe(a,{compatibilityAnchor:!0}),c.read={sectionId:t,lineId:s.id},r?a.rollback=ot({pointer:c.read}):zr(e,{sectionId:t,lineId:s.id})}return Mt(e,a?.pointers?.read,{screenTransition:n}),e},sl=({state:e},t)=>Ko(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),Ho=e=>(e.global.accountViewedRegistry=Ta(e.global.accountViewedRegistry),e.global.accountViewedRegistry),Jr=(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)}))}})},Jo=(e,t)=>{Jr(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:[]}}])},al=(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=X({state:e},{sectionId:r});if(s?.lines){let a=s.lines.findIndex(l=>l.id===i.lastLineId),c=s.lines.findIndex(l=>l.id===n);if(a===-1||c>a)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},We=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;al(e,Ho(e),t)&&Jo(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},cl=({state:e},t)=>(We(e,t),e.global.pendingEffects.push({name:"render"}),e),ll=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=Ho(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),Jo(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},Go=({state:e},t)=>{let r=ja(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,a=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 c=e.global.nextLineConfig.auto?.enabled,l=me({state:e});return!a&&!l&&c===!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}}):!a&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),he(e,"setNextLineConfig",t),e},ul=({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=jt(r),s=D(e.contexts);s?.forEach(l=>{Ke(l),To(l.rollback),Ua(l.rollback)});let a={contexts:s},c={formatVersion:Io,slotId:vo(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:a};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},fl=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=jt(r),o=e.global.saveSlots[n];if(o){let i=Ya(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=Vt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,qe(e),Ye(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},dl=({state:e},t)=>{let{projectData:r}=t;Ao(r),e.projectData=r;let n=r?.resources?.variables??{};return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables=je(e.global.variables,n)),e.contexts?.forEach(o=>{Object.prototype.hasOwnProperty.call(o??{},"variables")&&(o.variables=je(o.variables,n))}),qe(e),Ye(e),e.global.pendingEffects.push({name:"render"}),e},pl=({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&&!X({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=X({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 c=Ke(o);return c.read={sectionId:i,lineId:n},Mt(e,c.read),e},hl=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return Ft({state:e}),e;let r=me({state:e});if(r?.source===Nr&&t?.bypassChoice!==!0||r?.source===Tt&&t?._interactionSource!==Tt)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=ue({state:e})?.pointer,f=u?.sectionId,d=u?.lineId;f&&d&&We(e,{sectionId:f,lineId:d}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ye(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=ue({state:e})?.pointer,o=n?.sectionId,i=X({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],a=i?.lines||[],l=a.findIndex(u=>u.id===n?.lineId)+1;if(l<a.length){let u=a[l],f=!ye(e,"skipUnseenText");if(e.global.skipMode&&f&&!Wr({state:e},{sectionId:o,lineId:u.id}))return ke({state:e}),e;if(s&&!s.rollback&&Pe(s,{compatibilityAnchor:!0}),s){let h=Ke(s),g=h.read?.lineId;g&&o&&We(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:u.id}}zr(e,{sectionId:o,lineId:u.id}),Vr(e);let{activeInteraction:d}=Mt(e,{sectionId:o,lineId:u.id}),p=e.global.nextLineConfig;p?.auto?.enabled&&!d&&p.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}})}else e.global.autoMode&&st({state:e}),e.global.skipMode&&ke({state:e});return e},ml=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=me({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ye(e,"autoForwardDelay")}});let r=ue({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&We(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},gl=({state:e},t)=>Ko(e,{sectionId:t?.sectionId,screen:t?.screen}),yl=({state:e})=>{if(e.global.dialogueUIHidden)return Ft({state:e}),e;if(me({state:e}))return e;let t=ue({state:e})?.pointer,r=t?.sectionId,n=X({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],a=i.findIndex(c=>c.id===t?.lineId)+1;if(a<i.length){let c=i[a],l=!ye(e,"skipUnseenText");if(e.global.skipMode&&l&&!Wr({state:e},{sectionId:r,lineId:c.id}))return ke({state:e}),e;if(o&&!o.rollback&&Pe(o,{compatibilityAnchor:!0}),o){let f=Ke(o),d=f.read?.lineId;d&&r&&We(e,{sectionId:r,lineId:d}),f.read={sectionId:r,lineId:c.id}}zr(e,{sectionId:r,lineId:c.id}),Vr(e);let{activeInteraction:u}=Mt(e,{sectionId:r,lineId:c.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},Gr=(e,t={})=>{let r=it({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},bl=(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(Ae(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return xt(n,t.variableId),Ct(o,"set",t.variableId),{variableConfig:r,scope:n}},Il=(e,t)=>({id:e.id,key:e.key,valid:!0,values:D(t),fields:D(e.fields),fieldList:D(e.fieldList)}),wl=({state:e},t={})=>{let r=Gr(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=$o(e,r.key),i=Dt(t.value),s=r.fields[n],a=Mr(s,i);return o.values[n]=i,o.touched[n]=!0,a?o.errors[n]=a:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},Al=({state:e},t={})=>{let r=Gr(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=$o(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([f,d])=>{let p=Object.prototype.hasOwnProperty.call(n.values,f)?n.values[f]:d.value,h=Mr(d,p);n.touched[f]=!0,h&&(i[f]=h),o[f]=_o(d,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 a=!1,c=[],l=[];Object.entries(r.fields).forEach(([f,d])=>{let{scope:p}=bl(e,d),h=p==="context"?s.variables:e.global.variables,g=o[f];h[d.variableId]=St(h[d.variableId],"set",g),p==="context"&&(a=!0,l.push({variableId:d.variableId,op:"set",value:g})),(p==="device"||p==="account")&&c.push({scope:p,path:`variables.${d.variableId}`,op:"set",value:D(h[d.variableId])})}),a&&he(e,"updateVariable",{id:"submitForm",operations:l}),Jr(e,c);let u=Il(r,o);return delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},vl=({state:e},t={})=>{let r=Gr(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"}},El=({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=[],a=[];return n.forEach(({variableId:c,op:l,value:u,roundTo:f})=>{let d=e.projectData.resources?.variables?.[c],p=d?.scope,h=d?.type;if(Ae(d))throw new Error(`Cannot update computed variable: ${c}`);if(d?.readonly===!0)throw new Error(`Cannot update readonly variable: ${c}`);xt(p,c),Ct(h,l,c),pr(h,l,u,c,{roundTo:f});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:c,op:l,value:u};f!==void 0&&(y.roundTo=f),a.push(y)}g[c]=St(g[c],l,u,{roundTo:f}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${c}`,op:"set",value:D(g[c])})}),i&&he(e,"updateVariable",{id:r,operations:a}),Jr(e,s),e.global.pendingEffects.push({name:"render"}),e},xl=e=>(t,r)=>e({state:t},r),Cl=e=>({variables:Et({variables:{...e.global?.variables??{},...Br(e)?.variables??{}},runtime:ze(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:ze(e)}),Sl=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")},_l=(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")},$l=(e,t)=>{Sl(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(_l(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!Ze(n.when,Cl(e)))){Object.entries(n.actions).forEach(([i,s])=>{Xo(e,i,s)});return}}},Ol={conditional:{replayLine:$l},updateVariable:{recordSources:[Fr],replayLine:bo,replayRecorded:bo,persistInSaveSlot:!0},setNextLineConfig:{replayLine:xl(Go)}},Ut=e=>Ol[e]??null,Rl=e=>Ut(e)?.persistInSaveSlot===!0,Ll=(e,t)=>{let r=Ut(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},kl=(e,t,r)=>{Ut(t)?.replayRecorded?.(e,r)},Xo=(e,t,r)=>{Ut(t)?.replayLine?.(e,r)},Qo=({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}},Zo=({state:e})=>Qo({state:e},{offset:-1})!==null,Pl=({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=Pe(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:Do(e,i)},Tl=({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=Pe(o,{compatibilityAnchor:!o.rollback}),a=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===r&&c.lineId===n);if(a===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return a===i.currentIndex?e:Do(e,a)},ei=e=>{let t=gc(e);return Tn(t,{selectPendingEffects:bc,selectSkipMode:No,selectAutoMode:Ic,selectIsChoiceVisible:Fo,selectIsFormVisible:Ac,selectActiveInteraction:me,selectActiveForm:it,selectDialogueUIHidden:Vo,selectDialogueHistory:jo,selectConfirmDialog:wc,selectIsLineAccountViewed:Wr,selectIsResourceAccountViewed:xc,selectNextLineConfig:Cc,selectSystemState:Sc,selectSaveSlotMap:Uo,selectSaveSlots:kc,selectSaveSlot:_c,selectRuntime:qr,selectRuntimeValue:$c,selectAllVariables:Yr,selectCurrentPointer:ue,selectSection:X,selectCurrentLine:Kr,selectPresentationState:Bo,selectPresentationChanges:Oc,selectSectionLineChanges:Lc,selectSaveSlotPage:Hr,selectCurrentPageSlots:Pc,selectRenderState:Dc,selectOverlayStack:yc,selectLineIdByOffset:Qo,selectCanRollback:Zo,startAutoMode:Wo,stopAutoMode:st,toggleAutoMode:zc,startSkipMode:qo,stopSkipMode:ke,toggleSkipMode:Wc,showDialogueUI:Ft,hideDialogueUI:Yo,toggleDialogueUI:qc,setDialogueTextSpeed:Yc,setAutoForwardDelay:Kc,setSkipUnseenText:Hc,setSkipTransitionsAndAnimations:Jc,setSoundVolume:Gc,setMusicVolume:Xc,setMuteAll:Qc,setSaveLoadPagination:Zc,incrementSaveLoadPagination:el,decrementSaveLoadPagination:tl,setMenuPage:rl,setMenuEntryPoint:nl,showConfirmDialog:Nc,hideConfirmDialog:Vc,resetStoryAtSection:sl,clearPendingEffects:ol,appendPendingEffect:il,beginRollbackActionBatch:dc,endRollbackActionBatch:pc,addViewedLine:cl,addViewedResource:ll,setNextLineConfig:Go,saveSlot:ul,loadSlot:fl,updateProjectData:dl,sectionTransition:gl,jumpToLine:pl,nextLine:hl,markLineCompleted:ml,rollbackToLine:Tl,rollbackByOffset:Pl,pushOverlay:jc,popOverlay:Mc,replaceLastOverlay:Fc,clearOverlays:Uc,updateFormField:wl,submitForm:Al,cancelForm:vl,updateVariable:El,nextLineFromSystem:yl},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var Dl="route-engine",Nl="projectPersistence";var ri=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),J=e=>Object.prototype.toString.call(e)==="[object Object]",ti="variables.",Vl=(e={})=>{let t=J(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!J(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)}:!J(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},jl=(e={})=>{let t=J(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!J(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)}:!J(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Ml=(e,t)=>{let r=jl(e),n=Vl(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let a=o.find(c=>c.sectionId===s.sectionId);if(!a){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(a.lastLineId!==void 0){if(s.lineId===void 0){delete a.lastLineId;return}a.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(c=>c.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},ni=(e={})=>{let t=J(e)?e:{};return{saveSlots:J(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:J(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:J(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:J(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:J(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Fl=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!J(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(ti)?t.path.slice(ti.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}].`)})},Ul=(e,t)=>{let r={};return Fl(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=Ml(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},Xr=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},Bl=e=>{let t=Xr(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},zl=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},Wl=({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}".`))}}),ql=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let c=n.transaction(t,"readonly").objectStore(t).get(r);c.onsuccess=()=>{o(c.result??null)},c.onerror=()=>{i(c.error??new Error(`Failed to read persisted namespace "${r}" from IndexedDB.`))}})},ct=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let a=o.transaction(t,"readwrite"),c=a.objectStore(t),l=c.get(r),u=!1,f=p=>{u||(u=!0,s(p))},d=()=>{u||(u=!0,i())};l.onerror=()=>{f(l.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},l.onsuccess=()=>{let p=ni(l.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...ri(),...p,...h},y=c.put(g);y.onerror=()=>{f(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},a.oncomplete=()=>{d()},a.onerror=()=>{f(a.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},a.onabort=()=>{f(a.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},Yl=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let s=n.transaction(t,"readwrite"),c=s.objectStore(t).delete(r),l=!1,u=d=>{l||(l=!0,i(d))},f=()=>{l||(l=!0,o())};c.onerror=()=>{u(c.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{f()},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}".`))}})},Qr=(e={})=>{let{indexedDB:t,databaseName:r=Dl,objectStoreName:n=Nl,namespace:o}=e,i=zl(t),s=Bl(o),a=Wl({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let c=await ql({databasePromise:a,objectStoreName:n,namespace:s});return{...ri(),...ni(c)}},clear:async()=>Yl({databasePromise:a,objectStoreName:n,namespace:s}),saveSlots:async c=>ct({databasePromise:a,objectStoreName:n,namespace:s,patch:{saveSlots:J(c)?c:{}}}),saveGlobalDeviceVariables:async c=>ct({databasePromise:a,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:J(c)?c:{}}}),saveGlobalAccountVariables:async c=>ct({databasePromise:a,objectStoreName:n,namespace:s,patch:{globalAccountVariables:J(c)?c:{}}}),saveGlobalRuntime:async c=>ct({databasePromise:a,objectStoreName:n,namespace:s,patch:{globalRuntime:J(c)?c:{}}}),applyScopedDataUpdates:async c=>ct({databasePromise:a,objectStoreName:n,namespace:s,patch:l=>Ul(l,c)})}},Kl=Qr;var Hl=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Jl=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),oi="conditional",Zr="form",Gl=new Set(["submitForm","cancelForm"]),lt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function en(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:a}=e,c=(w=new Map,C=Date.now())=>new Map(Array.from(w.entries()).filter(([,$])=>C<$.expiresAt).map(([$,F])=>[$,{animation:structuredClone(F.animation),startedAt:F.startedAt,expiresAt:F.expiresAt}])),l=(w=new Map)=>Array.from(w.values()).map(C=>structuredClone(C.animation)),u=(w=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,C])=>w<C.expiresAt))},f=()=>{for(;t.selectPendingEffects().length>0;){let w=[...t.selectPendingEffects()];t.clearPendingEffects();try{a(w)}catch(C){throw t.clearPendingEffects(),w.forEach($=>{t.appendPendingEffect($)}),C}}},d=({initialState:w,namespace:C})=>{t=ei(w),r=0,n=Xr(C),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),f()},p=()=>n,h=()=>t.selectPresentationState(),g=()=>t.selectPresentationChanges(),y=w=>t.selectSectionLineChanges(w),I=(w={})=>{r+=1;let C=Date.now();u(C);let $=i.size>0,F=c(o,C),z=$?c(i,C):new Map,fe={...t.selectRenderState({activePersistentAnimations:l(F),restoredPersistentAnimations:l(z)}),id:`render-${r}`};return s.set(fe.id,{builtAt:C,persistentAnimationSessions:new Map([...z.entries(),...F.entries()]),usedRestoredPersistentAnimationSessions:$}),fe},A=(w={})=>I(w),x=(w={})=>I(w),b=w=>{let C=typeof w?.id=="string"&&w.id.length>0?w.id:null,$=C?s.get(C):null;C&&s.delete(C);let F=new Map;to(w?.animations).forEach(z=>{let ne=Rt(z);if(!ne)return;let fe=$?.persistentAnimationSessions?.get(ne)??o.get(ne),ft=Math.max(0,no(z)),on=fe?.startedAt??$?.builtAt??Date.now();F.set(ne,{animation:structuredClone(z),startedAt:on,expiresAt:on+ft})}),o=F,$?.usedRestoredPersistentAnimationSessions&&(i=new Map)},R=()=>t.selectSystemState(),L=()=>t.selectSaveSlotMap(),V=w=>t.selectSaveSlot(w),N=w=>t.selectSaveSlotPage(w),_=()=>t.selectSkipMode(),U=()=>t.selectAutoMode(),M=()=>t.selectRuntime(),P=()=>t.selectIsChoiceVisible(),B=()=>t.selectIsFormVisible(),E=()=>t.selectActiveInteraction(),S=(w,C,$={})=>w!=="nextLine"||!lt(C)?C:$.bypassChoice===!0?{...C,bypassChoice:!0}:$.interactionSource===Zr?{...C,_interactionSource:Zr}:C,j=(w,C)=>{if(!t[w])return;Hl.has(w)&&(Jl.has(w)?i=c(o):i=new Map,o=new Map);let $=t[w](C);return f(),$},q=(w,C,$,F={})=>{if(w===oi){let z=W($),ne=gr({[w]:C},z);rn(ne[w],$,F);return}j(w,C)},H=(w,C)=>{q(w,C)},W=w=>{if(!w)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(w,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:C,...$}=w,F=t.selectAllVariables?t.selectAllVariables():void 0;return{...$,_event:C,variables:F,runtime:t.selectRuntime?t.selectRuntime():{}}},ut=w=>{if(!lt(w))throw new Error("conditional action payload must be an object");if(!Array.isArray(w.branches))throw new Error("conditional action requires branches array");if(w.branches.length===0)throw new Error("conditional action requires at least one branch")},De=(w,C,$)=>{if(!lt(w))throw new Error(`conditional branch at index ${C} must be an object`);if(!lt(w.actions))throw new Error(`conditional branch at index ${C} requires actions object`);if(!Object.prototype.hasOwnProperty.call(w,"when")&&C!==$-1)throw new Error("conditional else branch must be the last branch")},rn=(w,C,$)=>{ut(w);for(let F=0;F<w.branches.length;F+=1){let z=w.branches[F];De(z,F,w.branches.length);let ne=W(C);if(!(Object.prototype.hasOwnProperty.call(z,"when")&&!Ze(z.when,ne))){zt(z.actions,C,$);return}}},ai=(w,C)=>({...w??{},_form:C}),ci=(w,C,$,F)=>{let z=j(w,C),ne=z?.submitted===!0&&z.valid===!0,fe=z?.cancelled===!0;!ne&&!fe||lt(C.actions)&&zt(C.actions,ai($,z.form),{...F,interactionSource:Zr})},li=(w,C,$,F)=>{let z=W($),fe=gr({[w]:C},z)[w];if(w===oi){rn(fe,$,F);return}let ft=S(w,fe,F);if(Gl.has(w)){ci(w,ft,$,F);return}j(w,ft)},zt=(w,C,$)=>{Object.entries(w).forEach(([F,z])=>{li(F,z,C,$)})},nn=(w,C,$={})=>{t.beginRollbackActionBatch({source:$.rollbackSource});try{zt(w,C,$)}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:q,handleInternalAction:H,handleActions:nn,selectRenderState:A,prepareRenderState:x,commitRenderState:b,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:R,selectSaveSlotMap:L,selectSaveSlot:V,selectSaveSlotPage:N,selectSaveSlots:L,selectRuntime:M,selectIsChoiceVisible:P,selectIsFormVisible:B,selectActiveInteraction:E,handleLineActions:()=>{let w=t.selectCurrentLine();return w?.actions?(nn(w.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var tn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},Xl=80,si=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},Ql=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&si({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},Zl=({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 a=n.delay??1e3;r.getElapsed()>=a&&(t.remove(i),r.setCallback(null),r.setElapsed(0),Bt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},eu=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},tu=({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 a=n?.delay??Xl;r.getElapsed()>=a&&(r.setElapsed(0),Bt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},ru=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},nu=({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 a=n.delay??1e3;r.getElapsed()>=a&&(r.setElapsed(0),Bt(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},ou=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},iu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},su=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},au=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},cu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},lu=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},ii={render:si,saveSlots:iu,saveGlobalDeviceVariables:su,saveGlobalAccountVariables:au,saveGlobalRuntime:cu,applyScopedDataUpdates:lu,handleLineActions:Ql,startAutoNextTimer:Zl,clearAutoNextTimer:eu,startSkipNextTimer:tu,clearSkipNextTimer:ru,nextLineConfigTimer:nu,clearNextLineConfigTimer:ou},uu=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Bt=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},fu=(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(!uu.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},du=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:a})=>{let c=tn(),l=tn(),u=tn(),f=s??null,d=Promise.resolve(),p=null,h=null,g=!1,y=0,I=E=>{if(o){o(E);return}console.error("RouteEngine persistence write failed.",E)},A=()=>{if(f)return f;let E=e();return f=Qr({indexedDB:i,namespace:a??E?.getNamespace?.()}),f},x=E=>{d=d.catch(()=>{}).then(()=>{let S=A();return E(S)}).catch(S=>{I(S)})},b=E=>{let S=typeof E?.id=="string"&&E.id.length>0?E.id:null;y+=1,p=S,g=!1},R=()=>y,L=(E={})=>{if(E?.aborted===!0)return!1;let S=typeof E?.id=="string"&&E.id.length>0?E.id:null;return S?S!==p||S===h?!1:(h=S,!0):p!==null||g?!1:(g=!0,!0)},V=(E,S={})=>{if(E!=="renderComplete"||!L(S))return!1;let j=e();return Bt(j,"markLineCompleted",{}),!0},N=E=>typeof E?.selectActiveInteraction=="function"?E.selectActiveInteraction():typeof E?.selectIsChoiceVisible=="function"&&E.selectIsChoiceVisible()?{source:"choice"}:null,_=(E,S)=>!(!E||typeof E!="object"||Array.isArray(E)||E._interactionSource!==S?.source||S.source==="form"&&E._formKey&&E._formKey!==S.formKey||S.source==="form"&&E.formKey&&E.formKey!==S.formKey),U=(E={},S)=>{if(_(E,S))return!0;let j=E?.actions;return!j||typeof j!="object"||Array.isArray(j)?!1:Object.values(j).some(q=>_(q,S))},M=(E,S={})=>{if(!S?.actions)return!1;let j=N(E);return!j||j.source==="choice"?!1:!U(S,j)},P=({preprocessPayload:E,onEvent:S}={})=>async(j,q={})=>{let H=e();if(M(H,q))return S?.(j,q);let W=await E?.(j,q)??q;if(M(H,W))return S?.(j,W);if(V(j,W),W?.actions){let ut=W?._event?{_event:W._event}:W?.event?{_event:W.event}:void 0,De;W?.bypassChoice===!0?De={bypassChoice:!0}:W?._interactionSource&&(De={interactionSource:W._interactionSource}),De?H.handleActions(W.actions,ut,De):H.handleActions(W.actions,ut)}return S?.(j,W)},B=E=>{let S=e(),j=fu(E);j.forEach(H=>{if(!ii[H.name]&&!n)throw new Error(`Unhandled pending effect "${H.name}".`)});let q={engine:S,routeGraphics:t,ticker:r,autoTimer:c,skipTimer:l,nextLineConfigTimerState:u,trackRenderDispatch:b,getRenderDispatchCount:R,enqueuePersistenceWrite:x};for(let H of j){let W=ii[H.name];if(W){W(q,H.payload);continue}n(H,q)}};return B.handleRouteGraphicsEvent=V,B.createRouteGraphicsEventHandler=P,B},pu=du;var hu=(e,t={})=>{let{resources:r={}}=t;return Pr(e,r)};var Lf=en;export{pu as createEffectsHandler,Kl as createIndexedDbPersistence,Lf as default,gs as resolveComputedVariables,hu as resolveLayoutReferences};
1
+ var pi=Object.defineProperty;var hi=(e,t)=>{for(var r in t)pi(e,r,{get:t[r],enumerable:!0})};var dn=Symbol.for("immer-nothing"),an=Symbol.for("immer-draftable"),ee=Symbol.for("immer-state");function ie(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Ve=Object.getPrototypeOf;function te(e){return!!e&&!!e[ee]}function Se(e){return e?pn(e)||Array.isArray(e)||!!e[an]||!!e.constructor?.[an]||yt(e)||bt(e):!1}var mi=Object.prototype.constructor.toString();function pn(e){if(!e||typeof e!="object")return!1;let t=Ve(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)===mi}function pt(e,t){gt(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function gt(e){let t=e[ee];return t?t.type_:Array.isArray(e)?1:yt(e)?2:bt(e)?3:0}function Kt(e,t){return gt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function hn(e,t,r){let n=gt(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function gi(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function yt(e){return e instanceof Map}function bt(e){return e instanceof Set}function Ce(e){return e.copy_||e.base_}function Ht(e,t){if(yt(e))return new Map(e);if(bt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=pn(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[ee];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],a=n[s];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(n[s]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[s]})}return Object.create(Ve(e),n)}else{let n=Ve(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function Zt(e,t=!1){return It(e)||te(e)||!Se(e)||(gt(e)>1&&(e.set=e.add=e.clear=e.delete=yi),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>Zt(n,!0))),e}function yi(){ie(2)}function It(e){return Object.isFrozen(e)}var bi={};function _e(e){let t=bi[e];return t||ie(0,e),t}var Je;function mn(){return Je}function Ii(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function cn(e,t){t&&(_e("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Jt(e){Gt(e),e.drafts_.forEach(wi),e.drafts_=null}function Gt(e){e===Je&&(Je=e.parent_)}function ln(e){return Je=Ii(Je,e)}function wi(e){let t=e[ee];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function un(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[ee].modified_&&(Jt(t),ie(4)),Se(e)&&(e=ht(t,e),t.parent_||mt(t,e)),t.patches_&&_e("Patches").generateReplacementPatches_(r[ee].base_,e,t.patches_,t.inversePatches_)):e=ht(t,r,[]),Jt(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==dn?e:void 0}function ht(e,t,r){if(It(t))return t;let n=t[ee];if(!n)return pt(t,(o,i)=>fn(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return mt(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),pt(i,(a,c)=>fn(e,n,o,a,c,r,s)),mt(e,o,!1),r&&e.patches_&&_e("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function fn(e,t,r,n,o,i,s){if(te(o)){let a=i&&t&&t.type_!==3&&!Kt(t.assigned_,n)?i.concat(n):void 0,c=ht(e,o,a);if(hn(r,n,c),te(c))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(Se(o)&&!It(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;ht(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&mt(e,o)}}function mt(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Zt(t,r)}function Ai(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:mn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=er;r&&(o=[n],i=Ge);let{revoke:s,proxy:a}=Proxy.revocable(o,i);return n.draft_=a,n.revoke_=s,a}var er={get(e,t){if(t===ee)return e;let r=Ce(e);if(!Kt(r,t))return vi(e,r,t);let n=r[t];return e.finalized_||!Se(n)?n:n===qt(e.base_,t)?(Yt(e),e.copy_[t]=Qt(n,e)):n},has(e,t){return t in Ce(e)},ownKeys(e){return Reflect.ownKeys(Ce(e))},set(e,t,r){let n=gn(Ce(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=qt(Ce(e),t),i=o?.[ee];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(gi(r,o)&&(r!==void 0||Kt(e.base_,t)))return!0;Yt(e),Xt(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 qt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Yt(e),Xt(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Ce(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){ie(11)},getPrototypeOf(e){return Ve(e.base_)},setPrototypeOf(){ie(12)}},Ge={};pt(er,(e,t)=>{Ge[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Ge.deleteProperty=function(e,t){return Ge.set.call(this,e,t,void 0)};Ge.set=function(e,t,r){return er.set.call(this,e[0],t,r,e[0])};function qt(e,t){let r=e[ee];return(r?Ce(r):e)[t]}function vi(e,t,r){let n=gn(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function gn(e,t){if(!(t in e))return;let r=Ve(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=Ve(r)}}function Xt(e){e.modified_||(e.modified_=!0,e.parent_&&Xt(e.parent_))}function Yt(e){e.copy_||(e.copy_=Ht(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Ei=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(c=i,...l){return s.produce(c,u=>r.call(this,u,...l))}}typeof r!="function"&&ie(6),n!==void 0&&typeof n!="function"&&ie(7);let o;if(Se(t)){let i=ln(this),s=Qt(t,void 0),a=!0;try{o=r(s),a=!1}finally{a?Jt(i):Gt(i)}return cn(i,n),un(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===dn&&(o=void 0),this.autoFreeze_&&Zt(o,!0),n){let i=[],s=[];_e("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else ie(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...a)=>this.produceWithPatches(s,c=>t(c,...a));let n,o;return[this.produce(t,r,(s,a)=>{n=s,o=a}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Se(e)||ie(8),te(e)&&(e=$e(e));let t=ln(this),r=Qt(e,void 0);return r[ee].isManual_=!0,Gt(t),r}finishDraft(e,t){let r=e&&e[ee];(!r||!r.isManual_)&&ie(9);let{scope_:n}=r;return cn(n,t),un(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=_e("Patches").applyPatches_;return te(e)?n(e,t):this.produce(e,o=>n(o,t))}};function Qt(e,t){let r=yt(e)?_e("MapSet").proxyMap_(e,t):bt(e)?_e("MapSet").proxySet_(e,t):Ai(e,t);return(t?t.scope_:mn()).drafts_.push(r),r}function $e(e){return te(e)||ie(10,e),yn(e)}function yn(e){if(!Se(e)||It(e))return e;let t=e[ee],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=Ht(e,t.scope_.immer_.useStrictShallowCopy_)}else r=Ht(e,!0);return pt(r,(n,o)=>{hn(r,n,yn(o))}),t&&(t.finalized_=!1),r}var re=new Ei,tr=re.produce,Au=re.produceWithPatches.bind(re),vu=re.setAutoFreeze.bind(re),Eu=re.setUseStrictShallowCopy.bind(re),xu=re.applyPatches.bind(re),Cu=re.createDraft.bind(re),Su=re.finishDraft.bind(re);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},je={NOT:0};var v=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},Q=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var rr=e=>{if(!e||e.trim()==="")throw new v("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new v(`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 v(`Incomplete comparison expression - missing right operand (got: '${e}')`)},bn=e=>{if(e.trim().endsWith(" in"))throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new v(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new v(`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 v(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new v(`Invalid loop syntax (got: '$for ${e}')`)}};var In=(e,t,r=!1)=>{if(t===null)return new Q(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new Q(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new Q(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new Q(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},wn=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new Q(`Unknown function '${e}' (${r})`)};var xi=(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=k(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},k=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return Y(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return Y(e.path,r,n);if(e.type===m.INTERPOLATION)return Si(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return vn(e,t,r,n);case m.BINARY:return En(e,t,r,n);case m.UNARY:return xn(e,t,r,n);case m.CONDITIONAL:return $i(e,t,r,n);case m.LOOP:return Pi(e,t,r,n);case m.OBJECT:return Di(e,t,r,n);case m.ARRAY:return Ni(e,t,r,n);case m.PARTIAL:return Vi(e,t,r,n);case m.PATH_REFERENCE:return ji(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},An=new Map,Ci=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 a=s.slice(1,-1);t.push({type:"property",value:a})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},Y=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=An.get(e);if(!n){let i=[],s="",a=0;for(let c=0;c<e.length;c++){let l=e[c];l==="["?(a++,s+=l):l==="]"?(a--,s+=l):l==="."&&a===0?s&&(i.push(s),s=""):s+=l}s&&i.push(s),n=[];for(let c of i){let l=Ci(c.trim());n.push(...l)}An.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},Si=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=k(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},vn=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw wn(e.name,o);let s=e.args.map(a=>k(a,t,r,n));return i(...s)},be=(e,t,r,n)=>{if(e.var&&!e.type)return Y(e.var,r,n);switch(e.type){case m.VARIABLE:return Y(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return En(e,t,r,n);case m.UNARY:return xn(e,t,r,n);case m.FUNCTION:return vn(e,t,r,n);default:return k(e,t,r,n)}},En=(e,t,r,n)=>{if(e.op===O.AND||e.op===O.OR){let s=be(e.left,t,r,n),a=be(e.right,t,r,n);switch(e.op){case O.AND:return s&&a;case O.OR:return s||a}}let o=k(e.left,t,r,n),i=k(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 Q(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case O.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new Q(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},xn=(e,t,r,n)=>{let o=e.op===je.NOT?be(e.operand,t,r,n):k(e.operand,t,r,n);if(e.op===je.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},_i=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(Y(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?k(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)a[l]=u.value;else if(u.type===m.VARIABLE)a[l]=Y(u.path,r,n);else if(u.type===m.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===m.VARIABLE){let p=Y(d.path,r,n);f.push(p!=null?String(p):"")}else{let p=k(d,t,r,n);f.push(p!=null?String(p):"")}a[l]=f.join("")}else a[l]=k(u,t,r,n)}return a}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?k(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)a[l]=u.value;else if(u.type===m.VARIABLE)a[l]=Y(u.path,r,n);else if(u.type===m.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===m.VARIABLE){let p=Y(d.path,r,n);f.push(p!=null?String(p):"")}else{let p=k(d,t,r,n);f.push(p!=null?String(p):"")}a[l]=f.join("")}else a[l]=k(u,t,r,n)}return a}}}return null},$i=(e,t,r,n)=>{let o=_i(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||be(s,t,r,n))return k(e.bodies[i],t,r,n)}return Cn},Oi=(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 c of i.properties)if(c.parsedKey)return null;let a=[];for(let c=0;c<t.length;c++){let l=t[c];if(l[s]){let u={};for(let f of i.properties){let d=f.key,p=f.value;if(p.type===m.LITERAL)u[d]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)u[d]=l;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);u[d]=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 I=y.path;if(I===n)h.push(l!=null?String(l):"");else if(I.startsWith(n+".")){let A=I.substring(n.length+1),x=l[A];h.push(x!=null?String(x):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[d]=h.join("")}else return null}a.push(u)}}return a}}}return null},Ri=(e,t)=>{let r=e.body,n=e.itemVar,o=Oi(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let a of r.properties)if(a.parsedKey)return null;let i=[],s=!0;for(let a of r.properties){let c=a.key,l=a.value;if(l.type===m.LITERAL)i.push({key:c,type:"literal",value:l.value});else if(l.type===m.VARIABLE){let u=l.path;if(u===n)i.push({key:c,type:"item"});else if(u.startsWith(n+".")){let f=u.substring(n.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(l.type===m.INTERPOLATION&&l.parts.length===1){let u=l.parts[0];if(u.type===m.VARIABLE){let f=u.path;if(f===n)i.push({key:c,type:"item_string"});else if(f.startsWith(n+".")){let d=f.substring(n.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let a=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let l=t[c];a[c]={id:l.id,title:l.title!=null?String(l.title):"",completed:l.completed}}else for(let c=0;c<t.length;c++){let l=t[c],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=l;else if(f.type==="prop")u[f.key]=l[f.prop];else if(f.type==="item_string")u[f.key]=l!=null?String(l):"";else if(f.type==="prop_string"){let d=l[f.prop];u[f.key]=d!=null?String(d):""}a[c]=u}return a}}return null},Li=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let a=e.itemVar,c=e.indexVar;for(let l=0;l<o.length;l++){let u=o[l],f={},d={...n,[a]:u,...c&&{[c]:l}};d.__paths__||(d.__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(".")))}d.__paths__={...d.__paths__,[a]:`${p}[${l}]`,...c&&{[c]:l}};for(let h of s.properties){let g=h.parsedKey?k(h.parsedKey,t,r,d):h.key,y=h.value;if(y.type===m.LITERAL)f[g]=y.value;else if(y.type===m.VARIABLE){let I=y.path;if(I===a)f[g]=u;else if(I===c)f[g]=l;else if(I.startsWith(a+".")){let A=I.substring(a.length+1);!A.includes(".")&&!A.includes("[")?f[g]=u[A]:f[g]=Y(I,r,{...n,[a]:u,...c&&{[c]:l}})}else f[g]=Y(I,r,{...n,[a]:u,...c&&{[c]:l}})}else if(y.type===m.INTERPOLATION){let I=[];for(let A of y.parts)if(typeof A=="string")I.push(A);else if(A.type===m.VARIABLE){let x=A.path,b;if(x===a)b=u;else if(x===c)b=l;else if(x.startsWith(a+".")){let R=x.substring(a.length+1);!R.includes(".")&&!R.includes("[")?b=u[R]:b=Y(x,r,{...n,[a]:u,...c&&{[c]:l}})}else b=Y(x,r,{...n,[a]:u,...c&&{[c]:l}});I.push(b!=null?String(b):"")}else{let x={...n,[a]:u,...c&&{[c]:l}},b=k(A,t,r,x);I.push(b!=null?String(b):"")}f[g]=I.join("")}else{let I={...n,[a]:u,...c&&{[c]:l}};f[g]=k(y,t,r,I)}}i.push(f)}return i}return null},ki=(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 a=s.properties[0],c=s.properties[1];if(a.key==="id"&&a.value.type===m.VARIABLE&&a.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===m.CONDITIONAL){let l=[];for(let u=0;u<t.length;u++){let f=t[u];if(f.visible){let d={id:f.id};f.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${f.name}`):(d.highlight=!1,d.message=f.name),l.push(d)}}return l}}}}return null},Pi=(e,t,r,n)=>{let o=k(e.iterable,t,r,n);if(!Array.isArray(o)){let l,u=!1;if(e.iterable.type===m.FUNCTION){u=!0;let d=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}(${d})`}else l=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw In(f,o,u)}if(!e.indexVar){let l=ki(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=Ri(e,o);if(l!==null)return l}let i=Li(e,t,r,n,o);if(i!==null)return i;let s=[],a=e.iterable.path||"";if(n&&n.__paths__&&a){let l=a.split("."),u=l[0];u in n.__paths__&&(a=n.__paths__[u],l.length>1&&(a+="."+l.slice(1).join(".")))}let c=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(l=>l.type===m.OBJECT&&l.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let l=0;l<o.length;l++){let u=e.indexVar?{...n,[e.itemVar]:o[l],[e.indexVar]:l}:{...n,[e.itemVar]:o[l]};u.__paths__||(u.__paths__=n.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${a}[${l}]`},e.indexVar&&(u.__paths__[e.indexVar]=l);let f=k(e.body,t,r,u);if(Array.isArray(f)&&f.length===1&&!c){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},Ti=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?k(o.parsedKey,t,r,n):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let a={},c={},l=!0;for(let u of s.properties){let f=u.parsedKey?k(u.parsedKey,t,r,n):u.key,d=u.value;if(d.type===m.LITERAL)c[f]=d.value;else if(d.type===m.VARIABLE)c[f]=Y(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=Y(h.path,r,n);p.push(g!=null?String(g):"")}else{l=!1;break}if(!l)break;c[f]=p.join("")}else if(d.type===m.OBJECT&&d.properties.length<=5){let p={};for(let h of d.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]=Y(y.path,r,n);else if(y.type===m.INTERPOLATION){let I=[];for(let A of y.parts)if(typeof A=="string")I.push(A);else if(A.type===m.VARIABLE){let x=Y(A.path,r,n);I.push(x!=null?String(x):"")}else{l=!1;break}if(!l)break;p[g]=I.join("")}else{l=!1;break}}if(!l)break;c[f]=p}else{l=!1;break}}if(l)return a[i]=c,a}}return null},Di=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!be(e.whenCondition,o,r,n))return;let i=Ti(e,t,r,n);if(i!==null)return i;if(e.fast){let l={};for(let u of e.properties){let f=u.parsedKey?k(u.parsedKey,t,r,n):u.key,d=u.value;if(d.type===m.LITERAL)l[f]=d.value;else if(d.type===m.VARIABLE)l[f]=Y(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=Y(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=k(h,t,r,n);p.push(g!=null?String(g):"")}l[f]=p.join("")}else l[f]=k(d,t,r,n)}return l}let s={},a=null,c=!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 ")){c=!0;break}for(let l of e.properties)if(l.key.startsWith("$if ")||l.key.match(/^\$if\s+\w+.*:?$/)){let u=k(l.value,t,r,n);if(!c&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(l.key.startsWith("$for ")){if(e.properties.length===1)return k(l.value,t,r,n)}else{let u=l.value;if(u&&u.type===m.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=k(f.value,t,r,n);d!==void 0&&(s[l.key]=d)}else{let d=k(l.value,t,r,n);d!==void 0&&(s[l.key]=d)}}else{let f=l.parsedKey?k(l.parsedKey,t,r,n):l.key,d=k(l.value,t,r,n);d!==void 0&&(s[f]=d)}}return s},Cn={},Ni=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=k(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=k(i,t,r,n);s!==Cn&&s!==void 0&&o.push(s)}return o},Vi=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,a=t.partials||{},c=t.functions||t;if(s&&!be(s,c,r,n))return;if(!a[o])throw new Q(`Partial '${o}' is not defined`);let l=n._partialStack||[];if(l.includes(o))throw new Q(`Circular partial reference detected: ${o}`);let u=a[o],f=r,d={...n,_partialStack:[...l,o]};if(n){f={...r};for(let p of Object.keys(n))p.startsWith("_")||(f[p]=n[p])}if(i){let p=k(i,t,r,n);f={...f,...p}}return k(u,t,f,d)},ji=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],a=i.slice(1);if(!n||!(s in n))throw new Q(`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 Q(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=n.__paths__[s];if(typeof c=="number"){if(a.length>0)throw new Q(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return a.length>0&&(c+="."+a.join(".")),c};var nr=xi;var Mi=/\$\{([^}]*)\}/g,Fi=/#\{([^}]*)\}/g,_n=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=Ui(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},Ui=(e,t={})=>e.trim()?Bi(e).map(n=>zi(n.trim(),t)):[],Bi=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let a=e[s],c=s>0?e[s-1]:"";!o&&(a==='"'||a==="'")?(o=!0,i=a,r+=a):o&&a===i&&c!=="\\"?(o=!1,i="",r+=a):!o&&a==="("?(n++,r+=a):!o&&a===")"?(n--,r+=a):!o&&a===","&&n===0?(t.push(r),r=""):r+=a}return r&&t.push(r),t},zi=(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=_n(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:a,type:c}of o){let l=0;for(;l<n.length;){let u=Oe(n.substring(l),a);if(u===-1)break;let f=l+u;f>i&&(i=f,s={op:a,type:c}),l=f+a.length}}if(i!==-1)try{return K(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},$n=/^\w+\(.*\)$/,Wi=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,qi=e=>{if(!(!e||e.trim()===""||$n.test(e))&&Wi.test(e))throw e.includes("?")&&e.includes(":")?new v(`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 v(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new v(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Sn=e=>{let t=e.trim();if($n.test(t))throw new v(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new v(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new v(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new v(`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 v(`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}},Xe=(e,t={})=>{let r=e.trim();qi(r);let n=_n(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}},or=(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,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\(#\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(Mi)],i=[...r.matchAll(Fi)],s=[...o.map(l=>({match:l,type:"variable"})),...i.map(l=>({match:l,type:"pathref"}))].sort((l,u)=>l.match.index-u.match.index);if(s.length===0){let l=r;for(let u=0;u<n.length;u++)l=l.replace(`__ESCAPED_${u}__`,n[u]);return{type:m.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:l,type:u}=s[0];try{return u==="variable"?Xe(l[1],t):Sn(l[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw f}}let a=[],c=0;for(let{match:l,type:u}of s){let[f,d]=l,p=l.index;if(p>c){let h=r.substring(c,p);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&a.push(h)}try{let h;u==="variable"?h=Xe(d.trim(),t):h=Sn(d.trim()),a.push(h)}catch(h){if(h.message==="Invalid array index syntax")a.push(f);else throw h}c=p+f.length}if(c<r.length){let l=r.substring(c);for(let u=0;u<n.length;u++)l=l.replace(`__ESCAPED_${u}__`,n[u]);l&&a.push(l)}return{type:m.INTERPOLATION,parts:a}};var ar=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ln=e=>Object.keys(e),G=e=>e.join("."),Ie=(e,t,r)=>{let n=Ln(e).filter(o=>!t.has(o));if(n.length>0)throw new v(`Unexpected key '${n[0]}' in condition JSON at '${G(r)}'`)},we=(e,t)=>typeof e=="string"?or(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Ki(e,t):Hi(e,t):{type:m.LITERAL,value:e},Yi=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new v("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new v("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new v("Empty $each body not allowed");if(r.$partial!==void 0)throw new v("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${n}`]:r}},Ki=(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 c=Yi(i),l=Object.keys(c);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let u=Rn(l[0],c[l[0]],t,!0);r.push(u),n=!0;continue}}catch(c){throw c instanceof v?c:new v(c.message)}let a=Object.keys(i);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let c=Rn(a[0],i[a[0]],t);r.push(c),n=!0;continue}}let s=we(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}},Hi=(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 v("$partial value must be a string");if(e.$partial.trim()==="")throw new v("$partial value cannot be an empty string");let c=["$if","$elif","$else","$for"],l=[];for(let[I]of i)for(let A of c)if(I===A||I.startsWith(A+" ")||I.startsWith(A+"#")){l.push(A);break}if(l.length>0)throw new v(`Cannot use $partial with ${l.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...d}=e,p={},h=!1;for(let[I,A]of Object.entries(d)){let x=I;(I.startsWith("\\$")||I.startsWith("$$"))&&(x=I.slice(1)),p[x]=A,h=!0}let g=null;if(h&&(g=we(p,t),g.type===m.OBJECT)){let I=!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){I=!0;break}I&&(g.fast=!1)}let y={type:m.PARTIAL,name:u,data:g};return f!==void 0&&(y.whenCondition=On(f,t)),y}for(let[c,l]of i)if(c==="$when"){if(o!==null)throw new v("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new v("Missing condition expression after '$when'");o=On(l,t),n=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new v("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[c,l]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new v("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=Ji(i,s,t);r.push({key:c,value:u.node}),n=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(c)){let u=c.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new v(`$for loops must be inside arrays - use '- $for${f} item in items:' instead of '$for${f} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(c.startsWith("$elif ")||c.startsWith("$else"))throw new v(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new v("Missing condition expression after '$if'");{let u=we(l,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 f=or(c,t),d={key:c,value:u};(f.type!==m.LITERAL||f.value!==c)&&(d.parsedKey=f),r.push(d),s++}}}let a={type:m.OBJECT,properties:r,fast:!n};return o&&(a.whenCondition=o),a},Ji=(e,t,r={})=>{let n=[],o=[],i=t,[s,a]=e[i],c=null,l;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=f[1],l=f[2];else throw new v(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());rr(l);let u=K(l,r);for(n.push(u),o.push(we(a,r)),i++;i<e.length;){let[f,d]=e[i],p=!1,h;if(c?f.startsWith(`$elif#${c} `)?(h=f.substring(`$elif#${c} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f===`$else#${c}`||f===`$else#${c}:`)&&(p=!0,h=null):f.startsWith("$elif ")?(h=f.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f==="$else"||f==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{rr(h);let g=K(h,r);n.push(g)}if(o.push(we(d,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:c},nextIndex:i}},ir={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},sr={all:O.AND,any:O.OR},Gi=new Set(["var","literal","call","not",...Object.keys(ir),...Object.keys(sr)]),Xi=(e,t,r)=>{if(!Array.isArray(e))throw new v(`Condition JSON operator '${t}' at '${G(r)}' requires an array`);if(e.length!==2)throw new v(`Condition JSON operator '${t}' at '${G(r)}' requires exactly 2 operands`);return e},Qi=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new v(`Condition JSON operator '${t}' at '${G(o)}' requires an array`);if(e.length===0)throw new v(`Condition JSON operator '${t}' at '${G(o)}' requires at least 1 condition`);return e.map((s,a)=>de(s,n,[...o,a])).reduce((s,a)=>({type:m.BINARY,op:r,left:s,right:a}))},Zi=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],Ie(e,new Set(["call","args"]),r);else if(ar(e.call))n=e.call.name,o=e.call.args??[],Ie(e,new Set(["call"]),r),Ie(e.call,new Set(["name","args"]),[...r,"call"]);else throw new v(`Condition JSON call at '${G(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new v(`Condition JSON call at '${G(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new v(`Invalid condition JSON function name '${n}' at '${G(r)}'`);if(!Array.isArray(o))throw new v(`Condition JSON call '${n}' at '${G(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>de(i,t,[...r,"args",s]))}},de=(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 v(`Condition JSON array at '${G(r)}' must be wrapped in an operator or { literal: [...] }`);if(!ar(e))throw new v(`Invalid condition JSON value at '${G(r)}'`);let n=Ln(e);if(n.length===0)throw new v(`Condition JSON object at '${G(r)}' must contain an operator`);let o=n.filter(s=>Gi.has(s));if(o.length===0)throw new v(`Unknown condition JSON operator '${n[0]}' at '${G(r)}'`);if(o.length>1)throw new v(`Condition JSON at '${G(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(Ie(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new v(`Condition JSON var at '${G(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return Ie(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return Zi(e,t,r);if(i==="not")return Ie(e,new Set(["not"]),r),{type:m.UNARY,op:je.NOT,operand:de(e.not,t,[...r,"not"])};if(i in sr)return Ie(e,new Set([i]),r),Qi(e[i],i,sr[i],t,[...r,i]);if(i in ir){Ie(e,new Set([i]),r);let s=Xi(e[i],i,[...r,i]);return{type:m.BINARY,op:ir[i],left:de(s[0],t,[...r,i,0]),right:de(s[1],t,[...r,i,1])}}throw new v(`Unknown condition JSON operator '${i}' at '${G(r)}'`)},On=(e,t={})=>{if(e==null)throw new v("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new v("Empty condition expression after '$when'");return K(e,t)}return ar(e)||Array.isArray(e)?de(e,t):{type:m.LITERAL,value:e}},K=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let l=e.slice(1,-1),u=0,f=!0;for(let d=0;d<l.length;d++)if(l[d]==="("?u++:l[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return K(l,t)}let r=Oe(e,"||");if(r!==-1)return{type:m.BINARY,op:O.OR,left:K(e.substring(0,r).trim(),t),right:K(e.substring(r+2).trim(),t)};let n=Oe(e,"&&");if(n!==-1)return{type:m.BINARY,op:O.AND,left:K(e.substring(0,n).trim(),t),right:K(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:u}of o){let f=Oe(e,l);if(f!==-1)return{type:m.BINARY,op:u,left:K(e.substring(0,f).trim(),t),right:K(e.substring(f+l.length).trim(),t)}}let i=-1,s=null,a=[{op:" + ",type:O.ADD},{op:" - ",type:O.SUBTRACT}];for(let{op:l,type:u}of a){let f=0;for(;f<e.length;){let d=Oe(e.substring(f),l);if(d===-1)break;let p=f+d;p>i&&(i=p,s={op:l,type:u}),f=p+l.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:K(e.substring(0,i).trim(),t),right:K(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let l of c)if(Oe(e,l)!==-1)throw new v(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:m.UNARY,op:je.NOT,operand:K(e.substring(1).trim(),t)}:kn(e,t)},Oe=(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},es=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}},kn=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return Xe(r,t);let o=es(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return Xe(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},ts=(e,t=!1)=>{let r=t?"$each":"$for";try{bn(e)}catch(n){if(n instanceof v&&t){let o=n.message.replace(/\$for/g,"$each");throw new v(o.replace("Parse Error: ",""))}throw n}},Rn=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new v(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],a=i[2].trim();ts(a,n);let c=a.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let y=n?"$each":"$for";throw new v(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${a}')`)}let l=c[1].trim(),u=c[2].trim(),f,d=null;if(l.includes(",")){let y=l.split(",").map(I=>I.trim());if(y.length!==2)throw new v(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);f=y[0],d=y[1]}else f=l;let p=["this","undefined","null","true","false"];if(p.includes(f))throw new v(`Reserved variable name: ${f}`);if(d&&p.includes(d))throw new v(`Reserved variable name: ${d}`);let h=kn(u,r),g=we(t,r);return{type:m.LOOP,itemVar:f,indexVar:d,iterable:h,body:g,flatten:s!=="nested"}};var rs=(e,t={})=>{let{functions:r={}}=t;return we(e,r)},wt=rs;var Qe={};hi(Qe,{now:()=>ns});var ns=()=>Date.now();var os=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...Qe,...n},s=wt(e,{functions:i}),a={};for(let[c,l]of Object.entries(o))a[c]=wt(l,{functions:i});return nr(s,t,{functions:i,partials:a})},Z=os;var is=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",ss=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,as=(e,t)=>{if(is(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new v("Empty condition expression");return K(e,t)}return de(e,t)},cs=(e,t={},r={})=>{let n=ss(r),o={...Qe,...n},i=as(e,o);return!!be(i,{functions:o,partials:{}},t,{})},cr=cs;var et=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return cr(e,t)},Dn=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:a=c=>c}=r;for(let[c,l]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>l(s(n),...u):i[c]=(...u)=>{let f;return n=tr(n,p=>{let h=l(a(p),...u);f=h!==void 0&&!te(h)?h:void 0}),f});return{...o,...i}},Et=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return tr(n,i=>{o.forEach(s=>{t.forEach(a=>{a(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{}}},ae=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),Ze=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Nn=e=>{let t=te(e)?$e(e):e;return structuredClone(t)},Ae=e=>ae(e,"computed"),Me=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Ae(t[r]))),us=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),lr=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},fs=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=us(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 lr(s,i)}return n==="runtime"?lr(t.runtime,r.slice(1)):lr(t,r)},ds=(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)`)},Pn=(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`)},ps=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},se=(e,t,r,n)=>(ds(e,t,n),t.map(o=>vt(o,r))),oe=(e,t,r,n)=>{let o=se(e,t,r,n);return o.forEach(i=>ps(e,i)),o},hs=(e,t,r)=>{switch(e){case"var":return fs(t,r);case"add":{let[n,o]=oe(e,t,r,2);return n+o}case"sub":{let[n,o]=oe(e,t,r,2);return n-o}case"mul":{let[n,o]=oe(e,t,r,2);return n*o}case"div":{let[n,o]=oe(e,t,r,2);return n/o}case"mod":{let[n,o]=oe(e,t,r,2);return n%o}case"neg":{let[n]=oe(e,t,r,1);return-n}case"round":{let[n]=oe(e,t,r,1);return Math.round(n)}case"floor":{let[n]=oe(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=oe(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=oe(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=oe(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=oe(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=se(e,t,r,2);return n==o}case"neq":{let[n,o]=se(e,t,r,2);return n!=o}case"gt":{let[n,o]=se(e,t,r,2);return n>o}case"gte":{let[n,o]=se(e,t,r,2);return n>=o}case"lt":{let[n,o]=se(e,t,r,2);return n<o}case"lte":{let[n,o]=se(e,t,r,2);return n<=o}case"in":{let[n,o]=se(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return Pn(e,t),t.every(n=>!!vt(n,r));case"or":case"any":return Pn(e,t),t.some(n=>!!vt(n,r));case"not":{let[n]=se(e,t,r,1);return!n}case"length":{let[n]=se(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:Ze(n)?Object.keys(n).length:0}case"includes":{let[n,o]=se(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return Nn(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},vt=(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 hs(n,o,t)},ms=(e,t={})=>et(e,{variables:t.variables,runtime:t.runtime}),gs=(e,t)=>{if(!Ze(e))throw new Error(`${t} must be an object`);let r=ae(e,"expr"),n=ae(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},ur=(e,t,r)=>(gs(e,t),ae(e,"value")?Nn(e.value):vt(e.expr,r)),ys=(e,t={},r="unknown")=>{if(!Ze(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=ae(e,"expr"),o=ae(e,"value");if(ae(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(!Ze(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let a=e.branches[s];if(!Ze(a))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!ae(a,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(ms(a.when,t))return ur(a,`Computed variable "${r}" branch ${s}`,t)}return ur(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 ur(e,`Computed variable "${r}"`,t)},bs=(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}`)}},xt=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=Me(e,r),i=Object.entries(r).filter(([,f])=>Ae(f)).map(([f])=>f),s={},a=[],c=f=>{if(ae(s,f))return s[f];let d=r[f];if(!Ae(d))return o[f];let p=a.indexOf(f);if(p>=0){let h=[...a.slice(p),f].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}a.push(f);try{let h=ys(d.computed,u,f);return bs(f,d.type,h),s[f]=h,h}finally{a.pop()}},l=new Proxy({},{get:(f,d)=>{if(typeof d=="string")return c(d)},has:(f,d)=>typeof d=="string"&&(ae(o,d)||i.includes(d)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(f,d)=>{if(!(typeof d!="string"||!ae(o,d)&&!i.includes(d)))return{enumerable:!0,configurable:!0}}}),u={variables:l,runtime:t,resolveVariable:c};return n?(i.forEach(f=>{c(f)}),{...o,...s}):l},Is=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>xt({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),pr=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(Ae(o))return;let i=ls(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},Ct=(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(", ")}`)},St=(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(", ")}`)},ws=2,Tn=12,Vn=(e=ws)=>{if(!Number.isInteger(e)||e<0||e>Tn)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${Tn}.`);return e},As=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},At=e=>typeof e=="number"&&Number.isFinite(e),hr=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!At(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!At(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!At(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}".`);Vn(o.roundTo)}}},_t=(e,t,r,n={})=>{let o=(s,a,c)=>{let l=s??a;if(!At(l))throw new Error(`Operation "${t}" requires ${c} to be a number.`);return l},i=s=>{let a=o(s,void 0,"value");if(a===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return a};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return As(o(e,0,"current value")/i(r),Vn(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 jn=(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()))},vs=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let a=i.character?.sprite;return a&&Object.keys(a).length>0&&(s.sprite=a),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},mr=(e={},t={})=>{let r={},n=["sfx","voice"],o=s=>{let a=e[s],c=t[s];c&&!a?r[s]={changeType:"add",data:c}:a&&!c?n.includes(s)||(r[s]={changeType:"delete",data:a}):a&&c&&JSON.stringify(a)!==JSON.stringify(c)&&(r[s]={changeType:"update",data:c})};o("background"),o("bgm"),o("voice");let i=vs(e.dialogue,t.dialogue);return i&&(r.dialogue=i),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),r},gr=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,t.background.resourceId||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"),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(a=>{let c={...a};return delete c.animations,i(c)?c: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},Es=(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},xs=(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=Es(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},Cs={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"])},Mn=(e,t)=>{let r=e[e.length-1];return r?Cs[r]?.has(t)===!0:!1},fr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>fr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Mn(r,n)?o:fr(o,t,[...r,n])])):xs(e,t),dr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>dr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Mn(r,n)?o:dr(o,t,[...r,n])])):typeof e=="string"?Z(e,t):e,yr=(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=fr(e,t._event);return dr(r,t)};var pe=e=>structuredClone(te(e)?$e(e):e),tt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:pe(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Bn=(e,t)=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let r=e.map(n=>pe(n)).filter(n=>t(n)||n.animations);return{hasValidItems:r.length>0,processedItems:r}},Fe=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Fn=e=>e?.animations?.playback?.continuity==="persistent",Ss=e=>{if(e){if(e.character&&Fe(e.character,"name"))return e.character.name;if(Fe(e,"characterName"))return e.characterName}},zn=e=>!!e?.character&&Fe(e.character,"sprite"),_s=e=>{let t={},r=!1,n=Ss(e);return n!==void 0&&(t.name=n,r=!0),zn(e)&&(t.sprite=pe(e.character.sprite),r=!0),r?t:void 0},Un=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},$s=({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=>pe(o)):delete e.initialRevealedContent,e.content=[...n,...t]},Os=()=>({}),Rs=(e,t)=>{if(t.background){let{animationsOnly:r,state:n}=tt(t.background,s=>!!s.resourceId);if(r){e.background=e.background?.resourceId?{...pe(e.background),...n}:n;return}if(!t.background.resourceId){delete e.background;return}let o=pe(t.background),i=e.background;i?.resourceId===o.resourceId&&i?.transformId===o.transformId&&!Fe(o,"animations")&&Fn(i)&&(o.animations=pe(i.animations)),e.background=o}else e.background?.animations&&!Fn(e.background)&&(e.background.animations={})},Ls=(e,t)=>{if(!t.dialogue){e.dialogue&&(Un(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:u}=tt(t.dialogue.ui,f=>!!f.resourceId);l?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&&$s({dialogueState:e.dialogue,content:t.dialogue.content,append:n});let o=Fe(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=Fe(t.dialogue,"characterId"),s=_s(t.dialogue),a=s!==void 0,c=zn(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,a?e.dialogue.character=!i&&o&&e.dialogue.character?{...pe(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,c||Un(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=pe(e.dialogue.character)),e.dialogue.lines.push(l)}},ks=(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},Ps=(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}}},Ts=(e,t)=>{if(t.visual){let{hasValidItems:r,processedItems:n}=Bn(t.visual.items,o=>!!o.resourceId);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))},Ds=(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}=Bn(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);r?e.character={items:n}:delete e.character},Ns=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Vs=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=tt(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},js=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=tt(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},Ms=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=tt(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=pe(t.form)}else e.form&&delete e.form},Fs=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},Us=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},Bs=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},Re=e=>Et(Os,[Bs,Rs,ks,Ps,Ts,Ls,Ds,Ns,Vs,js,Ms,Fs,Us])(e);var zs=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"}}),Le=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),rt=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Wn=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"}),br=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Ir=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Ws=(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]}},Ue=e=>Object.fromEntries(Object.entries(zs).map(([t,r])=>{let n=Ws(e,r.source),o=n!==void 0?n:Le[t]??rt[t];return[t,o]})),ge=(e,t)=>Ue(e)[t],qn=(e={})=>Object.fromEntries(br.map(t=>[t,e[t]??Le[t]]));var ve={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:jn},qs=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,Ys=(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},Rt=(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),a=qs.exec(s);if(a){let[,c,l,u]=a,f=Ys(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((p,h)=>{let g={...t,[c]:p};l&&(g[l]=h),d.forEach(y=>{let I=Rt(y,g,r),A=Z(I,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(Rt(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=Rt(i,t,r)}),n},Tr=({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".`)},Ks=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);return Tr({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n&&(i.playback=structuredClone(n)),i},Hs=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Tr({animationType:e.type,animationId:t,animationPath:r}),e.type},Js=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Gs=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Xs=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),no=e=>e?.playback?.continuity==="persistent",Cr=e=>Array.isArray(e)?e.map(Cr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=Cr(e[r]),t),{}),Lt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify(Cr(t))},oo=(e=[])=>e.filter(t=>no(t)).map(t=>structuredClone(t)),io=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,wr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,io(r)),0),so=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(wr(e.tween),wr(e.prev?.tween),wr(e.next?.tween),io(e.mask?.progress)),Yn=({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(Lt).filter(Boolean));return e.some(n=>{if(!no(n))return!1;let o=Lt(n);return o?r.has(o):!1})},ce=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||Yn({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:Yn({animationInstances:e,activePersistentAnimations:o}),Qs=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Zs=(e,t)=>{if(Qs(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},ea=({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?Ks({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},ta=({hasPrevious:e,hasCurrent:t,previousResourceId:r,currentResourceId:n,sharedTarget:o})=>!e&&t?"enter":e&&!t?"exit":e&&t?r===n&&o?"update":"replace":"none",ra=({animationType:e,animationId:t,animationPath:r,lifecycle:n})=>{if(!(e!=="update"||n==="update"))throw new Error(`[${r}] Animation "${t}" has type "update", but update animations can only be used when the same target persists across the state change. Use type "transition" for enter, exit, and replace.`)},na=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Tr({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},Dr=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(na(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Sr=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=Z(e,t);return r&&typeof r=="object"?e:r},_r=(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})=>_r(e,t).reduce((n,o)=>{let i=Sr(o.text,{variables:r});return n+`${i??""}`.length},0),Kn=(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))},$t=(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("-")}`},Ar=(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},ia=(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},Hn=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},Ot=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},sa=(e={})=>e.textStyles||{},aa=(e={})=>e.images||{},ca=(e={})=>e.colors||{},la=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,nt=(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`)},Jn=(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},ao=(e,t)=>{if(typeof e!="string"||!la.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},Gn=(e,t,r)=>{let n=ao(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=sa(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=Jn(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:Gn(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 a=e.colors?.[r.strokeColorId];if(!a)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let c=Jn(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=Gn(a.hex,c,`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},$r=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>$r(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]=$r(i,t,nt(r,o)));return e.textStyleId!==void 0&&(ze(e.textStyleId,r,"textStyleId"),n.textStyle=ua(t,e.textStyleId)),n},co=(e={},t)=>{let r=ca(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return ao(r.hex,`Color "${t}"`)},lo=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",vr=(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 ${lo(`${t}.fill`)} instead`)},fa=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>ot(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]=ot(i,t,nt(r,o)));return e.colorId!==void 0&&(ze(e.colorId,r,"colorId"),n.fill=co(t,e.colorId)),n},ot=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>ot(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 ${lo("fill")} instead`);vr(e,"hover",r),vr(e,"click",r),vr(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]=fa(i,t,nt(r,o));continue}n[o]=ot(i,t,nt(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(ze(e.colorId,r,"colorId"),n.fill=co(t,e.colorId)),n},Er=(e={},t)=>{let r=aa(e)?.[t];return r||null},uo=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",Xn=(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 ${uo(`${t}.${n}`)} instead`)},Qn=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},Or=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Or(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 ${uo(o)} instead`);Xn(e,"hover",r,"src"),Xn(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]=Or(i,t,nt(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){ze(e.imageId,r,"imageId");let o=Er(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"),Qn(n,"hover",Er(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(ze(e.clickImageId,r,"clickImageId"),Qn(n,"click",Er(t,e.clickImageId)?.fileId??e.clickImageId)),n},Nr=(e,t={},r="root")=>Or(ot($r(e,t,r),t,r),t,r),Ee=Nr,We=(e=[])=>e.find(t=>t.id==="story"),fo=100,Pt=fo,po=(e,t)=>e*t/fo,da=(e={},t=Pt)=>e?.muteAll?0:po(t,e?.soundVolume??Le.soundVolume),pa=(e={},t=Pt)=>e?.muteAll?0:po(t,e?.musicVolume??Le.musicVolume),le=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,confirmDialog:f,form:d,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:I}={})=>{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??a??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},x=ba({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e}),b={variables:e,runtime:A,saveSlots:r,isChoiceVisible:c,isFormVisible:l,canRollback:u,confirmDialog:f,form:d,historyDialogue:p,characters:h};return x&&(b.dialogue=x,b.dialogueLines=x.lines),b},Zn=100,kt=(e,t)=>{if(Array.isArray(e))return e.map(n=>kt(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=kt(r[n],t)}),r.type==="text-revealing"?t(r):r},ha=e=>kt(e,t=>({...t,revealEffect:"none"})),ma=e=>kt(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,Zn):Zn;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),xe=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?ha(e):r?ma(e):e,ho=({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:{}}}}),Rr=e=>{if(Array.isArray(e))return e.map(Rr);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Rr(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}}:{}}}}},ga=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),eo=(e,t)=>{let r=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},n=r.actions&&typeof r.actions=="object"?r.actions:{};return{...e||{},payload:{...r,actions:{...n,...t}}}},Lr=(e,t)=>{if(Array.isArray(e))return e.map(i=>Lr(i,t));if(!e||typeof e!="object")return e;let r={};for(let[i,s]of Object.entries(e))r[i]=Lr(s,t);if(r.type!=="input"||typeof r.field!="string")return r;let n=t?.fields?.[r.field];if(!n)return r;let o={updateFormField:{formId:t.id,formKey:t.key,field:n.id,value:"_event.value",_interactionSource:"form"}};return{...r,value:n.value,placeholder:r.placeholder===void 0?n.placeholder:r.placeholder,multiline:r.multiline===void 0?n.multiline:r.multiline,...r.maxLength===void 0&&n.maxLength!==void 0?{maxLength:n.maxLength}:{},change:eo(r.change,o),submit:eo(r.submit,t.submitActions)}},kr=(e,t)=>{if(Array.isArray(e))return e.map(n=>kr(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=kr(o,t);for(let n of ga){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form",_formId:t.id,_formKey:t.key}})}return r},Pr=({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}},mo=(e=[],t={})=>e.map(r=>{let n=Pr({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}}),ya=e=>!(!e||e.mode==="adv"&&e.content===void 0),ba=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n}={})=>{if(!t&&!ya(e))return;let o=e.content===void 0?[{text:""}]:_r(e.content,"dialogue.content"),i=e.content===void 0?0:oa({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),s=(e.lines||[]).map((c,l)=>{let u=_r(c.content,`dialogue.lines[${l}].content`),f=Pr({characterId:c.characterId,character:c.character,characterName:c.characterName,characters:r});return{...c,content:u.map(d=>({...d,text:Sr(d.text,{variables:n})})),character:f,characterName:f.name}}),a=Pr({characterId:e.characterId,character:e.character,characters:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:a,content:o.map(c=>({...c,text:Sr(c.text,{variables:n})})),initialRevealedCharacters:i,lines:s}},go=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=Z(e,r,{functions:ve});return Ee(xe(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},xr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),to=({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:xr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:xr(o.keyup)});return}e[n]={...i,[r]:{payload:xr(o)}}})},Ia=(e={},t={})=>{let r={};return to({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),to({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},ye=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:a,allowIncomingUpdateFallback:c=!1})=>{if(!e)return[];let l=[],u=({instanceId:b,targetId:R})=>{let L=ea({resources:t,animationId:g,playback:y,instanceId:b,targetId:R,animationPath:s});L&&l.push(L)},f=r!=null&&r!==!1,d=n!=null&&n!==!1,p=o&&i&&o===i,h=ta({hasPrevious:f,hasCurrent:d,previousResourceId:r,currentResourceId:n,sharedTarget:p});Zs(e,s);let g=Js(e),y=Gs(e),I=t?.animations?.[g],A=Hs(I,{animationId:g,animationPath:s}),x=c&&A==="update"&&h!=="update"&&d&&i;if(x||ra({animationType:A,animationId:g,animationPath:s,lifecycle:h}),A==="update")return f&&d&&r===n&&p?u({instanceId:`${a}-animation-update`,targetId:i}):x&&u({instanceId:`${a}-animation-update`,targetId:i}),l;if(A==="transition"){let b=`${a}-animation-transition`,R=y?.continuity==="persistent"?b:`${a}-animation-in`;if(f&&d&&p)return u({instanceId:b,targetId:i}),l;f&&u({instanceId:`${a}-animation-out`,targetId:o}),d&&u({instanceId:R,targetId:i})}return l},wa=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Aa=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:a,variables:c,runtime:l,activePersistentAnimations:u,restoredPersistentAnimations:f,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:I,saveSlots:A=[]})=>{let{elements:x,animations:b}=e;if(t.background){let R=n===void 0?!0:Xs(n?.background??{},"animations"),L=x.find(B=>B.id==="story");if(!L)return e;let V=ia(o,t.background),N=r?.background?.resourceId,_=t.background.resourceId??(t.background.animations?N:void 0),U=Hn(o,N),M=Hn(o,_);if(_){let{images:B={},videos:E={}}=o,S=B[_]||E[_];if(S){let j=E[_]!==void 0,q={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...V},H={id:Ot({resourceId:_,kind:j?"video":"sprite"}),type:j?"video":"sprite",x:q.x,y:q.y,src:S.fileId,width:S.width,height:S.height,alpha:1,anchorX:q.anchorX,anchorY:q.anchorY,rotation:q.rotation,scaleX:q.scaleX,scaleY:q.scaleY};j&&(H.loop=t.background.loop??!1,H.volume=S.volume??50),L.children.push(H)}}if(_){let{layouts:B={}}=o,E=B[_];if(E){let S={id:Ot({resourceId:_,kind:"container"}),type:"container",children:E.elements};V&&Object.assign(S,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...V});let j=Z(S,le({variables:c,runtime:l,saveSlots:A,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:I,characters:o.characters||{},skipTransitionsAndAnimations:a}),{functions:ve});L.children.push(Ee(xe(j,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:a}),o))}}let P=ye({animationsDef:t.background.animations,resources:o,previousResourceId:N,currentResourceId:_,previousTargetId:Ot({resourceId:N,kind:U}),currentTargetId:Ot({resourceId:_,kind:M}),animationPath:"background.animations",idPrefix:"bg-cg",allowIncomingUpdateFallback:!0});ce({animationInstances:P,isLineCompleted:s,skipTransitionsAndAnimations:a,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:R})&&b.push(...P)}return e},va=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:a,animations:c}=e;if(t.character&&n){let l=a.find(h=>h.id==="story");if(!l)return e;let u=t.character.items||[],f=r?.character?.items||[],d=Kn(u),p=Kn(f);for(let h=0;h<u.length;h++){let g=u[h],{transformId:y,sprites:I}=g,A=f.find(M=>M.id===g.id),x=f.findIndex(M=>M.id===g.id),b=A?.sprites&&A.sprites.length>0,R=I&&I.length>0,L=x>=0?$t(A,x,p):void 0,V=ye({animationsDef:g.animations,resources:n,previousResourceId:L,currentResourceId:R?$t(g,h,d):void 0,previousTargetId:L,currentTargetId:R?$t(g,h,d):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!I&&!y&&b&&ce({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){c.push(...V);continue}if(g.animations&&!I&&!y)continue;if(!I||I.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let N=$t(g,h,d),_=n.transforms[y];if(!_){console.warn("Transform not found:",y);continue}let U={type:"container",id:N,x:g.x??_.x,y:g.y??_.y,anchorX:_.anchorX,anchorY:_.anchorY,rotation:_.rotation,scaleX:_.scaleX,scaleY:_.scaleY,children:[]};for(let M of I){let P=n.images[M.resourceId];if(!P){console.warn(`Image resource not found: ${M.resourceId}`);continue}U.children.push({type:"sprite",id:`${N}-${M.id}`,src:P.fileId,width:P.width,height:P.height,x:0,y:0})}l.children.push(U),ce({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...V)}}return e},Ea=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:a,activePersistentAnimations:c,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,saveSlots:g=[]})=>{let{elements:y,animations:I}=e;if(t.visual&&n){let A=y.find(b=>b.id==="story");if(!A)return e;let x=t.visual.items;for(let b of x){if(b.resourceId){let{images:N={},videos:_={},spritesheets:U={}}=n,M=U[b.resourceId];if(M){let P=Ar(n,b),B=b.animationName;if(B){let E=M.animations?.[B];if(!E)throw new Error(`Animation '${B}' not found in spritesheet resource '${b.resourceId}'`);let S={id:`visual-${b.id}`,type:"animated-sprite",x:b.x??P.x,y:b.y??P.y,width:b.width??M.width,height:b.height??M.height,alpha:b.alpha??1,anchorX:P.anchorX,anchorY:P.anchorY,rotation:P.rotation,scaleX:P.scaleX,scaleY:P.scaleY,spritesheetSrc:M.fileId,spritesheetData:M.jsonData,animation:{frames:E.frames,animationSpeed:b.animationSpeed??E.animationSpeed??.5,loop:b.loop??E.loop??!0}};A.children.push(structuredClone(S))}}else{let P=N[b.resourceId]||_[b.resourceId];if(P){let B=_[b.resourceId]!==void 0,E=Ar(n,b),S={id:`visual-${b.id}`,type:B?"video":"sprite",src:P.fileId,width:P.width,height:P.height,x:E.x,y:E.y,anchorX:E.anchorX,anchorY:E.anchorY,rotation:E.rotation,scaleX:E.scaleX,scaleY:E.scaleY};B&&(S.loop=P.loop??!1,S.volume=P.volume??50),A.children.push(S)}}}if(b.resourceId){let{layouts:N={}}=n,_=N[b.resourceId];if(_){let U=Ar(n,b),M={id:`visual-${b.id}`,type:"container",children:structuredClone(_.elements),x:U.x,y:U.y,anchorX:U.anchorX,anchorY:U.anchorY,rotation:U.rotation,scaleX:U.scaleX,scaleY:U.scaleY},P=Z(M,le({variables:s,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i}),{functions:ve});A.children.push(Ee(xe(P,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),n))}}let L=(r?.visual?.items||[]).find(N=>N.id===b.id),V=ye({animationsDef:b.animations,resources:n,previousResourceId:L?.resourceId,currentResourceId:b.resourceId,previousTargetId:L?.resourceId?`visual-${b.id}`:void 0,currentTargetId:b.resourceId?`visual-${b.id}`:void 0,animationPath:`visual.items[${b.id}].animations`,idPrefix:b.id});ce({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:c})&&I.push(...V)}}return e},Be="dialogue-character-sprite",ro=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,xa=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:a}=e,c=We(e.elements);if(!c)return e;let l=t.dialogue?.character?.sprite,u=r?.dialogue?.character?.sprite,f=ro(l),d=ro(u),p=ye({animationsDef:l?.animations,resources:n,previousResourceId:d?Be:void 0,currentResourceId:f?Be:void 0,previousTargetId:d?Be:void 0,currentTargetId:f?Be:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!f)return l?.animations&&d&&ce({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.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:Be,x:h.x,y:h.y,anchorX:h.anchorX,anchorY:h.anchorY,rotation:h.rotation,scaleX:h.scaleX,scaleY:h.scaleY,children:[]};for(let y of l.items){let I=n.images?.[y.resourceId];if(!I){console.warn(`Image resource not found: ${y.resourceId}`);continue}g.children.push({type:"sprite",id:`${Be}-${y.id}`,src:I.fileId,width:I.width,height:I.height,x:0,y:0})}return c.children.push(g),ce({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...p),e},Ca=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:u,skipOnlyViewedLines:f,isLineCompleted:d,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:y,saveSlots:I=[]})=>{let{elements:A,animations:x}=e;if(!t.dialogue||o)return e;let b=A.find(L=>L.id==="story");if(!b)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:L={}}=n,V=L[t.dialogue.ui.resourceId];if(V){let N={elements:V.elements},_=le({variables:h,runtime:g,saveSlots:I,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:d,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:u,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:f,skipTransitionsAndAnimations:p}),U={functions:ve},M=Rt(N,_,U),P=Z(M,_,U),B=Ee(xe(P?.elements,{isLineCompleted:d,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(B))for(let E of B)b.children.push(E);else B&&b.children.push(B)}}xa(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let R=ye({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 ce({animationInstances:R,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&x.push(...R),e},Sa=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,runtime:c,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:I,animations:A}=e;if(t.choice&&n){let x=We(I);if(!x)return e;let b=n?.layouts[t.choice.resourceId];if(b&&b.elements){let L={elements:b.elements},V=Z(L,{...le({variables:a,runtime:c,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:u,isChoiceVisible:f??!!t.choice,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:ve}),N=Rr(Ee(xe(V?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n));if(Array.isArray(N))for(let _ of N)x.children.push(_);else N&&x.children.push(N)}let R=ye({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"});ce({animationInstances:R,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&A.push(...R)}return e},_a=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,runtime:c,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:I,animations:A}=e;if(!y?.resourceId||!n)return e;let x=We(I);if(!x)return e;let b=n?.layouts?.[y.resourceId];if(!b)return console.warn(`Form layout not found: ${y.resourceId}`),e;let R={id:"form-container",type:"container",x:0,y:0,children:b.elements||[]},L={...le({variables:a,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},V=Z(R,L,{functions:ve}),N=kr(Ee(xe(Lr(V,y),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n),y);N&&x.children.push(N);let _=ye({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 ce({animationInstances:_,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(..._),e},$a=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,saveSlots:d=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=Ia(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=We(e.elements);if(!y)return e;let I={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(go({container:I,resources:r,templateData:le({variables:n,runtime:o,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:a,skipTransitionsAndAnimations:p})),e},Oa=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!We(i))return e;let c=r.sounds[t.bgm.resourceId];if(!c)return e;let l=le({variables:o,runtime:n}).runtime;s.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:pa(l,t.bgm.volume??c.volume??Pt),startDelayMs:t.bgm.startDelayMs??null})}return e},Ra=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx.items;for(let s of i){let a=r.sounds?.[s.resourceId];a&&o.push({id:s.id,type:"sound",src:a.fileId,loop:s.loop??a.loop??!1,volume:da(n,s.volume??a.volume??Pt),startDelayMs:s.startDelayMs??a.startDelayMs??null})}}return e},La=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},ka=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,Pa=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let a=t.voice,{resourceId:c,loop:l,startDelayMs:u}=a,f=La(r,n,c);if(!f)return e;let d=le({variables:i,runtime:o}).runtime;return s.push({id:`voice-${n}-${c}`,type:"sound",src:f.fileId,volume:ka(a,d),loop:l??!1,startDelayMs:u??null}),e},Ta=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,saveSlots:d=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:I}=e;if(t.layout){let R=We(y);if(!R)return e;let L=n.layouts[t.layout.resourceId];if(!L)return e;Array.isArray(L.transitions)&&!p&&!h&&Dr({animations:I,transitions:L.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let V={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:L.elements||[]};R.children.push(go({container:V,resources:n,templateData:le({variables:o,runtime:i,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:a,skipTransitionsAndAnimations:h}))}let A=r?.layout?.resourceId,x=t.layout?.resourceId,b=ye({animationsDef:t.layout?.animations,resources:n,previousResourceId:A,currentResourceId:x,previousTargetId:A?`layout-${A}`:void 0,currentTargetId:x?`layout-${x}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return ce({animationInstances:b,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&I.push(...b),e},Da=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:a}=e,c=t?.screen?.animations;if(!c)return e;let l=r!=null,u=ye({animationsDef:c,resources:n,previousResourceId:l?"story":void 0,currentResourceId:"story",previousTargetId:l?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return ce({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...u),e},Na=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:u,overlayStack:f=[],dialogueHistory:d=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:I,animations:A}=e;return f&&f.length>0&&f.forEach((x,b)=>{let R=r.layouts[x.resourceId];if(!R){console.warn(`Overlay layout not found: ${x.resourceId}`);return}Array.isArray(R.transitions)&&(y||Dr({animations:A,transitions:R.transitions,defaultTargetId:`overlayStack-${b}`,idPrefix:`overlayStack-${b}`,animationPathPrefix:`overlayStack[${b}]`}));let L={id:`overlayStack-${b}`,type:"container",x:0,y:0,children:[ho({id:`overlayStack-${b}-blocker`,screen:h}),...R.elements||[]]},V=mo(d,r.characters),N=le({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:u,historyDialogue:V,characters:r.characters||{},skipTransitionsAndAnimations:y}),_=Z(L,N,{functions:ve}),[U,...M]=_.children||[],P=Ee(xe({..._,children:M},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);I.push({...P,children:U?[U,...P.children||[]]:P.children})}),e},Va=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,confirmDialog:d,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:I,animations:A}=e;if(!d?.resourceId)return e;let x=r.layouts?.[d.resourceId];if(!x)return console.warn(`ConfirmDialog layout not found: ${d.resourceId}`),e;Array.isArray(x.transitions)&&!y&&Dr({animations:A,transitions:x.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let b={id:"confirmDialog",type:"container",x:0,y:0,children:[ho({id:"confirmDialog-blocker",screen:h}),...x.elements||[]]},R=mo(p,r.characters),L=Z(b,le({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,confirmDialog:d,historyDialogue:R,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:ve}),[V,...N]=L.children||[],_=Ee(xe({...L,children:N},{isLineCompleted:g,skipMode:a,skipTransitionsAndAnimations:y}),r);return I.push({..._,children:V?[V,..._.children||[]]:_.children}),e},yo=e=>Et(wa,[$a,Aa,va,Ea,Ca,Sa,_a,Ta,Da,Oa,Ra,Pa,Na,Va])(e);var Tt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},vo=1,Vr="choice",Dt="form",jt=()=>({manual:{...Tt.manual},auto:{...Tt.auto},applyMode:Tt.applyMode}),jr=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...jt()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},D=e=>{let t=te(e)?$e(e):e;return structuredClone(t)},T=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Mt=e=>String(e),Eo=()=>({sections:[],resources:[]}),ja=e=>T(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Eo(),Ma=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Fa=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:Ma(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),Ua=()=>({resourceId:void 0}),Ba=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},Mr=(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}},xo=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 a=r.get(s);if(a!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${a}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},Co=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},So=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==vo)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},za=(e,t={})=>{let r;try{r=So(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:Co(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},Wa=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,za(t,r)])),_o=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Tl(r));return t.length>0?t:void 0},qa=e=>{!T(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!T(t))return;let r=_o(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}},Ya=(e,t="viewedRegistry")=>{if(e===void 0)return Eo();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]})))}},$o=(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}=Mr(t,n);if(!s)throw new Error(`Malformed save slot ${r}: section "${n}" does not exist in projectData.`);if(!s.lines?.some(c=>c.id===o))throw new Error(`Malformed save slot ${r}: line "${o}" does not exist in section "${n}".`);return{sceneId:i,sectionId:n,lineId:o}},Ka=(e,t,r)=>{if(!T(e)||!Array.isArray(e.timeline))return it({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((a,c)=>{if(!T(a))return[];try{let l=$o(a,r,`rollback.timeline[${c}]`),u=Vt({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:a.rollbackPolicy}),f=_o(D(a.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(n.length===0)return it({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 a=n.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);a>=0?o=a:(n.push(Vt({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}},Ha=(e,t,r)=>{if(!T(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=Br(t),o=$o(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?Me(D(e.variables),t.resources?.variables??{}):{},s=ac({loadedContextRuntime:T(e.runtime)?D(e.runtime):{}}),a={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:Ka(e.rollback,o,t)};return s&&(a.runtime=s),a},Ja=(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)=>Ha(r,t,n))}},Ga=(e,t)=>{if(!T(e))throw new Error("Malformed save slot.");let r=So(e.formatVersion);return{...e,formatVersion:r,state:Ja(e.state,t)}},Io=(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},Xa=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Io(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Io(e.cancelActions,"cancelActions")}},Ye=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Qa=e=>(T(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),Ke=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},Oo=e=>{if(!(!T(e)||!e.animations))return{animations:D(e.animations)}},Za=(e,t)=>{let r=Oo(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},ec=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},tc=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},Nt=e=>String(e??""),Ro=(e,t)=>{let r=Nt(t);return e?.trim===!0?r.trim():r},rc=e=>T(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>T(t)).map(([t,r])=>[t,{id:t,...D(r)}])):{},nc=(e,t)=>{if(!t||!T(e.global.formDrafts))return;let r=e.global.formDrafts[t];return T(r)?r:void 0},Lo=(e,t)=>{let r=Qa(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},Fr=(e,t)=>{let r=Ro(e,t);return e?.required===!0&&r.length===0?"required":null},oc=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=X({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:Re(n.slice(0,o+1).map(i=>i.actions||{}))},ic=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=ec(t),o=tc(r,n);if(!n||!o)return null;let i=nc(e,o),s=rc(t),a=Kr({state:e}),c={},l=[],u={},f=!0;return Object.entries(s).forEach(([d,p])=>{let h=Nt(a?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},d)?Nt(i.values[d]):h,y=i?.touched?.[d]===!0,I=Fr(p,g),A=i?.submitted||y?I:null,x=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,b={id:d,variableId:p.variableId,value:g,initialValue:h,valid:!I,error:A,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...x!==void 0?{maxLength:x}:{}};I&&(f=!1),c[d]=b,l.push(b),u[d]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:f,submitted:i?.submitted===!0,fields:c,fieldList:l,values:u,submitActions:{submitForm:{formId:n,formKey:o,actions:D(t.submitActions??{})}},cancelActions:{cancelForm:{formId:n,formKey:o,actions:D(t.cancelActions??{})}}}},ke=[],wo="line",Ur="interaction",Vt=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),Br=e=>{let{contextVariableDefaultValues:t}=pr(e??{});return D(t)},ko=()=>({...D(rt)}),Po=({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]=To(s,D(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},sc=({loadedGlobalRuntime:e={}})=>Po({loadedRuntime:e,runtimeIds:br,defaults:Le,path:"global.runtime"}).runtimeState,ac=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=Po({loadedRuntime:e,runtimeIds:Ir,defaults:ko(),path:"context.runtime"});return r?t:void 0},zr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},cc=e=>e.runtime?(Ir.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=D(rt[t]))}),e.runtime):(e.runtime=ko(),e.runtime),lc=e=>qn(e.global),uc=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:lc(e)}})},fc=e=>Wn[e],dc=(e,t)=>{let r=fc(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}"`)},To=(e,t)=>(dc(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),Do=(e,t,r)=>{let n=To(t,r);if(t in rt){let o=zr(e);if(!o)return n;let i=cc(o);return i[t]=n,n}return e.global[t]=n,n},No=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:D(e)},configuration:{},views:[],bgm:Ua(),variables:Br(t),rollback:it({pointer:e})}),He=e=>e?(e.currentPointerMode="read",T(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,pc=(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=No({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,hc(e,{queueRender:t}),o},hc=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,Ye(e),Ke(e),e.global.nextLineConfig=jt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},Vo=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},it=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[Vt({sectionId:e.sectionId,lineId:e.lineId})]:[]}},Te=(e,t={})=>{if(e?.rollback)return Vo(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=it({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},Wr=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=Te(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(Vt(t)),n.currentIndex=n.timeline.length-1},mc=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=ke[ke.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)},gc=({state:e},t={})=>{let r=t?.source===wo?wo:Ur,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?(ke.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),ke.push({checkpointIndex:o.currentIndex,source:r}),e)},yc=({state:e})=>(ke.pop(),e),he=(e,t,r)=>{let o=ke[ke.length-1]?.source??Ur;if(!Dl(t,o))return;let i=mc(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:D(r)}))},Ao=(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:a}of n){let c=e.projectData.resources?.variables?.[o],l=c?.scope,u=c?.type;if(Ae(c))throw new Error(`Cannot update computed variable: ${o}`);if(c?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Ct(l,o),St(u,i,o),hr(u,i,s,o,{roundTo:a}),l==="context"&&(r.variables[o]=_t(r.variables[o],i,s,{roundTo:a}))}},bc=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{Nl(e,r,n)})},Ic=(e,t)=>{let{sectionId:r,lineId:n}=t,s=X({state:e},{sectionId:r})?.lines?.find(a=>a.id===n)?.actions;s&&Object.entries(s).forEach(([a,c])=>{ei(e,a,c)})},jo=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=Te(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&at({state:e}),e.global.skipMode&&Pe({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=Br(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=D(Tt),e.global.overlayStack=[],Ye(e),Ke(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let a=i;a<=t;a++)a>i&&jr(e),Ic(e,n.timeline[a]),bc(e,n.timeline[a]);let s=He(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(a=>a?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},wc=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;xo(t);let a=t.story.initialSceneId,c=t.story.scenes[a],l=c.initialSectionId,u=c.sections[l],f={sceneId:a,sectionId:l,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:d}=pr(t),p={...d,...Me(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:Ya(s,"accountViewedRegistry"),nextLineConfig:jt(),saveSlots:Wa(n),overlayStack:[],variables:p,...sc({loadedGlobalRuntime:i})},contexts:[No({pointer:f,projectData:t})]}},Ac=({state:e})=>e.global.overlayStack||[],vc=({state:e})=>e.global.pendingEffects,Mo=({state:e})=>e.global.skipMode,Ec=({state:e})=>e.global.autoMode,Fo=({state:e})=>e.global.dialogueUIHidden,Uo=({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=X({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),a=i.lines.slice(0,s+1),c=[],l={};for(let u of a){let f=u.actions||{};if(l=Re([l,f]),!f.dialogue)continue;let d=l.dialogue||{},p="";d.character?.name!==void 0?p=d.character.name:d.characterId&&(p=e.projectData.resources?.characters?.[d.characterId]?.name||"");let h=Fa({sectionId:n,lineId:u.id,content:f.dialogue.append===!0?d.content:f.dialogue.content,dialogueState:d,characterName:p});if(f.dialogue.append===!0&&c.length>0){c[c.length-1]={...c[c.length-1],content:h.content,text:h.text,characterId:h.characterId,character:h.character,characterName:h.characterName};continue}c.push(h)}return c},xc=({state:e})=>e.global.confirmDialog??null,st=({state:e},{pointer:t}={})=>{let r=t??ue({state:e})?.pointer,n=oc({state:e,pointer:r});return ic({state:e,form:n.form,pointer:r})},Cc=({state:e},{pointer:t}={})=>!!st({state:e},{pointer:t}),me=({state:e},{pointer:t}={})=>{let r=st({state:e},{pointer:t});if(r)return{source:Dt,formId:r.id,formKey:r.key};let n=Bo({state:e,pointer:t});return n?{source:Vr,resourceId:n}:null},Sc=({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 a=X({state:e},{sectionId:n});if(!a||!a.lines||!Array.isArray(a.lines))return s.lastLineId===o;let c=a.lines.findIndex(u=>u.id===s.lastLineId),l=a.lines.findIndex(u=>u.id===o);return c===-1||l===-1?s.lastLineId===o:l<=c},_c=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},qr=({state:e},t)=>Sc({state:e,registry:e.global.accountViewedRegistry},t),$c=({state:e},t)=>_c({registry:e.global.accountViewedRegistry},t),Oc=({state:e})=>e.global.nextLineConfig,Bo=({state:e,pointer:t}={})=>{let r=t??ue({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=X({state:e},{sectionId:n})?.lines||[],a=s.findIndex(l=>l.id===o);if(a<0)return;let c;for(let l of s.slice(0,a+1)){let u=l?.actions;if(u?.cleanAll&&(c=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){c=void 0;continue}let f=u.choice;if(f?.resourceId){c=f.resourceId;continue}f?.animations||(c=void 0)}return c},zo=({state:e})=>!!Bo({state:e}),Rc=({state:e})=>structuredClone(e),Wo=({state:e})=>e.global.saveSlots,Lc=({state:e},t)=>{let r=t?.slotId,n=Mt(r);return e.global.saveSlots[n]},Yr=({state:e})=>Ue(e),kc=({state:e},t)=>ge(e,t?.runtimeId),Kr=({state:e})=>{let t={...e.global?.variables??{},...zr(e)?.variables??{}};return xt({variables:t,runtime:Ue(e),variableConfigs:e.projectData.resources?.variables??{}})},ue=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},X=({state:e},t)=>{let{sectionId:r}=t;return Mr(e.projectData,r).section},Hr=({state:e})=>{let t=ue({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=X({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},qo=({state:e})=>{let{sectionId:t,lineId:r}=ue({state:e}).pointer,o=X({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===r),a=o.slice(0,i+1).map(l=>{let u=l.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return Re(a)},Pc=({state:e})=>{let t=Yo({state:e}),n=Hr({state:e})?.actions??{},o=Re([t??{},n]);return mr(t??{},o??{})},Tc=({state:e},{sectionId:t})=>{let r=X({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},a=Re([o,s]),c=mr(o,a);n.push({id:i.id,changes:c,presentationState:a}),o=gr(a)}return n},Dc=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=Tc({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},Yo=({state:e})=>{let{sectionId:t,lineId:r}=ue({state:e}).pointer,o=X({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===r);if(i<=0)return null;let a=o.slice(0,i).map(c=>{let l=c.actions||{},u={};return Object.keys(l).forEach(f=>{u[f]=l[f]}),u});return gr(Re(a))},Jr=({state:e},{slotsPerPage:t=6}={})=>{let o=((Yr({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let a=o+s,c=e.global.saveSlots&&e.global.saveSlots[Mt(a)]||{};i.push({...c,slotId:a})}return{saveSlots:i}},Nc=Wo,Vc=Jr,jc=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},Mc=({state:e},t={})=>{let r=qo({state:e}),n=Yo({state:e}),o=Hr({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:D(i)}:o,a=i?.animations&&n===null?{}:n,{sectionId:c}=ue({state:e}).pointer,{sceneId:l}=Mr(e.projectData,c),u=Yr({state:e}),f=t?.activePersistentAnimations??[],d=t?.restoredPersistentAnimations??[],p=st({state:e}),h=zo({state:e}),g=Kr({state:e}),{saveSlots:y}=Jr({state:e}),I=jc(e);return yo({presentationState:r,previousPresentationState:a,currentLineActions:s,resources:e.projectData.resources,currentSceneId:l,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:ri({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||I,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:Uo({state:e}),saveSlots:y,variables:g,runtime:u,activePersistentAnimations:f,restoredPersistentAnimations:d})},Fc=({state:e},t)=>(e.global.confirmDialog=Xa(t),e.global.pendingEffects.push({name:"render"}),e),Uc=({state:e})=>(e.global.confirmDialog&&(Ye(e),e.global.pendingEffects.push({name:"render"})),e),Bc=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),he(e,"pushOverlay",t),e),zc=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),he(e,"popOverlay",void 0),e),Wc=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),he(e,"replaceLastOverlay",t),e),qc=({state:e})=>(e.global.overlayStack=[],Ye(e),Ke(e),e.global.pendingEffects.push({name:"render"}),he(e,"clearOverlays",void 0),e),Yc=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"})},Ft=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,Za(e,r),Ke(e);let n=me({state:e},{pointer:t}),o=n?.source===Vr,i=n?.source===Dt;return n&&Yc(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},Ko=({state:e})=>(me({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:ge(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),at=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Kc=({state:e})=>{let t=e.global.autoMode;return me({state:e})&&!t||(t?at({state:e}):Ko({state:e})),e},Ho=({state:e})=>(me({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),Pe=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Hc=({state:e})=>{let t=Mo({state:e});return me({state:e})&&!t||(t?Pe({state:e}):Ho({state:e})),e},Ut=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),he(e,"showDialogueUI",void 0),e),Jo=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),he(e,"hideDialogueUI",void 0),e),Jc=({state:e})=>(Fo({state:e})?Ut({state:e}):Jo({state:e}),e),De=(e,t,r)=>(Do(e,t,r),uc(e),e.global.pendingEffects.push({name:"render"}),e),ct=(e,t,r,n)=>{let o=Do(e,t,r);return e.global.pendingEffects.push({name:"render"}),he(e,n,{value:o}),e},Gc=({state:e},t)=>De(e,"dialogueTextSpeed",t?.value),Xc=({state:e},t)=>De(e,"autoForwardDelay",t?.value),Qc=({state:e},t)=>De(e,"skipUnseenText",t?.value),Zc=({state:e},t)=>De(e,"skipTransitionsAndAnimations",t?.value),el=({state:e},t)=>De(e,"soundVolume",t?.value),tl=({state:e},t)=>De(e,"musicVolume",t?.value),rl=({state:e},t)=>De(e,"muteAll",t?.value),nl=({state:e},t)=>ct(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),ol=({state:e})=>{let t=ge(e,"saveLoadPagination")+1;return ct(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},il=({state:e})=>{let t=ge(e,"saveLoadPagination")-1;return ct(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},sl=({state:e},t)=>ct(e,"menuPage",t?.value,"setMenuPage"),al=({state:e},t)=>ct(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),cl=({state:e})=>(e.global.pendingEffects=[],e),ll=({state:e},t)=>(e.global.pendingEffects.push(t),e),Go=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!Oo(n),i=X({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&&!pc(e,{queueRender:!o}))return e;e.global.autoMode&&at({state:e}),r&&e.global.skipMode&&Pe({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let c=He(a),l=c.read;r||qe(e,{sectionId:l?.sectionId,lineId:l?.lineId}),a.rollback||Te(a,{compatibilityAnchor:!0}),c.read={sectionId:t,lineId:s.id},r?a.rollback=it({pointer:c.read}):Wr(e,{sectionId:t,lineId:s.id})}return Ft(e,a?.pointers?.read,{screenTransition:n}),e},ul=({state:e},t)=>Go(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),Xo=e=>(e.global.accountViewedRegistry=ja(e.global.accountViewedRegistry),e.global.accountViewedRegistry),Gr=(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)}))}})},Qo=(e,t)=>{Gr(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:[]}}])},fl=(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=X({state:e},{sectionId:r});if(s?.lines){let a=s.lines.findIndex(l=>l.id===i.lastLineId),c=s.lines.findIndex(l=>l.id===n);if(a===-1||c>a)return i.lastLineId===n?!1:(i.lastLineId=n,!0)}else return i.lastLineId===n?!1:(i.lastLineId=n,!0);return!1}else return o.sections.push({sectionId:r,lastLineId:n}),!0},qe=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;fl(e,Xo(e),t)&&Qo(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},dl=({state:e},t)=>(qe(e,t),e.global.pendingEffects.push({name:"render"}),e),pl=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=Xo(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),Qo(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},Zo=({state:e},t)=>{let r=Ba(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,a=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 c=e.global.nextLineConfig.auto?.enabled,l=me({state:e});return!a&&!l&&c===!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}}):!a&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),he(e,"setNextLineConfig",t),e},hl=({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=Mt(r),s=D(e.contexts);s?.forEach(l=>{He(l),Vo(l.rollback),qa(l.rollback)});let a={contexts:s},c={formatVersion:vo,slotId:Co(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:a};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},ml=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=Mt(r),o=e.global.saveSlots[n];if(o){let i=Ga(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=jt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,Ye(e),Ke(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},gl=({state:e},t)=>{let{projectData:r}=t;xo(r),e.projectData=r;let n=r?.resources?.variables??{};return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables=Me(e.global.variables,n)),e.contexts?.forEach(o=>{Object.prototype.hasOwnProperty.call(o??{},"variables")&&(o.variables=Me(o.variables,n))}),Ye(e),Ke(e),e.global.pendingEffects.push({name:"render"}),e},yl=({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&&!X({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=X({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 c=He(o);return c.read={sectionId:i,lineId:n},Ft(e,c.read),e},bl=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return Ut({state:e}),e;let r=me({state:e});if(r?.source===Vr&&t?.bypassChoice!==!0||r?.source===Dt&&t?._interactionSource!==Dt)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=ue({state:e})?.pointer,f=u?.sectionId,d=u?.lineId;f&&d&&qe(e,{sectionId:f,lineId:d}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ge(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=ue({state:e})?.pointer,o=n?.sectionId,i=X({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],a=i?.lines||[],l=a.findIndex(u=>u.id===n?.lineId)+1;if(l<a.length){let u=a[l],f=!ge(e,"skipUnseenText");if(e.global.skipMode&&f&&!qr({state:e},{sectionId:o,lineId:u.id}))return Pe({state:e}),e;if(s&&!s.rollback&&Te(s,{compatibilityAnchor:!0}),s){let h=He(s),g=h.read?.lineId;g&&o&&qe(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:u.id}}Wr(e,{sectionId:o,lineId:u.id}),jr(e);let{activeInteraction:d}=Ft(e,{sectionId:o,lineId:u.id}),p=e.global.nextLineConfig;p?.auto?.enabled&&!d&&p.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}})}else e.global.autoMode&&at({state:e}),e.global.skipMode&&Pe({state:e});return e},Il=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=me({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ge(e,"autoForwardDelay")}});let r=ue({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&qe(e,{sectionId:n,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},wl=({state:e},t)=>Go(e,{sectionId:t?.sectionId,screen:t?.screen}),Al=({state:e})=>{if(e.global.dialogueUIHidden)return Ut({state:e}),e;if(me({state:e}))return e;let t=ue({state:e})?.pointer,r=t?.sectionId,n=X({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],a=i.findIndex(c=>c.id===t?.lineId)+1;if(a<i.length){let c=i[a],l=!ge(e,"skipUnseenText");if(e.global.skipMode&&l&&!qr({state:e},{sectionId:r,lineId:c.id}))return Pe({state:e}),e;if(o&&!o.rollback&&Te(o,{compatibilityAnchor:!0}),o){let f=He(o),d=f.read?.lineId;d&&r&&qe(e,{sectionId:r,lineId:d}),f.read={sectionId:r,lineId:c.id}}Wr(e,{sectionId:r,lineId:c.id}),jr(e);let{activeInteraction:u}=Ft(e,{sectionId:r,lineId:c.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},Xr=(e,t={})=>{let r=st({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},vl=(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(Ae(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return Ct(n,t.variableId),St(o,"set",t.variableId),{variableConfig:r,scope:n}},El=(e,t)=>({id:e.id,key:e.key,valid:!0,values:D(t),fields:D(e.fields),fieldList:D(e.fieldList)}),xl=({state:e},t={})=>{let r=Xr(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=Lo(e,r.key),i=Nt(t.value),s=r.fields[n],a=Fr(s,i);return o.values[n]=i,o.touched[n]=!0,a?o.errors[n]=a:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},Cl=({state:e},t={})=>{let r=Xr(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=Lo(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([f,d])=>{let p=Object.prototype.hasOwnProperty.call(n.values,f)?n.values[f]:d.value,h=Fr(d,p);n.touched[f]=!0,h&&(i[f]=h),o[f]=Ro(d,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 a=!1,c=[],l=[];Object.entries(r.fields).forEach(([f,d])=>{let{scope:p}=vl(e,d),h=p==="context"?s.variables:e.global.variables,g=o[f];h[d.variableId]=_t(h[d.variableId],"set",g),p==="context"&&(a=!0,l.push({variableId:d.variableId,op:"set",value:g})),(p==="device"||p==="account")&&c.push({scope:p,path:`variables.${d.variableId}`,op:"set",value:D(h[d.variableId])})}),a&&he(e,"updateVariable",{id:"submitForm",operations:l}),Gr(e,c);let u=El(r,o);return delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},Sl=({state:e},t={})=>{let r=Xr(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"}},_l=({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=[],a=[];return n.forEach(({variableId:c,op:l,value:u,roundTo:f})=>{let d=e.projectData.resources?.variables?.[c],p=d?.scope,h=d?.type;if(Ae(d))throw new Error(`Cannot update computed variable: ${c}`);if(d?.readonly===!0)throw new Error(`Cannot update readonly variable: ${c}`);Ct(p,c),St(h,l,c),hr(h,l,u,c,{roundTo:f});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:c,op:l,value:u};f!==void 0&&(y.roundTo=f),a.push(y)}g[c]=_t(g[c],l,u,{roundTo:f}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${c}`,op:"set",value:D(g[c])})}),i&&he(e,"updateVariable",{id:r,operations:a}),Gr(e,s),e.global.pendingEffects.push({name:"render"}),e},$l=e=>(t,r)=>e({state:t},r),Ol=e=>({variables:xt({variables:{...e.global?.variables??{},...zr(e)?.variables??{}},runtime:Ue(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:Ue(e)}),Rl=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")},Ll=(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")},kl=(e,t)=>{Rl(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(Ll(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!et(n.when,Ol(e)))){Object.entries(n.actions).forEach(([i,s])=>{ei(e,i,s)});return}}},Pl={conditional:{replayLine:kl},updateVariable:{recordSources:[Ur],replayLine:Ao,replayRecorded:Ao,persistInSaveSlot:!0},setNextLineConfig:{replayLine:$l(Zo)}},Bt=e=>Pl[e]??null,Tl=e=>Bt(e)?.persistInSaveSlot===!0,Dl=(e,t)=>{let r=Bt(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},Nl=(e,t,r)=>{Bt(t)?.replayRecorded?.(e,r)},ei=(e,t,r)=>{Bt(t)?.replayLine?.(e,r)},ti=({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}},ri=({state:e})=>ti({state:e},{offset:-1})!==null,Vl=({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=Te(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:jo(e,i)},jl=({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=Te(o,{compatibilityAnchor:!o.rollback}),a=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===r&&c.lineId===n);if(a===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return a===i.currentIndex?e:jo(e,a)},ni=e=>{let t=wc(e);return Dn(t,{selectPendingEffects:vc,selectSkipMode:Mo,selectAutoMode:Ec,selectIsChoiceVisible:zo,selectIsFormVisible:Cc,selectActiveInteraction:me,selectActiveForm:st,selectDialogueUIHidden:Fo,selectDialogueHistory:Uo,selectConfirmDialog:xc,selectIsLineAccountViewed:qr,selectIsResourceAccountViewed:$c,selectNextLineConfig:Oc,selectSystemState:Rc,selectSaveSlotMap:Wo,selectSaveSlots:Nc,selectSaveSlot:Lc,selectRuntime:Yr,selectRuntimeValue:kc,selectAllVariables:Kr,selectCurrentPointer:ue,selectSection:X,selectCurrentLine:Hr,selectPresentationState:qo,selectPresentationChanges:Pc,selectSectionLineChanges:Dc,selectSaveSlotPage:Jr,selectCurrentPageSlots:Vc,selectRenderState:Mc,selectOverlayStack:Ac,selectLineIdByOffset:ti,selectCanRollback:ri,startAutoMode:Ko,stopAutoMode:at,toggleAutoMode:Kc,startSkipMode:Ho,stopSkipMode:Pe,toggleSkipMode:Hc,showDialogueUI:Ut,hideDialogueUI:Jo,toggleDialogueUI:Jc,setDialogueTextSpeed:Gc,setAutoForwardDelay:Xc,setSkipUnseenText:Qc,setSkipTransitionsAndAnimations:Zc,setSoundVolume:el,setMusicVolume:tl,setMuteAll:rl,setSaveLoadPagination:nl,incrementSaveLoadPagination:ol,decrementSaveLoadPagination:il,setMenuPage:sl,setMenuEntryPoint:al,showConfirmDialog:Fc,hideConfirmDialog:Uc,resetStoryAtSection:ul,clearPendingEffects:cl,appendPendingEffect:ll,beginRollbackActionBatch:gc,endRollbackActionBatch:yc,addViewedLine:dl,addViewedResource:pl,setNextLineConfig:Zo,saveSlot:hl,loadSlot:ml,updateProjectData:gl,sectionTransition:wl,jumpToLine:yl,nextLine:bl,markLineCompleted:Il,rollbackToLine:jl,rollbackByOffset:Vl,pushOverlay:Bc,popOverlay:zc,replaceLastOverlay:Wc,clearOverlays:qc,updateFormField:xl,submitForm:Cl,cancelForm:Sl,updateVariable:_l,nextLineFromSystem:Al},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var Ml="route-engine",Fl="projectPersistence";var ii=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),J=e=>Object.prototype.toString.call(e)==="[object Object]",oi="variables.",Ul=(e={})=>{let t=J(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!J(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)}:!J(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Bl=(e={})=>{let t=J(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!J(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)}:!J(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},zl=(e,t)=>{let r=Bl(e),n=Ul(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let a=o.find(c=>c.sectionId===s.sectionId);if(!a){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(a.lastLineId!==void 0){if(s.lineId===void 0){delete a.lastLineId;return}a.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(c=>c.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},si=(e={})=>{let t=J(e)?e:{};return{saveSlots:J(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:J(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:J(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:J(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:J(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Wl=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!J(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(oi)?t.path.slice(oi.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}].`)})},ql=(e,t)=>{let r={};return Wl(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=zl(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},Qr=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},Yl=e=>{let t=Qr(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Kl=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},Hl=({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}".`))}}),Jl=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let c=n.transaction(t,"readonly").objectStore(t).get(r);c.onsuccess=()=>{o(c.result??null)},c.onerror=()=>{i(c.error??new Error(`Failed to read persisted namespace "${r}" from IndexedDB.`))}})},lt=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let a=o.transaction(t,"readwrite"),c=a.objectStore(t),l=c.get(r),u=!1,f=p=>{u||(u=!0,s(p))},d=()=>{u||(u=!0,i())};l.onerror=()=>{f(l.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},l.onsuccess=()=>{let p=si(l.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...ii(),...p,...h},y=c.put(g);y.onerror=()=>{f(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},a.oncomplete=()=>{d()},a.onerror=()=>{f(a.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},a.onabort=()=>{f(a.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},Gl=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let s=n.transaction(t,"readwrite"),c=s.objectStore(t).delete(r),l=!1,u=d=>{l||(l=!0,i(d))},f=()=>{l||(l=!0,o())};c.onerror=()=>{u(c.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{f()},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}".`))}})},Zr=(e={})=>{let{indexedDB:t,databaseName:r=Ml,objectStoreName:n=Fl,namespace:o}=e,i=Kl(t),s=Yl(o),a=Hl({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let c=await Jl({databasePromise:a,objectStoreName:n,namespace:s});return{...ii(),...si(c)}},clear:async()=>Gl({databasePromise:a,objectStoreName:n,namespace:s}),saveSlots:async c=>lt({databasePromise:a,objectStoreName:n,namespace:s,patch:{saveSlots:J(c)?c:{}}}),saveGlobalDeviceVariables:async c=>lt({databasePromise:a,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:J(c)?c:{}}}),saveGlobalAccountVariables:async c=>lt({databasePromise:a,objectStoreName:n,namespace:s,patch:{globalAccountVariables:J(c)?c:{}}}),saveGlobalRuntime:async c=>lt({databasePromise:a,objectStoreName:n,namespace:s,patch:{globalRuntime:J(c)?c:{}}}),applyScopedDataUpdates:async c=>lt({databasePromise:a,objectStoreName:n,namespace:s,patch:l=>ql(l,c)})}},Xl=Zr;var Ql=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Zl=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),ai="conditional",en="form",eu=new Set(["submitForm","cancelForm"]),ut=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function tn(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:a}=e,c=(w=new Map,C=Date.now())=>new Map(Array.from(w.entries()).filter(([,$])=>C<$.expiresAt).map(([$,F])=>[$,{animation:structuredClone(F.animation),startedAt:F.startedAt,expiresAt:F.expiresAt}])),l=(w=new Map)=>Array.from(w.values()).map(C=>structuredClone(C.animation)),u=(w=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,C])=>w<C.expiresAt))},f=()=>{for(;t.selectPendingEffects().length>0;){let w=[...t.selectPendingEffects()];t.clearPendingEffects();try{a(w)}catch(C){throw t.clearPendingEffects(),w.forEach($=>{t.appendPendingEffect($)}),C}}},d=({initialState:w,namespace:C})=>{t=ni(w),r=0,n=Qr(C),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),f()},p=()=>n,h=()=>t.selectPresentationState(),g=()=>t.selectPresentationChanges(),y=w=>t.selectSectionLineChanges(w),I=(w={})=>{r+=1;let C=Date.now();u(C);let $=i.size>0,F=c(o,C),z=$?c(i,C):new Map,fe={...t.selectRenderState({activePersistentAnimations:l(F),restoredPersistentAnimations:l(z)}),id:`render-${r}`};return s.set(fe.id,{builtAt:C,persistentAnimationSessions:new Map([...z.entries(),...F.entries()]),usedRestoredPersistentAnimationSessions:$}),fe},A=(w={})=>I(w),x=(w={})=>I(w),b=w=>{let C=typeof w?.id=="string"&&w.id.length>0?w.id:null,$=C?s.get(C):null;C&&s.delete(C);let F=new Map;oo(w?.animations).forEach(z=>{let ne=Lt(z);if(!ne)return;let fe=$?.persistentAnimationSessions?.get(ne)??o.get(ne),dt=Math.max(0,so(z)),sn=fe?.startedAt??$?.builtAt??Date.now();F.set(ne,{animation:structuredClone(z),startedAt:sn,expiresAt:sn+dt})}),o=F,$?.usedRestoredPersistentAnimationSessions&&(i=new Map)},R=()=>t.selectSystemState(),L=()=>t.selectSaveSlotMap(),V=w=>t.selectSaveSlot(w),N=w=>t.selectSaveSlotPage(w),_=()=>t.selectSkipMode(),U=()=>t.selectAutoMode(),M=()=>t.selectRuntime(),P=()=>t.selectIsChoiceVisible(),B=()=>t.selectIsFormVisible(),E=()=>t.selectActiveInteraction(),S=(w,C,$={})=>w!=="nextLine"||!ut(C)?C:$.bypassChoice===!0?{...C,bypassChoice:!0}:$.interactionSource===en?{...C,_interactionSource:en}:C,j=(w,C)=>{if(!t[w])return;Ql.has(w)&&(Zl.has(w)?i=c(o):i=new Map,o=new Map);let $=t[w](C);return f(),$},q=(w,C,$,F={})=>{if(w===ai){let z=W($),ne=yr({[w]:C},z);nn(ne[w],$,F);return}j(w,C)},H=(w,C)=>{q(w,C)},W=w=>{if(!w)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(w,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:C,...$}=w,F=t.selectAllVariables?t.selectAllVariables():void 0;return{...$,_event:C,variables:F,runtime:t.selectRuntime?t.selectRuntime():{}}},ft=w=>{if(!ut(w))throw new Error("conditional action payload must be an object");if(!Array.isArray(w.branches))throw new Error("conditional action requires branches array");if(w.branches.length===0)throw new Error("conditional action requires at least one branch")},Ne=(w,C,$)=>{if(!ut(w))throw new Error(`conditional branch at index ${C} must be an object`);if(!ut(w.actions))throw new Error(`conditional branch at index ${C} requires actions object`);if(!Object.prototype.hasOwnProperty.call(w,"when")&&C!==$-1)throw new Error("conditional else branch must be the last branch")},nn=(w,C,$)=>{ft(w);for(let F=0;F<w.branches.length;F+=1){let z=w.branches[F];Ne(z,F,w.branches.length);let ne=W(C);if(!(Object.prototype.hasOwnProperty.call(z,"when")&&!et(z.when,ne))){Wt(z.actions,C,$);return}}},ui=(w,C)=>({...w??{},_form:C}),fi=(w,C,$,F)=>{let z=j(w,C),ne=z?.submitted===!0&&z.valid===!0,fe=z?.cancelled===!0;!ne&&!fe||ut(C.actions)&&Wt(C.actions,ui($,z.form),{...F,interactionSource:en})},di=(w,C,$,F)=>{let z=W($),fe=yr({[w]:C},z)[w];if(w===ai){nn(fe,$,F);return}let dt=S(w,fe,F);if(eu.has(w)){fi(w,dt,$,F);return}j(w,dt)},Wt=(w,C,$)=>{Object.entries(w).forEach(([F,z])=>{di(F,z,C,$)})},on=(w,C,$={})=>{t.beginRollbackActionBatch({source:$.rollbackSource});try{Wt(w,C,$)}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:q,handleInternalAction:H,handleActions:on,selectRenderState:A,prepareRenderState:x,commitRenderState:b,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:R,selectSaveSlotMap:L,selectSaveSlot:V,selectSaveSlotPage:N,selectSaveSlots:L,selectRuntime:M,selectIsChoiceVisible:P,selectIsFormVisible:B,selectActiveInteraction:E,handleLineActions:()=>{let w=t.selectCurrentLine();return w?.actions?(on(w.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var rn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},tu=80,li=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},ru=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&li({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},nu=({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 a=n.delay??1e3;r.getElapsed()>=a&&(t.remove(i),r.setCallback(null),r.setElapsed(0),zt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},ou=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},iu=({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 a=n?.delay??tu;r.getElapsed()>=a&&(r.setElapsed(0),zt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},su=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},au=({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 a=n.delay??1e3;r.getElapsed()>=a&&(r.setElapsed(0),zt(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},cu=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},lu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},uu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},fu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},du=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},pu=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},ci={render:li,saveSlots:lu,saveGlobalDeviceVariables:uu,saveGlobalAccountVariables:fu,saveGlobalRuntime:du,applyScopedDataUpdates:pu,handleLineActions:ru,startAutoNextTimer:nu,clearAutoNextTimer:ou,startSkipNextTimer:iu,clearSkipNextTimer:su,nextLineConfigTimer:au,clearNextLineConfigTimer:cu},hu=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)},mu=(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(!hu.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},gu=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:a})=>{let c=rn(),l=rn(),u=rn(),f=s??null,d=Promise.resolve(),p=null,h=null,g=!1,y=0,I=E=>{if(o){o(E);return}console.error("RouteEngine persistence write failed.",E)},A=()=>{if(f)return f;let E=e();return f=Zr({indexedDB:i,namespace:a??E?.getNamespace?.()}),f},x=E=>{d=d.catch(()=>{}).then(()=>{let S=A();return E(S)}).catch(S=>{I(S)})},b=E=>{let S=typeof E?.id=="string"&&E.id.length>0?E.id:null;y+=1,p=S,g=!1},R=()=>y,L=(E={})=>{if(E?.aborted===!0)return!1;let S=typeof E?.id=="string"&&E.id.length>0?E.id:null;return S?S!==p||S===h?!1:(h=S,!0):p!==null||g?!1:(g=!0,!0)},V=(E,S={})=>{if(E!=="renderComplete"||!L(S))return!1;let j=e();return zt(j,"markLineCompleted",{}),!0},N=E=>typeof E?.selectActiveInteraction=="function"?E.selectActiveInteraction():typeof E?.selectIsChoiceVisible=="function"&&E.selectIsChoiceVisible()?{source:"choice"}:null,_=(E,S)=>!(!E||typeof E!="object"||Array.isArray(E)||E._interactionSource!==S?.source||S.source==="form"&&E._formKey&&E._formKey!==S.formKey||S.source==="form"&&E.formKey&&E.formKey!==S.formKey),U=(E={},S)=>{if(_(E,S))return!0;let j=E?.actions;return!j||typeof j!="object"||Array.isArray(j)?!1:Object.values(j).some(q=>_(q,S))},M=(E,S={})=>{if(!S?.actions)return!1;let j=N(E);return!j||j.source==="choice"?!1:!U(S,j)},P=({preprocessPayload:E,onEvent:S}={})=>async(j,q={})=>{let H=e();if(M(H,q))return S?.(j,q);let W=await E?.(j,q)??q;if(M(H,W))return S?.(j,W);if(V(j,W),W?.actions){let ft=W?._event?{_event:W._event}:W?.event?{_event:W.event}:void 0,Ne;W?.bypassChoice===!0?Ne={bypassChoice:!0}:W?._interactionSource&&(Ne={interactionSource:W._interactionSource}),Ne?H.handleActions(W.actions,ft,Ne):H.handleActions(W.actions,ft)}return S?.(j,W)},B=E=>{let S=e(),j=mu(E);j.forEach(H=>{if(!ci[H.name]&&!n)throw new Error(`Unhandled pending effect "${H.name}".`)});let q={engine:S,routeGraphics:t,ticker:r,autoTimer:c,skipTimer:l,nextLineConfigTimerState:u,trackRenderDispatch:b,getRenderDispatchCount:R,enqueuePersistenceWrite:x};for(let H of j){let W=ci[H.name];if(W){W(q,H.payload);continue}n(H,q)}};return B.handleRouteGraphicsEvent=V,B.createRouteGraphicsEventHandler=P,B},yu=gu;var bu=(e,t={})=>{let{resources:r={}}=t;return Nr(e,r)};var Nf=tn;export{yu as createEffectsHandler,Xl as createIndexedDbPersistence,Nf as default,Is as resolveComputedVariables,bu as resolveLayoutReferences};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "route-engine-js",
3
- "version": "1.14.2",
3
+ "version": "1.14.3",
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",