route-engine-js 1.31.0 → 1.31.2

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 na=Object.defineProperty;var ra=(e,t)=>{for(var n in t)na(e,n,{get:t[n],enumerable:!0})};var so=Symbol.for("immer-nothing"),to=Symbol.for("immer-draftable"),he=Symbol.for("immer-state");function ge(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var ot=Object.getPrototypeOf;function se(e){return!!e&&!!e[he]}function ze(e){return e?ao(e)||Array.isArray(e)||!!e[to]||!!e.constructor?.[to]||qt(e)||Ht(e):!1}var oa=Object.prototype.constructor.toString();function ao(e){if(!e||typeof e!="object")return!1;let t=ot(e);if(t===null)return!0;let n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return n===Object?!0:typeof n=="function"&&Function.toString.call(n)===oa}function Vn(e){return se(e)||ge(15,e),e[he].base_}function Mt(e,t){zt(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function zt(e){let t=e[he];return t?t.type_:Array.isArray(e)?1:qt(e)?2:Ht(e)?3:0}function Ln(e,t){return zt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function co(e,t,n){let r=zt(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function ia(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function qt(e){return e instanceof Map}function Ht(e){return e instanceof Set}function Ue(e){return e.copy_||e.base_}function $n(e,t){if(qt(e))return new Map(e);if(Ht(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=ao(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[he];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let s=o[i],l=r[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(r[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(ot(e),r)}else{let r=ot(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function jn(e,t=!1){return Wt(e)||se(e)||!ze(e)||(zt(e)>1&&(e.set=e.add=e.clear=e.delete=sa),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>jn(r,!0))),e}function sa(){ge(2)}function Wt(e){return Object.isFrozen(e)}var aa={};function qe(e){let t=aa[e];return t||ge(0,e),t}var bt;function lo(){return bt}function ca(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function no(e,t){t&&(qe("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Tn(e){Dn(e),e.drafts_.forEach(la),e.drafts_=null}function Dn(e){e===bt&&(bt=e.parent_)}function ro(e){return bt=ca(bt,e)}function la(e){let t=e[he];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function oo(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[he].modified_&&(Tn(t),ge(4)),ze(e)&&(e=Bt(t,e),t.parent_||Ut(t,e)),t.patches_&&qe("Patches").generateReplacementPatches_(n[he].base_,e,t.patches_,t.inversePatches_)):e=Bt(t,n,[]),Tn(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==so?e:void 0}function Bt(e,t,n){if(Wt(t))return t;let r=t[he];if(!r)return Mt(t,(o,i)=>io(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Ut(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let o=r.copy_,i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Mt(i,(l,a)=>io(e,r,o,l,a,n,s)),Ut(e,o,!1),n&&e.patches_&&qe("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function io(e,t,n,r,o,i,s){if(se(o)){let l=i&&t&&t.type_!==3&&!Ln(t.assigned_,r)?i.concat(r):void 0,a=Bt(e,o,l);if(co(n,r,a),se(a))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(ze(o)&&!Wt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Bt(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&Ut(e,o)}}function Ut(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&jn(t,n)}function ua(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:lo(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=Fn;n&&(o=[r],i=It);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var Fn={get(e,t){if(t===he)return e;let n=Ue(e);if(!Ln(n,t))return da(e,n,t);let r=n[t];return e.finalized_||!ze(r)?r:r===On(e.base_,t)?(kn(e),e.copy_[t]=Pn(r,e)):r},has(e,t){return t in Ue(e)},ownKeys(e){return Reflect.ownKeys(Ue(e))},set(e,t,n){let r=uo(Ue(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=On(Ue(e),t),i=o?.[he];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(ia(n,o)&&(n!==void 0||Ln(e.base_,t)))return!0;kn(e),Nn(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return On(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,kn(e),Nn(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=Ue(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ge(11)},getPrototypeOf(e){return ot(e.base_)},setPrototypeOf(){ge(12)}},It={};Mt(Fn,(e,t)=>{It[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});It.deleteProperty=function(e,t){return It.set.call(this,e,t,void 0)};It.set=function(e,t,n){return Fn.set.call(this,e[0],t,n,e[0])};function On(e,t){let n=e[he];return(n?Ue(n):e)[t]}function da(e,t,n){let r=uo(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function uo(e,t){if(!(t in e))return;let n=ot(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=ot(n)}}function Nn(e){e.modified_||(e.modified_=!0,e.parent_&&Nn(e.parent_))}function kn(e){e.copy_||(e.copy_=$n(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var fa=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){let i=n;n=t;let s=this;return function(a=i,...c){return s.produce(a,u=>n.call(this,u,...c))}}typeof n!="function"&&ge(6),r!==void 0&&typeof r!="function"&&ge(7);let o;if(ze(t)){let i=ro(this),s=Pn(t,void 0),l=!0;try{o=n(s),l=!1}finally{l?Tn(i):Dn(i)}return no(i,r),oo(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===so&&(o=void 0),this.autoFreeze_&&jn(o,!0),r){let i=[],s=[];qe("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ge(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,a=>t(a,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){ze(e)||ge(8),se(e)&&(e=He(e));let t=ro(this),n=Pn(e,void 0);return n[he].isManual_=!0,Dn(t),n}finishDraft(e,t){let n=e&&e[he];(!n||!n.isManual_)&&ge(9);let{scope_:r}=n;return no(r,t),oo(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){let o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));let r=qe("Patches").applyPatches_;return se(e)?r(e,t):this.produce(e,o=>r(o,t))}};function Pn(e,t){let n=qt(e)?qe("MapSet").proxyMap_(e,t):Ht(e)?qe("MapSet").proxySet_(e,t):ua(e,t);return(t?t.scope_:lo()).drafts_.push(n),n}function He(e){return se(e)||ge(10,e),fo(e)}function fo(e){if(!ze(e)||Wt(e))return e;let t=e[he],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=$n(e,t.scope_.immer_.useStrictShallowCopy_)}else n=$n(e,!0);return Mt(n,(r,o)=>{co(n,r,fo(o))}),t&&(t.finalized_=!1),n}var me=new fa,Mn=me.produce,Ap=me.produceWithPatches.bind(me),wp=me.setAutoFreeze.bind(me),Ep=me.setUseStrictShallowCopy.bind(me),xp=me.applyPatches.bind(me),vp=me.createDraft.bind(me),Cp=me.finishDraft.bind(me);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},k={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},it={NOT:0};var v=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},pe=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Bn=e=>{if(!e||e.trim()==="")throw new v("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new v(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${n}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let n of t)if(e.trim().endsWith(n))throw new v(`Incomplete comparison expression - missing right operand (got: '${e}')`)},po=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,n]=e.split(" in ");if(!n||n.trim()==="")throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);let r=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of r){if(!o)throw new 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 ho=(e,t,n=!1)=>{if(t===null)return new pe(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new pe(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new pe(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new pe(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},mo=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new pe(`Unknown function '${e}' (${n})`)};var pa=(e,t,n={})=>{let r={},o={};n&&typeof n=="object"&&(n.functions!==void 0||n.partials!==void 0?(r=n.functions||{},o=n.partials||{}):typeof n=="object"&&(r=n));let s=L(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},L=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return K(e.var,n,r);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return K(e.path,n,r);if(e.type===m.INTERPOLATION)return ma(e.parts,t,n,r);switch(e.type){case m.FUNCTION:return yo(e,t,n,r);case m.BINARY:return bo(e,t,n,r);case m.UNARY:return Io(e,t,n,r);case m.CONDITIONAL:return ya(e,t,n,r);case m.LOOP:return Ea(e,t,n,r);case m.OBJECT:return va(e,t,n,r);case m.ARRAY:return Ca(e,t,n,r);case m.PARTIAL:return Sa(e,t,n,r);case m.PATH_REFERENCE:return _a(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},go=new Map,ha=e=>{let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(i==="]"){if(r&&n){let s=n.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let l=s.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:s});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},K=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=go.get(e);if(!r){let i=[],s="",l=0;for(let a=0;a<e.length;a++){let c=e[a];c==="["?(l++,s+=c):c==="]"?(l--,s+=c):c==="."&&l===0?s&&(i.push(s),s=""):s+=c}s&&i.push(s),r=[];for(let a of i){let c=ha(a.trim());r.push(...c)}go.set(e,r)}let o=t;for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="property"&&s.value in n){o=n[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},ma=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},yo=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw mo(e.name,o);let s=e.args.map(l=>L(l,t,n,r));return i(...s)},$e=(e,t,n,r)=>{if(e.var&&!e.type)return K(e.var,n,r);switch(e.type){case m.VARIABLE:return K(e.path,n,r);case m.LITERAL:return e.value;case m.BINARY:return bo(e,t,n,r);case m.UNARY:return Io(e,t,n,r);case m.FUNCTION:return yo(e,t,n,r);default:return L(e,t,n,r)}},bo=(e,t,n,r)=>{if(e.op===k.AND||e.op===k.OR){let s=$e(e.left,t,n,r),l=$e(e.right,t,n,r);switch(e.op){case k.AND:return s&&l;case k.OR:return s||l}}let o=L(e.left,t,n,r),i=L(e.right,t,n,r);switch(e.op){case k.EQ:return o==i;case k.NEQ:return o!=i;case k.GT:return o>i;case k.LT:return o<i;case k.GTE:return o>=i;case k.LTE:return o<=i;case k.IN:return Array.isArray(i)?i.includes(o):!1;case k.ADD:if(typeof o!="number"||typeof i!="number")throw new pe(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case k.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new pe(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Io=(e,t,n,r)=>{let o=e.op===it.NOT?$e(e.operand,t,n,r):L(e.operand,t,n,r);if(e.op===it.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},ga=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(K(o.path,n,r)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?L(a.parsedKey,t,n,r):a.key,u=a.value;if(u.type===m.LITERAL)l[c]=u.value;else if(u.type===m.VARIABLE)l[c]=K(u.path,n,r);else if(u.type===m.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===m.VARIABLE){let p=K(f.path,n,r);d.push(p!=null?String(p):"")}else{let p=L(f,t,n,r);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=L(u,t,n,r)}return l}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?L(a.parsedKey,t,n,r):a.key,u=a.value;if(u.type===m.LITERAL)l[c]=u.value;else if(u.type===m.VARIABLE)l[c]=K(u.path,n,r);else if(u.type===m.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===m.VARIABLE){let p=K(f.path,n,r);d.push(p!=null?String(p):"")}else{let p=L(f,t,n,r);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=L(u,t,n,r)}return l}}}return null},ya=(e,t,n,r)=>{let o=ga(e,t,n,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||$e(s,t,n,r))return L(e.bodies[i],t,n,r)}return Ao},ba=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===m.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===m.VARIABLE){let o=n.conditions[0].path,i=n.bodies[0];if(o.startsWith(r+".")){let s=o.substring(r.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let a of i.properties)if(a.parsedKey)return null;let l=[];for(let a=0;a<t.length;a++){let c=t[a];if(c[s]){let u={};for(let d of i.properties){let f=d.key,p=d.value;if(p.type===m.LITERAL)u[f]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===r)u[f]=c;else if(h.startsWith(r+".")){let g=h.substring(r.length+1);u[f]=c[g]}else return null}else if(p.type===m.INTERPOLATION){let h=[],g=!0;for(let b of p.parts)if(typeof b=="string")h.push(b);else if(b.type===m.VARIABLE){let A=b.path;if(A===r)h.push(c!=null?String(c):"");else if(A.startsWith(r+".")){let w=A.substring(r.length+1),C=c[w];h.push(C!=null?String(C):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[f]=h.join("")}else return null}l.push(u)}}return l}}}return null},Ia=(e,t)=>{let n=e.body,r=e.itemVar,o=ba(e,t);if(o!==null)return o;if(n.type===m.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let l of n.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of n.properties){let a=l.key,c=l.value;if(c.type===m.LITERAL)i.push({key:a,type:"literal",value:c.value});else if(c.type===m.VARIABLE){let u=c.path;if(u===r)i.push({key:a,type:"item"});else if(u.startsWith(r+".")){let d=u.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:a,type:"prop",prop:d});else{s=!1;break}}else{s=!1;break}}else if(c.type===m.INTERPOLATION&&c.parts.length===1){let u=c.parts[0];if(u.type===m.VARIABLE){let d=u.path;if(d===r)i.push({key:a,type:"item_string"});else if(d.startsWith(r+".")){let f=d.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:a,type:"prop_string",prop:f});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let l=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let a=0;a<t.length;a++){let c=t[a];l[a]={id:c.id,title:c.title!=null?String(c.title):"",completed:c.completed}}else for(let a=0;a<t.length;a++){let c=t[a],u={};for(let d of i)if(d.type==="literal")u[d.key]=d.value;else if(d.type==="item")u[d.key]=c;else if(d.type==="prop")u[d.key]=c[d.prop];else if(d.type==="item_string")u[d.key]=c!=null?String(c):"";else if(d.type==="prop_string"){let f=c[d.prop];u[d.key]=f!=null?String(f):""}l[a]=u}return l}}return null},Aa=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let l=e.itemVar,a=e.indexVar;for(let c=0;c<o.length;c++){let u=o[c],d={},f={...r,[l]:u,...a&&{[a]:c}};f.__paths__||(f.__paths__=r.__paths__||{});let p=e.iterable.path||"";if(r&&r.__paths__&&p){let h=p.split("."),g=h[0];g in r.__paths__&&(p=r.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}f.__paths__={...f.__paths__,[l]:`${p}[${c}]`,...a&&{[a]:c}};for(let h of s.properties){let g=h.parsedKey?L(h.parsedKey,t,n,f):h.key,b=h.value;if(b.type===m.LITERAL)d[g]=b.value;else if(b.type===m.VARIABLE){let A=b.path;if(A===l)d[g]=u;else if(A===a)d[g]=c;else if(A.startsWith(l+".")){let w=A.substring(l.length+1);!w.includes(".")&&!w.includes("[")?d[g]=u[w]:d[g]=K(A,n,{...r,[l]:u,...a&&{[a]:c}})}else d[g]=K(A,n,{...r,[l]:u,...a&&{[a]:c}})}else if(b.type===m.INTERPOLATION){let A=[];for(let w of b.parts)if(typeof w=="string")A.push(w);else if(w.type===m.VARIABLE){let C=w.path,R;if(C===l)R=u;else if(C===a)R=c;else if(C.startsWith(l+".")){let V=C.substring(l.length+1);!V.includes(".")&&!V.includes("[")?R=u[V]:R=K(C,n,{...r,[l]:u,...a&&{[a]:c}})}else R=K(C,n,{...r,[l]:u,...a&&{[a]:c}});A.push(R!=null?String(R):"")}else{let C={...r,[l]:u,...a&&{[a]:c}},R=L(w,t,n,C);A.push(R!=null?String(R):"")}d[g]=A.join("")}else{let A={...r,[l]:u,...a&&{[a]:c}};d[g]=L(b,t,n,A)}}i.push(d)}return i}return null},wa=(e,t,n)=>{let r=e.body;if(r.type===m.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===m.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===m.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===m.OBJECT&&s.properties.length===2){let l=s.properties[0],a=s.properties[1];if(l.key==="id"&&l.value.type===m.VARIABLE&&l.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===m.CONDITIONAL){let c=[];for(let u=0;u<t.length;u++){let d=t[u];if(d.visible){let f={id:d.id};d.highlighted?(f.highlight=!0,f.message=`This item is highlighted: ${d.name}`):(f.highlight=!1,f.message=d.name),c.push(f)}}return c}}}}return null},Ea=(e,t,n,r)=>{let o=L(e.iterable,t,n,r);if(!Array.isArray(o)){let c,u=!1;if(e.iterable.type===m.FUNCTION){u=!0;let f=e.iterable.args.map(p=>p.type===m.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===m.VARIABLE?p.path:p.type===m.FUNCTION?`${p.name}(...)`:"?").join(", ");c=`${e.iterable.name}(${f})`}else c=e.iterable.path||"undefined";let d=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${c}`;throw ho(d,o,u)}if(!e.indexVar){let c=wa(e,o,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=Ia(e,o);if(c!==null)return c}let i=Aa(e,t,n,r,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(r&&r.__paths__&&l){let c=l.split("."),u=c[0];u in r.__paths__&&(l=r.__paths__[u],c.length>1&&(l+="."+c.slice(1).join(".")))}let a=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(c=>c.type===m.OBJECT&&c.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let c=0;c<o.length;c++){let u=e.indexVar?{...r,[e.itemVar]:o[c],[e.indexVar]:c}:{...r,[e.itemVar]:o[c]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${c}]`},e.indexVar&&(u.__paths__[e.indexVar]=c);let d=L(e.body,t,n,u);if(Array.isArray(d)&&d.length===1&&!a){let f=d[0];s.push(f===void 0?{}:f)}else s.push(d===void 0?{}:d)}return s},xa=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let l={},a={},c=!0;for(let u of s.properties){let d=u.parsedKey?L(u.parsedKey,t,n,r):u.key,f=u.value;if(f.type===m.LITERAL)a[d]=f.value;else if(f.type===m.VARIABLE)a[d]=K(f.path,n,r);else if(f.type===m.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=K(h.path,n,r);p.push(g!=null?String(g):"")}else{c=!1;break}if(!c)break;a[d]=p.join("")}else if(f.type===m.OBJECT&&f.properties.length<=5){let p={};for(let h of f.properties){let g=h.key,b=h.value;if(b.type===m.LITERAL)p[g]=b.value;else if(b.type===m.VARIABLE)p[g]=K(b.path,n,r);else if(b.type===m.INTERPOLATION){let A=[];for(let w of b.parts)if(typeof w=="string")A.push(w);else if(w.type===m.VARIABLE){let C=K(w.path,n,r);A.push(C!=null?String(C):"")}else{c=!1;break}if(!c)break;p[g]=A.join("")}else{c=!1;break}}if(!c)break;a[d]=p}else{c=!1;break}}if(c)return l[i]=a,l}}return null},va=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!$e(e.whenCondition,o,n,r))return;let i=xa(e,t,n,r);if(i!==null)return i;if(e.fast){let c={};for(let u of e.properties){let d=u.parsedKey?L(u.parsedKey,t,n,r):u.key,f=u.value;if(f.type===m.LITERAL)c[d]=f.value;else if(f.type===m.VARIABLE)c[d]=K(f.path,n,r);else if(f.type===m.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=K(h.path,n,r);p.push(g!=null?String(g):"")}else{let g=L(h,t,n,r);p.push(g!=null?String(g):"")}c[d]=p.join("")}else c[d]=L(f,t,n,r)}return c}let s={},l=null,a=!1;for(let c of e.properties)if(!c.key.startsWith("$if ")&&!c.key.match(/^\$if\s+\w+.*:?$/)&&!c.key.startsWith("$elif")&&!c.key.startsWith("$else")&&!c.key.startsWith("$for ")){a=!0;break}for(let c of e.properties)if(c.key.startsWith("$if ")||c.key.match(/^\$if\s+\w+.*:?$/)){let u=L(c.value,t,n,r);if(!a&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(c.key.startsWith("$for ")){if(e.properties.length===1)return L(c.value,t,n,r)}else{let u=c.value;if(u&&u.type===m.OBJECT&&u.properties){let d=u.properties.find(f=>f.key.startsWith("$for "));if(d){let f=L(d.value,t,n,r);f!==void 0&&(s[c.key]=f)}else{let f=L(c.value,t,n,r);f!==void 0&&(s[c.key]=f)}}else{let d=c.parsedKey?L(c.parsedKey,t,n,r):c.key,f=L(c.value,t,n,r);f!==void 0&&(s[d]=f)}}return s},Ao={},Ca=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=L(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,n,r);s!==Ao&&s!==void 0&&o.push(s)}return o},Sa=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},a=t.functions||t;if(s&&!$e(s,a,n,r))return;if(!l[o])throw new pe(`Partial '${o}' is not defined`);let c=r._partialStack||[];if(c.includes(o))throw new pe(`Circular partial reference detected: ${o}`);let u=l[o],d=n,f={...r,_partialStack:[...c,o]};if(r){d={...n};for(let p of Object.keys(r))p.startsWith("_")||(d[p]=r[p])}if(i){let p=L(i,t,n,r);d={...d,...p}}return L(u,t,d,f)},_a=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),s=i[0],l=i.slice(1);if(!r||!(s in r))throw new pe(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(s in r.__paths__))throw new pe(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=r.__paths__[s];if(typeof a=="number"){if(l.length>0)throw new pe(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return l.length>0&&(a+="."+l.join(".")),a};var Un=pa;var Ra=/\$\{([^}]*)\}/g,Oa=/#\{([^}]*)\}/g,Eo=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=ka(o,t);return{isFunction:!0,type:m.FUNCTION,name:r,args:i}},ka=(e,t={})=>e.trim()?La(e).map(r=>$a(r.trim(),t)):[],La=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],a=s>0?e[s-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,n+=l):o&&l===i&&a!=="\\"?(o=!1,i="",n+=l):!o&&l==="("?(r++,n+=l):!o&&l===")"?(r--,n+=l):!o&&l===","&&r===0?(t.push(n),n=""):n+=l}return n&&t.push(n),t},$a=(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 n=Eo(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:l,type:a}of o){let c=0;for(;c<r.length;){let u=We(r.substring(c),l);if(u===-1)break;let d=c+u;d>i&&(i=d,s={op:l,type:a}),c=d+l.length}}if(i!==-1)try{return Z(r,t)}catch{return{type:m.VARIABLE,path:r}}return{type:m.VARIABLE,path:r}},xo=/^\w+\(.*\)$/,Ta=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Da=e=>{if(!(!e||e.trim()===""||xo.test(e))&&Ta.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}"`)},wo=e=>{let t=e.trim();if(xo.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}},At=(e,t={})=>{let n=e.trim();Da(n);let r=Eo(n,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};if(n.includes("[")&&!/[\s+\-*/%|&?:]/.test(n)){let o=0;for(let i of n)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:n}},zn=(e,t={})=>{let n=e,r=[];(e.includes("\\${")||e.includes("\\#{"))&&(n=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),n=n.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),n=n.replace(/\\(\$\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${r.length}__`;return r.push(u),d}),n=n.replace(/\\(#\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${r.length}__`;return r.push(u),d}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...n.matchAll(Ra)],i=[...n.matchAll(Oa)],s=[...o.map(c=>({match:c,type:"variable"})),...i.map(c=>({match:c,type:"pathref"}))].sort((c,u)=>c.match.index-u.match.index);if(s.length===0){let c=n;for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);return{type:m.LITERAL,value:c}}if(s.length===1&&s[0].match[0]===n&&r.length===0){let{match:c,type:u}=s[0];try{return u==="variable"?At(c[1],t):wo(c[1])}catch(d){if(d.message==="Invalid array index syntax")return{type:m.LITERAL,value:n};throw d}}let l=[],a=0;for(let{match:c,type:u}of s){let[d,f]=c,p=c.index;if(p>a){let h=n.substring(a,p);for(let g=0;g<r.length;g++)h=h.replace(`__ESCAPED_${g}__`,r[g]);h&&l.push(h)}try{let h;u==="variable"?h=At(f.trim(),t):h=wo(f.trim()),l.push(h)}catch(h){if(h.message==="Invalid array index syntax")l.push(d);else throw h}a=p+d.length}if(a<n.length){let c=n.substring(a);for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);c&&l.push(c)}return{type:m.INTERPOLATION,parts:l}};var Wn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),So=e=>Object.keys(e),ae=e=>e.join("."),Te=(e,t,n)=>{let r=So(e).filter(o=>!t.has(o));if(r.length>0)throw new v(`Unexpected key '${r[0]}' in condition JSON at '${ae(n)}'`)},De=(e,t)=>typeof e=="string"?zn(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Pa(e,t):Va(e,t):{type:m.LITERAL,value:e},Na=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new v("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new v("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new v("Empty $each body not allowed");if(n.$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 ${r}`]:n}},Pa=(e,t)=>{let n=[],r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let a=Na(i),c=Object.keys(a);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let u=Co(c[0],a[c[0]],t,!0);n.push(u),r=!0;continue}}catch(a){throw a instanceof v?a:new v(a.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let a=Co(l[0],i[l[0]],t);n.push(a),r=!0;continue}}let s=De(i,t);n.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)&&(r=!0)}return{type:m.ARRAY,items:n,fast:!r}},Va=(e,t)=>{let n=[],r=!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 a=["$if","$elif","$else","$for"],c=[];for(let[A]of i)for(let w of a)if(A===w||A.startsWith(w+" ")||A.startsWith(w+"#")){c.push(w);break}if(c.length>0)throw new v(`Cannot use $partial with ${c.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:d,...f}=e,p={},h=!1;for(let[A,w]of Object.entries(f)){let C=A;(A.startsWith("\\$")||A.startsWith("$$"))&&(C=A.slice(1)),p[C]=w,h=!0}let g=null;if(h&&(g=De(p,t),g.type===m.OBJECT)){let A=!1;for(let w of g.properties)if(w.value.type===m.VARIABLE||w.value.type===m.INTERPOLATION||w.value.type===m.FUNCTION||w.value.type===m.CONDITIONAL||w.value.type===m.OBJECT&&!w.value.fast||w.value.type===m.ARRAY&&!w.value.fast){A=!0;break}A&&(g.fast=!1)}let b={type:m.PARTIAL,name:u,data:g};return d!==void 0&&(b.whenCondition=vo(d,t)),b}for(let[a,c]of i)if(a==="$when"){if(o!==null)throw new v("Multiple '$when' directives on the same object are not allowed");if(c==null)throw new v("Missing condition expression after '$when'");o=vo(c,t),r=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new v("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[a,c]=i[s];if(a==="$when"){s++;continue}if(a==="$each")throw new v("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let u=ja(i,s,t);n.push({key:a,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let u=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",d=u?`:${u}`:"";throw new v(`$for loops must be inside arrays - use '- $for${d} item in items:' instead of '$for${d} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(a.startsWith("$elif ")||a.startsWith("$else"))throw new v(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new v("Missing condition expression after '$if'");{let u=De(c,t);(u.type===m.FUNCTION||u.type===m.CONDITIONAL||u.type===m.PARTIAL||u.type===m.OBJECT&&!u.fast||u.type===m.ARRAY&&!u.fast)&&(r=!0);let d=zn(a,t),f={key:a,value:u};(d.type!==m.LITERAL||d.value!==a)&&(f.parsedKey=d),n.push(f),s++}}}let l={type:m.OBJECT,properties:n,fast:!r};return o&&(l.whenCondition=o),l},ja=(e,t,n={})=>{let r=[],o=[],i=t,[s,l]=e[i],a=null,c;if(s.startsWith("$if#")){let d=s.match(/^\$if#(\w+)\s+(.+)$/);if(d)a=d[1],c=d[2];else throw new v(`Invalid conditional syntax: ${s}`)}else c=s.substring(4),c.endsWith(":")&&(c=c.slice(0,-1).trim());Bn(c);let u=Z(c,n);for(r.push(u),o.push(De(l,n)),i++;i<e.length;){let[d,f]=e[i],p=!1,h;if(a?d.startsWith(`$elif#${a} `)?(h=d.substring(`$elif#${a} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(d===`$else#${a}`||d===`$else#${a}:`)&&(p=!0,h=null):d.startsWith("$elif ")?(h=d.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(d==="$else"||d==="$else:")&&(p=!0,h=null),p){if(h===null)r.push(null);else{Bn(h);let g=Z(h,n);r.push(g)}if(o.push(De(f,n)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:r,bodies:o,id:a},nextIndex:i}},qn={eq:k.EQ,neq:k.NEQ,gt:k.GT,gte:k.GTE,lt:k.LT,lte:k.LTE,in:k.IN,add:k.ADD,sub:k.SUBTRACT},Hn={all:k.AND,any:k.OR},Fa=new Set(["var","literal","call","not",...Object.keys(qn),...Object.keys(Hn)]),Ma=(e,t,n)=>{if(!Array.isArray(e))throw new v(`Condition JSON operator '${t}' at '${ae(n)}' requires an array`);if(e.length!==2)throw new v(`Condition JSON operator '${t}' at '${ae(n)}' requires exactly 2 operands`);return e},Ba=(e,t,n,r,o)=>{if(!Array.isArray(e))throw new v(`Condition JSON operator '${t}' at '${ae(o)}' requires an array`);if(e.length===0)throw new v(`Condition JSON operator '${t}' at '${ae(o)}' requires at least 1 condition`);return e.map((s,l)=>Ce(s,r,[...o,l])).reduce((s,l)=>({type:m.BINARY,op:n,left:s,right:l}))},Ua=(e,t,n)=>{let r,o;if(typeof e.call=="string")r=e.call,o=e.args??[],Te(e,new Set(["call","args"]),n);else if(Wn(e.call))r=e.call.name,o=e.call.args??[],Te(e,new Set(["call"]),n),Te(e.call,new Set(["name","args"]),[...n,"call"]);else throw new v(`Condition JSON call at '${ae(n)}' requires a function name`);if(typeof r!="string"||r.trim()==="")throw new v(`Condition JSON call at '${ae(n)}' requires a non-empty function name`);if(!/^\w+$/.test(r))throw new v(`Invalid condition JSON function name '${r}' at '${ae(n)}'`);if(!Array.isArray(o))throw new v(`Condition JSON call '${r}' at '${ae(n)}' requires args to be an array`);return{type:m.FUNCTION,name:r,args:o.map((i,s)=>Ce(i,t,[...n,"args",s]))}},Ce=(e,t={},n=["$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 '${ae(n)}' must be wrapped in an operator or { literal: [...] }`);if(!Wn(e))throw new v(`Invalid condition JSON value at '${ae(n)}'`);let r=So(e);if(r.length===0)throw new v(`Condition JSON object at '${ae(n)}' must contain an operator`);let o=r.filter(s=>Fa.has(s));if(o.length===0)throw new v(`Unknown condition JSON operator '${r[0]}' at '${ae(n)}'`);if(o.length>1)throw new v(`Condition JSON at '${ae(n)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(Te(e,new Set(["var"]),n),typeof e.var!="string"||e.var.trim()==="")throw new v(`Condition JSON var at '${ae(n)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return Te(e,new Set(["literal"]),n),{type:m.LITERAL,value:e.literal};if(i==="call")return Ua(e,t,n);if(i==="not")return Te(e,new Set(["not"]),n),{type:m.UNARY,op:it.NOT,operand:Ce(e.not,t,[...n,"not"])};if(i in Hn)return Te(e,new Set([i]),n),Ba(e[i],i,Hn[i],t,[...n,i]);if(i in qn){Te(e,new Set([i]),n);let s=Ma(e[i],i,[...n,i]);return{type:m.BINARY,op:qn[i],left:Ce(s[0],t,[...n,i,0]),right:Ce(s[1],t,[...n,i,1])}}throw new v(`Unknown condition JSON operator '${i}' at '${ae(n)}'`)},vo=(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 Z(e,t)}return Wn(e)||Array.isArray(e)?Ce(e,t):{type:m.LITERAL,value:e}},Z=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let c=e.slice(1,-1),u=0,d=!0;for(let f=0;f<c.length;f++)if(c[f]==="("?u++:c[f]===")"&&u--,u<0){d=!1;break}if(d&&u===0)return Z(c,t)}let n=We(e,"||");if(n!==-1)return{type:m.BINARY,op:k.OR,left:Z(e.substring(0,n).trim(),t),right:Z(e.substring(n+2).trim(),t)};let r=We(e,"&&");if(r!==-1)return{type:m.BINARY,op:k.AND,left:Z(e.substring(0,r).trim(),t),right:Z(e.substring(r+2).trim(),t)};let o=[{op:">=",type:k.GTE},{op:"<=",type:k.LTE},{op:"==",type:k.EQ},{op:"!=",type:k.NEQ},{op:">",type:k.GT},{op:"<",type:k.LT},{op:" in ",type:k.IN}];for(let{op:c,type:u}of o){let d=We(e,c);if(d!==-1)return{type:m.BINARY,op:u,left:Z(e.substring(0,d).trim(),t),right:Z(e.substring(d+c.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:k.ADD},{op:" - ",type:k.SUBTRACT}];for(let{op:c,type:u}of l){let d=0;for(;d<e.length;){let f=We(e.substring(d),c);if(f===-1)break;let p=d+f;p>i&&(i=p,s={op:c,type:u}),d=p+c.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:Z(e.substring(0,i).trim(),t),right:Z(e.substring(i+s.op.length).trim(),t)};let a=[" * "," / "," % "];for(let c of a)if(We(e,c)!==-1)throw new v(`Arithmetic operations are not allowed in conditionals: "${c}"`);return e.startsWith("!")?{type:m.UNARY,op:it.NOT,operand:Z(e.substring(1).trim(),t)}:_o(e,t)},We=(e,t)=>{let n=0,r=0;for(;r<=e.length-t.length;){if(e[r]==="(")n++;else if(e[r]===")")n--;else if(n===0&&e.substring(r,r+t.length)===t)return r;r++}return-1},za=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}},_o=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return At(n,t);let o=za(n);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:m.VARIABLE,path:n};try{return At(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},qa=(e,t=!1)=>{let n=t?"$each":"$for";try{po(e)}catch(r){if(r instanceof v&&t){let o=r.message.replace(/\$for/g,"$each");throw new v(o.replace("Parse Error: ",""))}throw r}},Co=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let b=r?"$each":"$for";throw new v(`Invalid loop syntax (got: '${e.replace("$for",b)}')`)}let s=i[1],l=i[2].trim();qa(l,r);let a=l.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let b=r?"$each":"$for";throw new v(`Invalid loop syntax - missing 'in' keyword (got: '${b} ${l}')`)}let c=a[1].trim(),u=a[2].trim(),d,f=null;if(c.includes(",")){let b=c.split(",").map(A=>A.trim());if(b.length!==2)throw new v(`Invalid loop variables: ${c}. Expected format: "item" or "item, index"`);d=b[0],f=b[1]}else d=c;let p=["this","undefined","null","true","false"];if(p.includes(d))throw new v(`Reserved variable name: ${d}`);if(f&&p.includes(f))throw new v(`Reserved variable name: ${f}`);let h=_o(u,n),g=De(t,n);return{type:m.LOOP,itemVar:d,indexVar:f,iterable:h,body:g,flatten:s!=="nested"}};var Ha=(e,t={})=>{let{functions:n={}}=t;return De(e,n)},Yt=Ha;var wt={};ra(wt,{now:()=>Wa});var Wa=()=>Date.now();var Ya=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...wt,...r},s=Yt(e,{functions:i}),l={};for(let[a,c]of Object.entries(o))l[a]=Yt(c,{functions:i});return Un(s,t,{functions:i,partials:l})},ce=Ya;var Ga=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Ka=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Ja=(e,t)=>{if(Ga(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new v("Empty condition expression");return Z(e,t)}return Ce(e,t)},Xa=(e,t={},n={})=>{let r=Ka(n),o={...wt,...r},i=Ja(e,o);return!!$e(i,{functions:o,partials:{}},t,{})},Yn=Xa;var xt=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return Yn(e,t)},Qa=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],To=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=a=>a,transformActionFirstArgument:l=a=>a}=n;for(let[a,c]of Object.entries(t))a!=="createInitialState"&&(a.startsWith("select")?o[a]=(...u)=>c(s(r),...u):i[a]=(...u)=>{let d;return r=Mn(r,p=>{let h=c(l(p),...u);d=h!==void 0&&!se(h)?h:void 0}),d});return{...o,...i}},Jt=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return Mn(r,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var Za=(e,t)=>{if(e.default!==void 0)return e.default;let n=["number","boolean","string","object"];if(!n.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${n.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},be=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),Et=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Do=e=>{let t=se(e)?He(e):e;return structuredClone(t)},ec=({characterId:e,resourceCharacter:t,variables:n={}}={})=>{if(!be(t,"nameVariableId"))return;let r=t.nameVariableId,o=n?.[r];if(typeof o!="string")throw new Error(`Character "${e}" nameVariableId "${r}" must resolve to a string variable`);return o},Xt=({characterId:e,character:t,characterName:n,characters:r={},variables:o={}}={})=>{let i=e?r?.[e]:void 0;if(t?.name!==void 0)return t.name;if(n!==void 0)return n;let s=ec({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},Ne=e=>be(e,"computed"),st=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([n])=>!Ne(t[n]))),tc=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),Gn=(e,t)=>{let n=e;for(let r of t){if(n==null)return;n=n[r]}return n},nc=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let n=tc(e),[r,o,...i]=n;if(r==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return Gn(s,i)}return r==="runtime"?Gn(t.runtime,n.slice(1)):Gn(t,n)},rc=(e,t,n)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(n!==void 0&&t.length!==n)throw new Error(`Computed expression operator "${e}" requires ${n} operand(s)`)},Ro=(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`)},oc=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},we=(e,t,n,r)=>(rc(e,t,r),t.map(o=>Kt(o,n))),ye=(e,t,n,r)=>{let o=we(e,t,n,r);return o.forEach(i=>oc(e,i)),o},ic=(e,t,n)=>{switch(e){case"var":return nc(t,n);case"add":{let[r,o]=ye(e,t,n,2);return r+o}case"sub":{let[r,o]=ye(e,t,n,2);return r-o}case"mul":{let[r,o]=ye(e,t,n,2);return r*o}case"div":{let[r,o]=ye(e,t,n,2);return r/o}case"mod":{let[r,o]=ye(e,t,n,2);return r%o}case"neg":{let[r]=ye(e,t,n,1);return-r}case"round":{let[r]=ye(e,t,n,1);return Math.round(r)}case"floor":{let[r]=ye(e,t,n,1);return Math.floor(r)}case"ceil":{let[r]=ye(e,t,n,1);return Math.ceil(r)}case"min":{let[r,o]=ye(e,t,n,2);return Math.min(r,o)}case"max":{let[r,o]=ye(e,t,n,2);return Math.max(r,o)}case"clamp":{let[r,o,i]=ye(e,t,n,3);return Math.min(i,Math.max(o,r))}case"eq":{let[r,o]=we(e,t,n,2);return r==o}case"neq":{let[r,o]=we(e,t,n,2);return r!=o}case"gt":{let[r,o]=we(e,t,n,2);return r>o}case"gte":{let[r,o]=we(e,t,n,2);return r>=o}case"lt":{let[r,o]=we(e,t,n,2);return r<o}case"lte":{let[r,o]=we(e,t,n,2);return r<=o}case"in":{let[r,o]=we(e,t,n,2);return Array.isArray(o)?o.includes(r):!1}case"and":case"all":return Ro(e,t),t.every(r=>!!Kt(r,n));case"or":case"any":return Ro(e,t),t.some(r=>!!Kt(r,n));case"not":{let[r]=we(e,t,n,1);return!r}case"length":{let[r]=we(e,t,n,1);return typeof r=="string"||Array.isArray(r)?r.length:Et(r)?Object.keys(r).length:0}case"includes":{let[r,o]=we(e,t,n,2);return typeof r=="string"||Array.isArray(r)?r.includes(o):!1}case"literal":return Do(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},Kt=(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 n=Object.entries(e);if(n.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[r,o]]=n;return ic(r,o,t)},sc=(e,t={})=>xt(e,{variables:t.variables,runtime:t.runtime}),ac=(e,t)=>{if(!Et(e))throw new Error(`${t} must be an object`);let n=be(e,"expr"),r=be(e,"value");if(n===r)throw new Error(`${t} must contain exactly one of expr or value`)},Kn=(e,t,n)=>(ac(e,t),be(e,"value")?Do(e.value):Kt(e.expr,n)),cc=(e,t={},n="unknown")=>{if(!Et(e))throw new Error(`Computed variable "${n}" computed must be an object`);let r=be(e,"expr"),o=be(e,"value");if(be(e,"branches")){if(r||o)throw new Error(`Computed variable "${n}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${n}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${n}" branches must not be empty`);if(!Et(e.default))throw new Error(`Computed variable "${n}" requires default`);for(let s=0;s<e.branches.length;s+=1){let l=e.branches[s];if(!Et(l))throw new Error(`Computed variable "${n}" branch ${s} must be an object`);if(!be(l,"when"))throw new Error(`Computed variable "${n}" branch ${s} requires when`);if(sc(l.when,t))return Kn(l,`Computed variable "${n}" branch ${s}`,t)}return Kn(e.default,`Computed variable "${n}" default`,t)}if(r===o)throw new Error(`Computed variable "${n}" must contain exactly one of expr, value, or branches`);return Kn(e,`Computed variable "${n}"`,t)},lc=(e,t,n)=>{switch(t){case"number":if(typeof n!="number"||!Number.isFinite(n))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(n)?"array":typeof n}`);return;case"boolean":if(typeof n!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(n)?"array":typeof n}`);return;case"string":if(typeof n!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(n)?"array":typeof n}`);return;case"object":if(n===null||typeof n!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof n}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},vt=({variables:e={},runtime:t={},variableConfigs:n={},eager:r=!0}={})=>{let o=st(e,n),i=Object.entries(n).filter(([,d])=>Ne(d)).map(([d])=>d),s={},l=[],a=d=>{if(be(s,d))return s[d];let f=n[d];if(!Ne(f))return o[d];let p=l.indexOf(d);if(p>=0){let h=[...l.slice(p),d].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}l.push(d);try{let h=cc(f.computed,u,d);return lc(d,f.type,h),s[d]=h,h}finally{l.pop()}},c=new Proxy({},{get:(d,f)=>{if(typeof f=="string")return a(f)},has:(d,f)=>typeof f=="string"&&(be(o,f)||i.includes(f)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(d,f)=>{if(!(typeof f!="string"||!be(o,f)&&!i.includes(f)))return{enumerable:!0,configurable:!0}}}),u={variables:c,runtime:t,resolveVariable:a};return r?(i.forEach(d=>{a(d)}),{...o,...s}):c},uc=({variables:e={},runtime:t={},variableConfigs:n,projectData:r}={})=>vt({variables:e,runtime:t,variableConfigs:n??r?.resources?.variables??{},eager:!0}),Qt=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{if(Ne(o))return;let i=Za(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},Zt=(e,t)=>{let n=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!n.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${n.join(", ")}`)},en=(e,t,n)=>{let r={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=r[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${n}`);if(!Object.values(r).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${n}" of type "${e}". Valid operations: ${o.join(", ")}`)},dc=2,Oo=12,No=(e=dc)=>{if(!Number.isInteger(e)||e<0||e>Oo)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${Oo}.`);return e},fc=(e,t)=>{let n=10**t;return Math.round((e+Number.EPSILON)*n)/n},Gt=e=>typeof e=="number"&&Number.isFinite(e),Qn=(e,t,n,r,o={})=>{if(e==="number"){if(t==="set"&&!Gt(n))throw new Error(`Operation "set" requires value to be a number for variable "${r}".`);if(t==="multiply"&&!Gt(n))throw new Error(`Operation "multiply" requires value to be a number for variable "${r}".`);if(t==="divide"&&!Gt(n))throw new Error(`Operation "divide" requires value to be a number for variable "${r}".`);if(t==="divide"){if(n===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${r}".`);No(o.roundTo)}}},tn=(e,t,n,r={})=>{let o=(s,l,a)=>{let c=s??l;if(!Gt(c))throw new Error(`Operation "${t}" requires ${a} to be a number.`);return c},i=s=>{let l=o(s,void 0,"value");if(l===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return l};switch(t){case"set":return n;case"multiply":return o(e,1,"current value")*o(n,void 0,"value");case"divide":return fc(o(e,0,"current value")/i(n),No(r.roundTo));case"increment":return o(e,0,"current value")+o(n,1,"value");case"decrement":return o(e,0,"current value")-o(n,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var Zn=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let n=new Date(e),r=s=>String(s).padStart(2,"0"),o=String(n.getFullYear()),i={DD:r(n.getDate()),MM:r(n.getMonth()+1),MMM:Qa[n.getMonth()],YYYY:o,YY:o.slice(-2),HH:r(n.getHours()),mm:r(n.getMinutes()),ss:r(n.getSeconds())};return t.replace(/YYYY|MMM|YY|MM|DD|HH|mm|ss/g,s=>i[s])},pc=(e,t)=>{let n=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let l=i.character?.sprite;return l&&Object.keys(l).length>0&&(s.sprite=l),Object.keys(s).length>0?s:void 0},r=n(e),o=n(t);return JSON.stringify(r)===JSON.stringify(o)?null:r&&!o?{changeType:"delete",data:e}:o&&!r?{changeType:"add",data:t}:o&&r?{changeType:"update",data:t}:null},ko=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};e.transformId!==void 0&&(t.transformId=e.transformId);for(let n of["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"])e[n]!==void 0&&(t[n]=e[n]);for(let n of["animationName","animationSpeed","loop"])e[n]!==void 0&&(t[n]=e[n]);return t},Lo=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},$o=(e,t)=>t&&!e?{changeType:"add",data:t}:e&&!t?{changeType:"delete",data:e}:e&&t&&JSON.stringify(e)!==JSON.stringify(t)?{changeType:"update",data:t}:null,hc=(e,t)=>{let n={},r=$o(ko(e),ko(t)),o=$o(Lo(e),Lo(t));return r&&(n.resource=r),o&&(n.color=o),Object.keys(n).length>0?n:null},er=(e={},t={})=>{let n={},r=["sfx","voice"],o=l=>{let a=e[l],c=t[l];c&&!a?n[l]={changeType:"add",data:c}:a&&!c?r.includes(l)||(n[l]={changeType:"delete",data:a}):a&&c&&JSON.stringify(a)!==JSON.stringify(c)&&(n[l]={changeType:"update",data:c})},i=hc(e.background,t.background);i&&(n.background=i),o("screen"),o("bgm"),o("voice");let s=pc(e.dialogue,t.dialogue);return s&&(n.dialogue=s),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},tr=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,!t.background.resourceId&&!t.background.colorId&&delete t.background);let n=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};n("layout"),n("choice"),n("form"),n("screen"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let r=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(l=>{let a={...l};return delete a.animations,i(a)?a:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return r("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),r("visual",o=>o.resourceId||o.transformId),t},mc=(e,t)=>{if(!e||!t)return;let n=e;for(let r of t.split(".")){if(n==null||!(r in Object(n)))return;n=n[r]}return n},gc=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let n=e.slice(7),r=mc(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},yc={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"])},Po=(e,t)=>{let n=e[e.length-1];return n?yc[n]?.has(t)===!0:!1},Jn=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Jn(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Po(n,r)?o:Jn(o,t,[...n,r])])):gc(e,t),Xn=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Xn(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Po(n,r)?o:Xn(o,t,[...n,r])])):typeof e=="string"?ce(e,t):e,nr=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let n=Jn(e,t._event);return Xn(n,t)};var W=e=>structuredClone(se(e)?He(e):e),P=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Vo=e=>e?.animations?.playback?.continuity==="persistent",N=(e,t)=>P(e??{},t)&&e[t]!==void 0,Ct=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:W(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},bc=e=>N(e,"opacity")||N(e,"blur"),zo=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],qo=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],rr=["animationName","animationSpeed","loop"],Ic=e=>zo.some(t=>N(e,t)),Ho=e=>e?.text&&N(e.text,"content")&&N(e.text,"textStyleId"),Wo=e=>N(e,"text"),Ac=(e,t)=>e.resourceId?!0:Ho(e)?!t?.text:!1,wc=(e,t)=>{let n={...W(e),...t};return t.text&&e.text&&(n.text={...W(e.text),...W(t.text)}),n},Ec=(e,t)=>{if(Wo(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!Ho(e)&&!t?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},jo=e=>qo.some(t=>N(e,t)),Fo=e=>rr.some(t=>N(e,t)),xc=(e,t,{hasAuthoredTransformId:n=!1}={})=>{if(!t)return e;for(let r of qo)!n&&!N(e,r)&&N(t,r)&&(e[r]=t[r]),P(e,r)&&e[r]===void 0&&delete e[r];return e},Yo=(e,t,n)=>{let r=e[n];return r?.id===t?.id?r:e.find(o=>o.id===t?.id)},vc=(e,t)=>{if(!t)return e;for(let n of zo)!N(e,n)&&N(t,n)&&(e[n]=t[n]),P(e,n)&&e[n]===void 0&&delete e[n];return e},Cc=(e,t)=>(t&&(!N(e,"opacity")&&N(t,"opacity")&&(e.opacity=t.opacity),!N(e,"blur")&&N(t,"blur")&&(e.blur=W(t.blur)),P(e,"opacity")&&e.opacity===void 0&&delete e.opacity,P(e,"blur")&&e.blur===void 0&&delete e.blur),e),Go=(e,t,n=[],{hasPatchFn:r=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,l)=>{let a=Yo(n,s,l),c=t(s,a),u=bc(s),d=Ic(s),f=r(s),p=P(s,"animations"),h=W(s);return!c&&(u||d||f)&&a&&(h=o?o(a,h):{...W(a),...h},p||delete h.animations),Cc(vc(h,a),a)}).filter(s=>t(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},Sc=e=>{if(e){if(e.character&&P(e.character,"name"))return e.character.name;if(P(e,"characterName"))return e.characterName}},Ko=e=>!!e?.character&&P(e.character,"sprite"),_c=e=>{let t={},n=!1,r=Sc(e);return r!==void 0&&(t.name=r,n=!0),Ko(e)&&(t.sprite=W(e.character.sprite),n=!0),n?t:void 0},Mo=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Bo=({dialogueState:e,dialogueAction:t,persistCharacter:n})=>P(t,"persistSprite")?t.persistSprite===!0:P(e,"persistSprite")?e.persistSprite===!0:n&&!P(t,"characterId"),Uo=({previousCharacter:e,characterFields:t,hasCharacterId:n,persistCharacter:r,persistSprite:o,hasExplicitPersistSprite:i,isAppendingAdvDialogueContent:s})=>{let l={},a=e??{},c=t??{},u=s&&!n,d=u&&!i;return P(c,"name")?l.name=c.name:(r&&!n||u)&&P(a,"name")&&(l.name=W(a.name)),P(c,"sprite")?l.sprite=W(c.sprite):(o||d)&&P(a,"sprite")&&(l.sprite=W(a.sprite)),Object.keys(l).length>0?l:void 0},Rc=({dialogueState:e,content:t,append:n=!1})=>{if(!n||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let r=Array.isArray(e.content)?e.content:[];r.length>0?e.initialRevealedContent=r.map(o=>W(o)):delete e.initialRevealedContent,e.content=[...r,...t]},Oc=()=>({}),kc=(e,t)=>{if(!t.screen)return;let n=N(t.screen,"opacity"),r=N(t.screen,"blur"),o=P(t.screen,"animations");if(!n&&!r){o||delete e.screen;return}let i=e.screen,s={};if(n?s.opacity=t.screen.opacity:N(i,"opacity")&&(s.opacity=i.opacity),r?s.blur=W(t.screen.blur):N(i,"blur")&&(s.blur=W(i.blur)),P(s,"opacity")&&s.opacity===void 0&&delete s.opacity,P(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},Lc=(e,t)=>{if(t.background){let n=N(t.background,"resourceId"),r=N(t.background,"colorId"),o=N(t.background,"opacity"),i=N(t.background,"blur"),s=N(t.background,"transformId"),l=jo(t.background),a=Fo(t.background),{animationsOnly:c,state:u}=Ct(t.background,p=>N(p,"resourceId")||N(p,"colorId")||N(p,"opacity")||N(p,"blur")||N(p,"transformId")||jo(p)||Fo(p));if(c){e.background=e.background?{...W(e.background),...u}:u;return}if(!n&&!r&&!o&&!i&&!s&&!l&&!a){delete e.background;return}let d=e.background,f=W(t.background);if(!n&&d?.resourceId){f.resourceId=d.resourceId,!P(f,"transformId")&&d.transformId&&(f.transformId=d.transformId);for(let p of rr)!N(f,p)&&N(d,p)&&(f[p]=d[p])}xc(f,d,{hasAuthoredTransformId:s}),!r&&d?.colorId&&(f.colorId=d.colorId),!o&&N(d,"opacity")&&(f.opacity=d.opacity),!i&&N(d,"blur")&&(f.blur=W(d.blur)),P(f,"resourceId")&&f.resourceId===void 0&&delete f.resourceId,P(f,"colorId")&&f.colorId===void 0&&delete f.colorId,P(f,"animations")&&f.animations===void 0&&delete f.animations,P(f,"transformId")&&f.transformId===void 0&&delete f.transformId,P(f,"opacity")&&f.opacity===void 0&&delete f.opacity,P(f,"blur")&&f.blur===void 0&&delete f.blur;for(let p of rr)P(f,p)&&f[p]===void 0&&delete f[p];if(!f.resourceId&&!f.colorId){delete e.background;return}d?.resourceId===f.resourceId&&d?.transformId===f.transformId&&!P(f,"animations")&&Vo(d)&&(f.animations=W(d.animations)),e.background=f}else e.background?.animations&&!Vo(e.background)&&(e.background.animations={})},$c=(e,t)=>{if(!t.dialogue){if(e.dialogue&&(Mo(e.dialogue),e.dialogue.mode==="adv")){e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,delete e.dialogue.textSpeed;let u=e.dialogue.persistCharacter===!0,d=Bo({dialogueState:e.dialogue,dialogueAction:{},persistCharacter:u});u||delete e.dialogue.characterId,e.dialogue.character=Uo({previousCharacter:e.dialogue.character,characterFields:{},hasCharacterId:!1,persistCharacter:u,persistSprite:d,hasExplicitPersistSprite:!1,isAppendingAdvDialogueContent:!1}),e.dialogue.character||delete e.dialogue.character}return}e.dialogue||(e.dialogue={});let n=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:u,state:d}=Ct(t.dialogue.ui,f=>!!f.resourceId);u?e.dialogue.ui={...e.dialogue.ui,...d}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let r=t.dialogue.append===!0&&n!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&Rc({dialogueState:e.dialogue,content:t.dialogue.content,append:r}),P(t.dialogue,"textSpeed")?e.dialogue.textSpeed=t.dialogue.textSpeed:delete e.dialogue.textSpeed;let o=P(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=Bo({dialogueState:e.dialogue,dialogueAction:t.dialogue,persistCharacter:o});P(t.dialogue,"persistSprite")&&(e.dialogue.persistSprite=i);let s=P(t.dialogue,"characterId"),l=_c(t.dialogue),a=Ko(t.dialogue);s?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!r&&delete e.dialogue.characterId;let c=Uo({previousCharacter:e.dialogue.character,characterFields:l,hasCharacterId:s,persistCharacter:o,persistSprite:i,hasExplicitPersistSprite:P(t.dialogue,"persistSprite"),isAppendingAdvDialogueContent:r});if(c?e.dialogue.character=c:delete e.dialogue.character,a||Mo(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 u={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.textSpeed!==void 0&&(u.textSpeed=e.dialogue.textSpeed),e.dialogue.character&&(u.character=W(e.dialogue.character)),e.dialogue.lines.push(u)}},Tc=(e,t)=>{if(t.sfx){let n=Array.isArray(t.sfx.items)&&t.sfx.items.length>0,r=Array.isArray(t.sfx.channels)&&t.sfx.channels.length>0;if(!n&&!r){delete e.sfx;return}e.sfx=W(t.sfx)}else e.sfx&&delete e.sfx},Dc=(e,t)=>{if(t.bgm){let n=Array.isArray(t.bgm.sounds);if(!t.bgm.resourceId&&!n||n&&t.bgm.sounds.length===0){e.bgm=void 0;return}e.bgm=W(t.bgm),t.bgm.resourceId&&(e.bgm.loop=t.bgm.loop??!0)}},Nc=(e,t)=>{if(t.visual){let n=e.visual?.items||[];t.visual.items?.forEach((i,s)=>{Ec(i,Yo(n,i,s))});let{hasValidItems:r,processedItems:o}=Go(t.visual.items,Ac,n,{hasPatchFn:Wo,mergeItemFn:wc});r?e.visual={items:o}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},Pc=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:n,processedItems:r}=Go(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);n?e.character={items:r}:delete e.character},Vc=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},jc=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=Ct(t.layout,o=>!!o.resourceId);if(n){e.layout=r;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},Fc=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=Ct(t.choice,o=>!!o.resourceId);if(n){e.choice={...e.choice,...r};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},Mc=(e,t)=>{if(t.form){let{animationsOnly:n,state:r}=Ct(t.form,o=>!!o.resourceId);if(n){e.form={...e.form,...r};return}if(!t.form.resourceId){delete e.form;return}e.form=W(t.form)}else e.form&&delete e.form},Bc=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},Uc=(e,t)=>{if(t.voice){let n=Array.isArray(t.voice.sounds);if(!t.voice.resourceId&&!n||n&&t.voice.sounds.length===0){delete e.voice;return}e.voice=W(t.voice)}else e.voice&&delete e.voice},zc=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},Ye=e=>Jt(Oc,[zc,kc,Lc,Tc,Dc,Nc,$c,Pc,Vc,jc,Fc,Mc,Bc,Uc])(e);var at=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=ce(e,t);return n&&typeof n=="object"?e:n};var qc=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},autoForwardSpeed:{source:"global.autoForwardSpeed"},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"}}),Ge=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,autoForwardSpeed:1,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),St=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Jo=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",autoForwardSpeed:"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"}),or=Object.freeze(["dialogueTextSpeed","autoForwardDelay","autoForwardSpeed","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),ir=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Hc=(e,t)=>{if(t.startsWith("global.")){let n=t.slice(7);return e?.global?.[n]}if(t.startsWith("context.runtime.")){let n=t.slice(16),r=Array.isArray(e?.contexts)?e.contexts:[];return r[r.length-1]?.runtime?.[n]}},Ke=e=>Object.fromEntries(Object.entries(qc).map(([t,n])=>{let r=Hc(e,n.source),o=r!==void 0?r:Ge[t]??St[t];return[t,o]})),Pe=(e,t)=>Ke(e)[t],Xo=(e={})=>Object.fromEntries(or.map(t=>[t,e[t]??Ge[t]]));var ct=Object.freeze({VISUAL_BEHIND_BACKGROUND:10,BACKGROUND:20,VISUAL_BEHIND_CHARACTER:30,CHARACTER:40,VISUAL_BEHIND_DIALOGUE:50,DIALOGUE:60,VISUAL_BEHIND_CHOICE:70,CHOICE:80,VISUAL_FOREGROUND:90}),_e=Object.freeze({BEHIND_BACKGROUND:ct.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:ct.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:ct.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:ct.VISUAL_BEHIND_CHOICE,FOREGROUND:ct.VISUAL_FOREGROUND}),sr=_e.BEHIND_DIALOGUE,ar=Object.freeze(Object.values(_e).sort((e,t)=>e-t));var Re={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:Zn},Wc=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,Yc=(e,t)=>{let n=String(t||"").trim();if(!n)return;let r=n.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of r){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},sn=(e,t,n)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),l=Wc.exec(s);if(l){let[,a,c,u]=l,d=Yc(t,u);if(!Array.isArray(d))continue;let f=Array.isArray(i[s])?i[s]:[];d.forEach((p,h)=>{let g={...t,[a]:p};c&&(g[c]=h),f.forEach(b=>{let A=sn(b,g,n),w=ce(A,g,n);Array.isArray(w)?o.push(...w):o.push(w)})});continue}}o.push(sn(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=sn(i,t,n)}),r},vr=({animationType:e,animationId:t,animationPath:n})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${n}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},Gc=({id:e,targetId:t,animation:n,playback:r,animationPath:o="animation"})=>{let i=structuredClone(n);if(vr({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,r!==void 0){let s=Qc(r,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},Kc=(e,{animationId:t="animation",animationPath:n="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return vr({animationType:e.type,animationId:t,animationPath:n}),e.type},Jc=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Xc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Qc=(e,t="animation.playback")=>{if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`[${t}] playback must be an object.`);if(e.continuity!==void 0&&e.continuity!=="render"&&e.continuity!=="persistent")throw new Error(`[${t}] playback.continuity must be "render" or "persistent".`);if(e.speed!==void 0&&(typeof e.speed!="number"||!Number.isFinite(e.speed)||e.speed<=0))throw new Error(`[${t}] playback.speed must be a finite number greater than 0.`);let n={};return e.continuity!==void 0&&(n.continuity=e.continuity),e.speed!==void 0&&e.speed!==1&&(n.speed=e.speed),Object.keys(n).length>0?n:void 0},Zc=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},Je=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),ui=e=>e?.playback?.continuity==="persistent",mr=e=>Array.isArray(e)?e.map(mr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,n)=>(t[n]=mr(e[n]),t),{}),cn=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return t.playback&&(delete t.playback.continuity,t.playback.speed===1&&delete t.playback.speed,Object.keys(t.playback).length===0&&delete t.playback),JSON.stringify(mr(t))},di=(e=[])=>e.filter(t=>ui(t)).map(t=>structuredClone(t)),fi=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,n)=>{let r=typeof n?.duration=="number"&&Number.isFinite(n.duration)?n.duration:0;return t+r},0):0,cr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,n)=>Math.max(t,fi(n)),0),pi=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(cr(e.tween),cr(e.prev?.tween),cr(e.next?.tween),fi(e.mask?.progress))/Zc(e),Qo=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let n=new Set(t.map(cn).filter(Boolean));return e.some(r=>{if(!ui(r))return!1;let o=cn(r);return o?n.has(o):!1})},Ee=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:n,activePersistentAnimations:r,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||n?!1:i&&!t||Qo({animationInstances:e,activePersistentAnimations:r})?!0:i?!1:Qo({animationInstances:e,activePersistentAnimations:o}),el=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),tl=(e,t)=>{if(el(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},nl=({resources:e,animationId:t,playback:n,instanceId:r,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?Gc({id:r,targetId:o,animation:s,playback:n,animationPath:i}):null},rl=(e,{defaultTargetId:t,defaultId:n,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return vr({animationType:o.type,animationId:o.id??n,animationPath:r}),o.id??=n,o.targetId??=t,o},Cr=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r,animationPathPrefix:o=r})=>{t.forEach((i,s)=>{e.push(rl(i,{defaultTargetId:n,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},gr=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(n=>n===null||typeof n!="object"||Array.isArray(n)))throw new Error(`${t} must be an array of objects`);return e},ol=({content:e,path:t,variables:n})=>gr(e,t).reduce((r,o)=>{let i=at(o.text,{variables:n});return r+`${i??""}`.length},0),Zo=(e=[])=>{let t=new Map;for(let n of e)n?.id&&t.set(n.id,(t.get(n.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,n])=>n>1).map(([n])=>n))},nn=(e,t=0,n=new Set)=>{if(!n.has(e?.id))return`character-container-${e.id}`;let r=e?.sprites?.map(({resourceId:o})=>o)||[];return r.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${r.join("-")}`},rn=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return n},il=(e,t={})=>{if(!t?.transformId)return;let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for background`);return n},sl=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],al=(e={})=>sl.some(t=>Je(e,t)),hi=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.spritesheets?.[t])return"spritesheet-animation";if(e.layouts?.[t])return"container"}},an=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},cl=(e={})=>e.textStyles||{},ll=(e={})=>e.images||{},ul=.5,dl=(e={},t,n)=>{if(t){if(!e.animations?.[t])throw new Error(`Animation '${t}' not found in spritesheet resource '${n}'`);return t}return Object.keys(e.animations??{})[0]},mi=({id:e,resourceId:t,spritesheet:n,animationName:r,animationSpeed:o,loop:i,transform:s={}}={})=>{let l=dl(n,r,t),a=l?n.animations?.[l]:void 0;if(!a){console.warn(`Spritesheet animation not found: ${t}`);return}return{id:e,type:"spritesheet-animation",...s,width:n.width,height:n.height,src:n.fileId,atlas:n.jsonData,playback:{frames:a.frames,animationSpeed:o??a.animationSpeed??ul,loop:i??a.loop??!0}}},gi=({id:e,item:t,resources:n={}}={})=>{let r=n.images?.[t.resourceId];if(r)return{type:"sprite",id:e,src:r.fileId,width:r.width,height:r.height,x:0,y:0};let o=n.spritesheets?.[t.resourceId];if(o)return mi({id:e,resourceId:t.resourceId,spritesheet:o,animationName:t.animationName,animationSpeed:t.animationSpeed,loop:t.loop,transform:{x:0,y:0}});console.warn(`Character sprite resource not found: ${t.resourceId}`)},fl=(e={})=>e.colors||{},pl=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Ot=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,ut=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},lr=(e,t,n)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);return e},ur=(e,t,n,r,{minimum:o}={})=>{if(e===void 0)return r;if(typeof e!="number"||!Number.isFinite(e)||o!==void 0&&e<o){let i=o===void 0?"a finite number":`a finite number >= ${o}`;throw new Error(`shadow.${t} for text style "${n}" must be ${i}`)}return e},dn=(e,t)=>{if(typeof e!="string"||!pl.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(n=>n.repeat(2)).join("")}`:e},ei=(e,t,n)=>{let r=dn(e,n);if(t===1)return r;let o=Number.parseInt(r.slice(1,3),16),i=Number.parseInt(r.slice(3,5),16),s=Number.parseInt(r.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},hl=(e={},t)=>{let n=cl(e)?.[t];if(!n)throw new Error(`Text style "${t}" not found`);let r=e.fonts?.[n.fontId];if(!r)throw new Error(`Font "${n.fontId}" not found for text style "${t}"`);let o=e.colors?.[n.colorId];if(!o)throw new Error(`Color "${n.colorId}" not found for text style "${t}"`);let i=lr(n.colorAlpha,"colorAlpha",t),s={fontFamily:r.fileId,fontSize:n.fontSize??16,fontWeight:n.fontWeight??"400",fontStyle:n.fontStyle??"normal",lineHeight:n.lineHeight??1.2,fill:ei(o.hex,i,`Color "${n.colorId}" for text style "${t}"`)};if(n.align!==void 0&&(s.align=n.align),n.wordWrap!==void 0&&(s.wordWrap=n.wordWrap),n.breakWords!==void 0&&(s.breakWords=n.breakWords),n.wordWrapWidth!==void 0&&(s.wordWrapWidth=n.wordWrapWidth),n.strokeColorId){let l=e.colors?.[n.strokeColorId];if(!l)throw new Error(`Stroke color "${n.strokeColorId}" not found for text style "${t}"`);let a=lr(n.strokeAlpha,"strokeAlpha",t);s.strokeColor=ei(l.hex,a,`Stroke color "${n.strokeColorId}" for text style "${t}"`)}else if(n.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);if(n.strokeWidth!==void 0&&(s.strokeWidth=n.strokeWidth),n.shadow!==void 0){let l=e.colors?.[n.shadow.colorId];if(!l)throw new Error(`Shadow color "${n.shadow.colorId}" not found for text style "${t}"`);s.shadow={color:dn(l.hex,`Shadow color "${n.shadow.colorId}" for text style "${t}"`),alpha:lr(n.shadow.alpha,"shadow.alpha",t),blur:ur(n.shadow.blur,"blur",t,0,{minimum:0}),offsetX:ur(n.shadow.offsetX,"offsetX",t,2),offsetY:ur(n.shadow.offsetY,"offsetY",t,2)}}return s},yr=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>yr(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${n}". Use textStyleId instead`);let r={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(r[o]=yr(i,t,Ot(n,o)));return e.textStyleId!==void 0&&(ut(e.textStyleId,n,"textStyleId"),r.textStyle=hl(t,e.textStyleId)),r},Sr=(e={},t)=>{let n=fl(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return dn(n.hex,`Color "${t}"`)},yi=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",dr=(e,t,n)=>{let r=e?.[t];if(!(!r||typeof r!="object"||Array.isArray(r))&&Object.prototype.hasOwnProperty.call(r,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${n}". Use ${yi(`${t}.fill`)} instead`)},ml=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>kt(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;let r={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(r[o]=kt(i,t,Ot(n,o)));return e.colorId!==void 0&&(ut(e.colorId,n,"colorId"),r.fill=Sr(t,e.colorId)),r},kt=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>kt(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${n}". Use ${yi("fill")} instead`);dr(e,"hover",n),dr(e,"click",n),dr(e,"rightClick",n)}let r={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){r[o]=ml(i,t,Ot(n,o));continue}r[o]=kt(i,t,Ot(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(ut(e.colorId,n,"colorId"),r.fill=Sr(t,e.colorId)),r},fr=(e={},t)=>{let n=ll(e)?.[t];return n||null},bi=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",ti=(e,t,n,r)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,r))throw new Error(`Inline ${t}.${r} is not allowed in sprite layout elements at "${n}". Use ${bi(`${t}.${r}`)} instead`)},ni=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},br=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>br(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${n}". Use ${bi(o)} instead`);ti(e,"hover",n,"src"),ti(e,"click",n,"src")}let r={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(r[o]=br(i,t,Ot(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){ut(e.imageId,n,"imageId");let o=fr(t,e.imageId),i=o?.fileId??e.imageId;r.src=i,r.width===void 0&&o?.width!==void 0&&(r.width=o.width),r.height===void 0&&o?.height!==void 0&&(r.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(ut(e.hoverImageId,n,"hoverImageId"),ni(r,"hover",fr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(ut(e.clickImageId,n,"clickImageId"),ni(r,"click",fr(t,e.clickImageId)?.fileId??e.clickImageId)),r},_r=(e,t={},n="root")=>br(kt(yr(e,t,n),t,n),t,n),Oe=_r,Qe=(e=[])=>e.find(t=>t.id==="story"),gl="#000000",Ir="bg-cg-background-color",yl=({resources:e={},background:t={},screen:n})=>t?.colorId===void 0?dn(n?.backgroundColor??gl,"screen.backgroundColor"):Sr(e,t.colorId),Ii=(e={})=>{if(Je(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},bl=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},ri=(e={},{includeDefaultAlpha:t=!1}={})=>{let n=Ii(e),r=bl(e),o={};return(t||n!==void 0)&&(o.alpha=n??1),r&&(o.blur=r),o},Il=(e={})=>{if(Je(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Al=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Ai=(e={})=>{let t=Il(e),n=Al(e),r={};return t!==void 0&&(r.alpha=t),n&&(r.blur=n),r},_t=(e={})=>Ai(e),Ve=(e={},t={})=>{let n={x:t.x??e.x,y:t.y??e.y,anchorX:t.anchorX??e.anchorX,anchorY:t.anchorY??e.anchorY,rotation:t.rotation??e.rotation,scaleX:t.scaleX??e.scaleX,scaleY:t.scaleY??e.scaleY},r=t.originX??e.originX,o=t.originY??e.originY;return r!==void 0&&(n.originX=r),o!==void 0&&(n.originY=o),n},wl=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],Rr=(e={})=>e.text&&Je(e.text,"content")&&Je(e.text,"textStyleId"),oi=(e={})=>{if(e.resourceId)return e.resourceId;if(Rr(e))return"text"},El=e=>{if(e.text){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!Rr(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let t of wl)if(Je(e.text,t))throw new Error(`Visual item "${e.id}" text.${t} is reserved for the visual item`)}},xl=({resources:e,background:t,screen:n={width:1920,height:1080},includeOpacity:r=!1})=>{let o={id:Ir,type:"rect",x:0,y:0,width:n?.width??1920,height:n?.height??1080,fill:yl({resources:e,background:t,screen:n})};if(r){let i=Ii(t);i!==void 0&&(o.alpha=i)}return o},vl=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.spritesheets?.[t]||e.layouts?.[t]):!1,ii=({resources:e={},resourceId:t,colorId:n})=>{let r=hi(e,t);return t&&(r||n===void 0)?{resourceId:t,targetId:an({resourceId:t,kind:r})}:n!==void 0?{resourceId:Ir,targetId:Ir}:{resourceId:void 0,targetId:void 0}},wi=100,Xe=wi,Cl="channel:bgm",Sl="channel:voice",_l="default",Rl=e=>String(e).replaceAll("%","%25").replaceAll(":","%3A"),Rt=(...e)=>e.map(Rl).join(":"),ln=(e,t,n)=>{let r=new Set;e.forEach(({id:o})=>{if(r.has(o)){let i=n?` in ${n}`:"";throw new Error(`Duplicate ${t} id "${o}"${i}.`)}r.add(o)})},Ol=(e,t)=>e*t/wi,Ei=(e={},t)=>e?.[t]??Ge[t],Or=(e={},t,n=Xe)=>Ol(n,Ei(e,t)),kr=({id:e,volume:t,muted:n,pan:r,children:o,runtime:i})=>({id:e,type:"audio-channel",volume:t,muted:!!i?.muteAll||(n??!1),pan:r??0,children:o}),on=(e,t,n,r)=>e[n]!==void 0?e[n]:t[n]!==void 0?t[n]:r,kl=["muted","pan","playbackRate","startAt","endAt"],Lr=({id:e,sound:t,resource:n,defaultLoop:r=!1})=>{let o={id:e,type:"sound",src:n.fileId,loop:on(t,n,"loop",r),volume:on(t,n,"volume",Xe),startDelayMs:on(t,n,"startDelayMs",0)};kl.forEach(s=>{let l=on(t,n,s,void 0);l!==void 0&&(o[s]=l)});let i=o.startAt??0;if(o.endAt!==void 0&&o.endAt!==null&&o.endAt<i)throw new Error(`Sound "${e}" endAt (${o.endAt}) must be greater than or equal to startAt (${i}).`);return o},xe=({variables:e,runtime:t,saveSlots:n=[],dialogueState:r,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,confirmDialog:d,form:f,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:b,skipTransitionsAndAnimations:A}={})=>{let w={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,autoForwardSpeed:t?.autoForwardSpeed??1,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??l??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},C=Nl({dialogueState:r,includeInactiveAdvDialogue:o,characters:h,variables:e,runtime:w}),R={variables:e,runtime:w,saveSlots:n,isChoiceVisible:a,isFormVisible:c,canRollback:u,confirmDialog:d,form:f,historyDialogue:p,characters:h};return C&&(R.dialogue=C,R.dialogueLines=C.lines),R},si=100,un=(e,t)=>{if(Array.isArray(e))return e.map(r=>un(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=un(n[r],t)}),n.type==="text-revealing"?t(n):n},Ll=e=>un(e,t=>({...t,revealEffect:"none"})),$l=e=>un(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,si):si;return{...t,speed:r,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:r}:{}}}),je=(e,{isLineCompleted:t=!1,skipMode:n=!1,skipTransitionsAndAnimations:r=!1}={})=>t||r?Ll(e):n?$l(e):e,xi=({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:{}}}}),Ar=e=>{if(Array.isArray(e))return e.map(Ar);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Ar(s);let n=t.click?.payload;if(!n||typeof n!="object"||Array.isArray(n))return t;let r=n.actions,o=r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"nextLine")?{...r.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...n,bypassChoice:!0,...o?{actions:{...r,nextLine:o}}:{}}}}},Tl=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),ai="submit",pr=(e,t,n={})=>{let r=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},o=r.actions&&typeof r.actions=="object"?r.actions:{},i=n.replaceActions===!0?t:{...o,...t};return{...e||{},payload:{...r,actions:i}}},wr=(e,t,n={})=>{if(Array.isArray(e))return e.map(c=>wr(c,t,n));if(!e||typeof e!="object")return e;let r=typeof e.type=="string",o=r&&e.formRole===ai,i=r&&n.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},l={};for(let[c,u]of Object.entries(e))l[c]=wr(u,t,c==="children"?s:{});let a=l;if(a.type==="input"&&typeof a.field=="string"){let c=t?.fields?.[a.field];if(c){let u={updateFormField:{formKey:t.key,field:c.id,value:"_event.value"}};a={...a,value:c.value,placeholder:a.placeholder===void 0?c.placeholder:a.placeholder,multiline:a.multiline===void 0?c.multiline:a.multiline,...a.maxLength===void 0&&c.maxLength!==void 0?{maxLength:c.maxLength}:{},change:pr(a.change,u),submit:pr(a.submit,t.submitActions)}}}return a.formRole===ai||i?{...a,click:pr(a.click,t.submitActions,{replaceActions:!0})}:a},Er=(e,t)=>{if(Array.isArray(e))return e.map(r=>Er(r,t));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e))n[r]=Er(o,t);for(let r of Tl){let o=n[r]?.payload;!o||typeof o!="object"||Array.isArray(o)||(n[r]={...n[r],payload:{...o,_interactionSource:"form"}})}return n},xr=({characterId:e,character:t,characterName:n,characters:r={},variables:o={}}={})=>{let i=e?r?.[e]:void 0,s=Xt({characterId:e,character:t,characterName:n,characters:r,variables:o});return{...i||{},...t||{},name:s}},vi=(e=[],t={},n={})=>e.map(r=>{let o=xr({characterId:r.characterId,character:r.character,characterName:r.characterName,characters:t,variables:n}),i=typeof r.text=="string"?r.text:Array.isArray(r.content)?r.content.map(s=>s?.text??"").join(""):"";return{...r,text:i,character:o,characterName:o.name}}),Dl=e=>!(!e||e.mode==="adv"&&e.content===void 0),Nl=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:n={},variables:r,runtime:o}={})=>{if(!t&&!Dl(e))return;let i=e.content===void 0?[{text:""}]:gr(e.content,"dialogue.content"),s=e.content===void 0?0:ol({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:r}),l=o?.dialogueTextSpeed??Ge.dialogueTextSpeed,a=e.textSpeed??l,c=(e.lines||[]).map((d,f)=>{let p=gr(d.content,`dialogue.lines[${f}].content`),h=xr({characterId:d.characterId,character:d.character,characterName:d.characterName,characters:n,variables:r});return{...d,textSpeed:d.textSpeed??l,content:p.map(g=>({...g,text:at(g.text,{variables:r})})),character:h,characterName:h.name}}),u=xr({characterId:e.characterId,character:e.character,characters:n,variables:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,persistSprite:e.persistSprite,character:u,textSpeed:a,content:i.map(d=>({...d,text:at(d.text,{variables:r})})),initialRevealedCharacters:s,lines:c}},Ci=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=ce(e,n,{functions:Re});return Oe(je(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},hr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),ci=({renderStateKeyboard:e,keyboard:t,phase:n})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([r,o])=>{let i=e[r]??{},s=n==="keydown"?o?.keydown:o?.keyup;if(n==="keydown"&&s&&typeof s=="object"){e[r]={...i,keydown:{payload:hr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[r].keyup={payload:hr(o.keyup)});return}e[r]={...i,[n]:{payload:hr(o)}}})},Pl=(e={},t={})=>{let n={};return ci({renderStateKeyboard:n,keyboard:e,phase:"keydown"}),ci({renderStateKeyboard:n,keyboard:t,phase:"keyup"}),Object.keys(n).length>0?n:void 0},ke=({animationsDef:e,resources:t,previousResourceId:n,currentResourceId:r,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l})=>{if(!e)return[];let a=[],c=({instanceId:A,targetId:w})=>{let C=nl({resources:t,animationId:p,playback:h,instanceId:A,targetId:w,animationPath:s});C&&a.push(C)},u=n!=null&&n!==!1,d=r!=null&&r!==!1,f=o&&i&&o===i;tl(e,s);let p=Jc(e),h=Xc(e),g=t?.animations?.[p],b=Kc(g,{animationId:p,animationPath:s});if(b==="update")return d&&i?c({instanceId:`${l}-animation-update`,targetId:i}):u&&o&&c({instanceId:`${l}-animation-update`,targetId:o}),a;if(b==="transition"){let A=`${l}-animation-transition`,w=h?.continuity==="persistent"?A:`${l}-animation-in`;if(u&&d&&f)return c({instanceId:A,targetId:i}),a;u&&c({instanceId:`${l}-animation-out`,targetId:o}),d&&c({instanceId:w,targetId:i})}return a},Vl=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),jl=(e,{presentationState:t,previousPresentationState:n,currentLineActions:r,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:a,runtime:c,activePersistentAnimations:u,restoredPersistentAnimations:d,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:b,form:A,saveSlots:w=[]})=>{let{elements:C,animations:R}=e;if(t.background){let V=r===void 0?!0:Je(r?.background??{},"animations"),j=C.find(ue=>ue.id==="story");if(!j)return e;let E=il(o,t.background),B=E||al(t.background),U=n?.background?.resourceId,J=n?.background?.colorId,M=t.background.resourceId??(t.background.animations?U:void 0),Y=t.background.colorId??(t.background.animations?J:void 0),G=vl(o,M),X={...t.background,colorId:Y};if((Y!==void 0||G)&&j.children.push(xl({resources:o,background:X,screen:i,includeOpacity:!G})),M){let{images:ue={},videos:de={},spritesheets:Q={}}=o,re=hi(o,M),fe;if(re==="sprite"?fe=ue[M]:re==="video"?fe=de[M]:re==="spritesheet-animation"&&(fe=Q[M]),fe){let S=re==="video",O=re==="spritesheet-animation",F={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...E},oe={...ri(t.background,{includeDefaultAlpha:!0}),...Ve(F,t.background)},ie;O?ie=mi({id:an({resourceId:M,kind:re}),resourceId:M,spritesheet:fe,animationName:t.background.animationName,animationSpeed:t.background.animationSpeed,loop:t.background.loop,transform:oe}):ie={id:an({resourceId:M,kind:re}),type:S?"video":"sprite",src:fe.fileId,width:fe.width,height:fe.height,...oe},S&&(ie.loop=t.background.loop??!1,ie.volume=fe.volume??50),ie&&j.children.push(ie)}}if(M){let{layouts:ue={}}=o,de=ue[M];if(de){let Q={id:an({resourceId:M,kind:"container"}),type:"container",children:de.elements,...ri(t.background)};B&&Object.assign(Q,Ve({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...E},t.background));let re=ce(Q,xe({variables:a,runtime:c,saveSlots:w,dialogueState:t.dialogue,isLineCompleted:s,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:b,form:A,characters:o.characters||{},skipTransitionsAndAnimations:l}),{functions:Re});j.children.push(Oe(je(re,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:l}),o))}}let ve=ii({resources:o,resourceId:U,colorId:J}),te=ii({resources:o,resourceId:M,colorId:Y}),ne=ke({animationsDef:t.background.animations,resources:o,previousResourceId:ve.resourceId,currentResourceId:te.resourceId,previousTargetId:ve.targetId,currentTargetId:te.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});Ee({animationInstances:ne,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:u,restoredPersistentAnimations:d,isAuthoredOnCurrentLine:V})&&R.push(...ne)}return e},Fl=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:a}=e;if(t.character&&r){let c=l.find(h=>h.id==="story");if(!c)return e;let u=t.character.items||[],d=n?.character?.items||[],f=Zo(u),p=Zo(d);for(let h=0;h<u.length;h++){let g=u[h],{transformId:b,sprites:A}=g,w=d.find(M=>M.id===g.id),C=d.findIndex(M=>M.id===g.id),R=w?.sprites&&w.sprites.length>0,V=A&&A.length>0,j=C>=0?nn(w,C,p):void 0,E=ke({animationsDef:g.animations,resources:r,previousResourceId:j,currentResourceId:V?nn(g,h,f):void 0,previousTargetId:j,currentTargetId:V?nn(g,h,f):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!A&&!b&&R&&Ee({animationInstances:E,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...E);continue}if(g.animations&&!A&&!b)continue;if(!A||A.length===0||!b){console.warn("Character item missing sprites or transformId:",g);continue}let B=nn(g,h,f),U=r.transforms[b];if(!U){console.warn("Transform not found:",b);continue}let J={type:"container",id:B,...Ve(U,g),..._t(g),children:[]};for(let M of A){let Y=gi({id:`${B}-${M.id}`,item:M,resources:r});Y&&J.children.push(Y)}c.children.push(J),Ee({animationInstances:E,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...E)}}return e},Si=(e,t)=>{if(!ar.includes(e))throw new Error(`${t} must be one of: ${ar.join(", ")}.`)},Ml=(e,t)=>{let n=!!e.resourceId||Rr(e),r=e.layer??(n?void 0:t?.layer)??sr;return Si(r,`Visual item "${e.id}" layer`),r},Bl=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:l,activePersistentAnimations:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,saveSlots:g=[],visualLayer:b})=>{let{elements:A,animations:w}=e;if(t.visual&&r){let C=A.find(E=>E.id==="story");if(!C)return e;let R=t.visual.items,V=n?.visual?.items||[],j=xe({variables:s,runtime:l,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,characters:r.characters||{},skipTransitionsAndAnimations:i});b!==void 0&&Si(b,"visualLayer");for(let E of R){let B=V.find(G=>G.id===E.id),U=Ml(E,B);if(b!==void 0&&U!==b)continue;if(El(E),E.text){let G=rn(r,E),X={...structuredClone(E.text),id:`visual-${E.id}`,type:"text",...Ve(G,E)};Object.assign(X,_t(E)),C.children.push(Oe(ce(X,j,{functions:Re}),r))}if(E.resourceId){let{images:G={},videos:X={},spritesheets:ve={}}=r,te=ve[E.resourceId];if(te){let ne=rn(r,E),ue=E.animationName;if(ue){let de=te.animations?.[ue];if(!de)throw new Error(`Animation '${ue}' not found in spritesheet resource '${E.resourceId}'`);let Q=_t(E),re={id:`visual-${E.id}`,type:"spritesheet-animation",...Ve(ne,E),width:E.width??te.width,height:E.height??te.height,alpha:Q.alpha??E.alpha??1,src:te.fileId,atlas:te.jsonData,playback:{frames:de.frames,animationSpeed:E.animationSpeed??de.animationSpeed??.5,loop:E.loop??de.loop??!0}};Q.blur&&(re.blur=Q.blur),C.children.push(structuredClone(re))}}else{let ne=G[E.resourceId]||X[E.resourceId];if(ne){let ue=X[E.resourceId]!==void 0,de=rn(r,E),Q={id:`visual-${E.id}`,type:ue?"video":"sprite",src:ne.fileId,width:ne.width,height:ne.height,...Ve(de,E)};Object.assign(Q,_t(E)),ue&&(Q.loop=ne.loop??!1,Q.volume=ne.volume??50),C.children.push(Q)}}}if(E.resourceId){let{layouts:G={}}=r,X=G[E.resourceId];if(X){let ve=rn(r,E),te={id:`visual-${E.id}`,type:"container",children:structuredClone(X.elements),...Ve(ve,E)};Object.assign(te,_t(E));let ne=ce(te,j,{functions:Re});C.children.push(Oe(je(ne,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),r))}}let J=oi(B),M=oi(E),Y=ke({animationsDef:E.animations,resources:r,previousResourceId:J,currentResourceId:M,previousTargetId:J?`visual-${E.id}`:void 0,currentTargetId:M?`visual-${E.id}`:void 0,animationPath:`visual.items[${E.id}].animations`,idPrefix:E.id});Ee({animationInstances:Y,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:a})&&w.push(...Y)}}return e},lt="dialogue-character-sprite",li=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,Ul=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=Qe(e.elements);if(!a)return e;let c=t.dialogue?.character?.sprite,u=n?.dialogue?.character?.sprite,d=li(c),f=li(u),p=ke({animationsDef:c?.animations,resources:r,previousResourceId:f?lt:void 0,currentResourceId:d?lt:void 0,previousTargetId:f?lt:void 0,currentTargetId:d?lt:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!d)return c?.animations&&f&&Ee({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e;let h=r.transforms?.[c.transformId];if(!h)return console.warn("Transform not found:",c.transformId),e;let g={type:"container",id:lt,...Ve(h),children:[]};for(let b of c.items){let A=gi({id:`${lt}-${b.id}`,item:b,resources:r});A&&g.children.push(A)}return a.children.push(g),Ee({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e},zl=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,skipOnlyViewedLines:d,isLineCompleted:f,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:b,saveSlots:A=[]})=>{let{elements:w,animations:C}=e;if(!t.dialogue||o)return e;let R=w.find(j=>j.id==="story");if(!R)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:j={}}=r,E=j[t.dialogue.ui.resourceId];if(E){let B={elements:E.elements},U=xe({variables:h,runtime:g,saveSlots:A,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:f,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,characters:r.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:d,skipTransitionsAndAnimations:p}),J={functions:Re},M=sn(B,U,J),Y=ce(M,U,J),G=Oe(je(Y?.elements,{isLineCompleted:f,skipMode:s,skipTransitionsAndAnimations:p}),r);if(Array.isArray(G))for(let X of G)R.children.push(X);else G&&R.children.push(G)}}Ul(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:b});let V=ke({animationsDef:t.dialogue.ui?.animations,resources:r,previousResourceId:n?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:n?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return Ee({animationInstances:V,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:b})&&C.push(...V),e},ql=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:b=[]})=>{let{elements:A,animations:w}=e;if(t.choice&&r){let C=Qe(A);if(!C)return e;let R=r?.layouts[t.choice.resourceId];if(R&&R.elements){let j={elements:R.elements},E=ce(j,{...xe({variables:l,runtime:a,saveSlots:b,dialogueState:t.dialogue,isLineCompleted:i,autoMode:c,skipMode:u,isChoiceVisible:d??!!t.choice,isFormVisible:f,canRollback:p,form:h,characters:r.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:Re}),B=Ar(Oe(je(E?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r));if(Array.isArray(B))for(let U of B)C.children.push(U);else B&&C.children.push(B)}let V=ke({animationsDef:t.choice.animations,resources:r,previousResourceId:n?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:n?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});Ee({animationInstances:V,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&w.push(...V)}return e},Hl=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:b})=>{let{elements:A,animations:w}=e;if(!b?.resourceId||!r)return e;let C=Qe(A);if(!C)return e;let R=r?.layouts?.[b.resourceId];if(!R)return console.warn(`Form layout not found: ${b.resourceId}`),e;let V={id:"form-container",type:"container",x:0,y:0,children:R.elements||[]},j={...xe({variables:l,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,characters:r.characters||{},skipTransitionsAndAnimations:s,form:b}),form:b},E=ce(V,j,{functions:Re}),B=Er(Oe(je(wr(E,b),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r),b);B&&C.children.push(B);let U=ke({animationsDef:b.animations,resources:r,previousResourceId:n?.form?.resourceId,currentResourceId:b.resourceId,previousTargetId:n?.form?.resourceId?"form-container":void 0,currentTargetId:b.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return Ee({animationInstances:U,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&w.push(...U),e},Wl=(e,{presentationState:t,resources:n={},variables:r,runtime:o,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,saveSlots:f=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=n.controls?.[t.control.resourceId];if(!h)return e;let g=Pl(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 b=Qe(e.elements);if(!b)return e;let A={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return b.children.push(Ci({container:A,resources:n,templateData:xe({variables:r,runtime:o,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,characters:n.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:l,skipTransitionsAndAnimations:p})),e},Yl=(e,{presentationState:t,resources:n,runtime:r,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&n){if(!Qe(i))return e;let a=t.bgm,c=!Array.isArray(a.sounds),u=c?a.resourceId?[{id:"default",resourceId:a.resourceId,loop:a.loop??!0,volume:a.volume,startDelayMs:a.startDelayMs??0}]:[]:a.sounds,d=[];if(c||ln(u,"BGM sound"),u.forEach(p=>{let h=n.sounds?.[p.resourceId];h&&d.push(Lr({id:Rt("bgm",c?"default":p.id),sound:p,resource:h,defaultLoop:!0}))}),d.length===0)return e;let f=xe({variables:o,runtime:r}).runtime;s.push(kr({id:Cl,volume:Or(f,"musicVolume",c?Xe:a.volume??Xe),muted:a.muted,pan:a.pan,children:d,runtime:f}))}return e},Gl=(e,{presentationState:t,resources:n,runtime:r})=>{let{audio:o}=e;if(t.sfx&&n){let i=t.sfx,s=!Array.isArray(i.channels),l=s?[{id:_l,sounds:i.items??[]}]:i.channels;s||ln(l,"SFX channel"),l.forEach(a=>{let c=[];s||ln(a.sounds,"SFX sound",`SFX channel "${a.id}"`),a.sounds.forEach((u,d)=>{let f=n.sounds?.[u.resourceId];f&&c.push(Lr({id:s?Rt("sfx","default",d,u.id):Rt("sfx",a.id,u.id),sound:u,resource:f}))}),c.length!==0&&o.push(kr({id:Rt("channel","sfx",a.id),volume:Or(r,"soundVolume",a.volume??Xe),muted:a.muted,pan:a.pan,children:c,runtime:r}))})}return e},Kl=(e,t,n)=>{if(!(!t||!n))return e?.voices?.[t]?.[n]},Jl=(e,{presentationState:t,resources:n,currentSceneId:r,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let l=t.voice,a=!Array.isArray(l.sounds),c=a?l.resourceId?[{id:"default",resourceId:l.resourceId,loop:l.loop??!1,volume:Xe,startDelayMs:l.startDelayMs??0}]:[]:l.sounds,u=[];if(a||ln(c,"Voice sound"),c.forEach(f=>{let p=Kl(n,r,f.resourceId);p&&u.push(Lr({id:Rt("voice",r,a?"default":f.id),sound:f,resource:p}))}),u.length===0)return e;let d=xe({variables:i,runtime:o}).runtime;return s.push(kr({id:Sl,volume:a?l.volume??Ei(d,"soundVolume"):Or(d,"soundVolume",l.volume??Xe),muted:l.muted,pan:l.pan,children:u,runtime:d})),e},Xl=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,saveSlots:f=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:b,animations:A}=e;if(t.layout){let V=Qe(b);if(!V)return e;let j=r.layouts[t.layout.resourceId];if(!j)return e;Array.isArray(j.transitions)&&!p&&!h&&Cr({animations:A,transitions:j.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let E={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:j.elements||[]};V.children.push(Ci({container:E,resources:r,templateData:xe({variables:o,runtime:i,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,characters:r.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:l,skipTransitionsAndAnimations:h}))}let w=n?.layout?.resourceId,C=t.layout?.resourceId,R=ke({animationsDef:t.layout?.animations,resources:r,previousResourceId:w,currentResourceId:C,previousTargetId:w?`layout-${w}`:void 0,currentTargetId:C?`layout-${C}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return Ee({animationInstances:R,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&A.push(...R),e},Ql=(e,{currentLineActions:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=t?.screen?.animations;if(!a)return e;let c=n!=null,u=ke({animationsDef:a,resources:r,previousResourceId:c?"story":void 0,currentResourceId:"story",previousTargetId:c?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return Ee({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...u),e},Zl=(e,{presentationState:t})=>{let n=Qe(e.elements);return!n||!t?.screen||Object.assign(n,Ai(t.screen)),e},eu=(e,{presentationState:t,resources:n={},variables:r,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,overlayStack:d=[],dialogueHistory:f=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:b})=>{let{elements:A,animations:w}=e;return d&&d.length>0&&d.forEach((C,R)=>{let V=n.layouts[C.resourceId];if(!V){console.warn(`Overlay layout not found: ${C.resourceId}`);return}Array.isArray(V.transitions)&&(b||Cr({animations:w,transitions:V.transitions,defaultTargetId:`overlayStack-${R}`,idPrefix:`overlayStack-${R}`,animationPathPrefix:`overlayStack[${R}]`}));let j={id:`overlayStack-${R}`,type:"container",x:0,y:0,children:[xi({id:`overlayStack-${R}-blocker`,screen:h}),...V.elements||[]]},E=vi(f,n.characters,r),B=xe({variables:r,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,historyDialogue:E,characters:n.characters||{},skipTransitionsAndAnimations:b}),U=ce(j,B,{functions:Re}),[J,...M]=U.children||[],Y=Oe(je({...U,children:M},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:b}),n);A.push({...Y,children:J?[J,...Y.children||[]]:Y.children})}),e},tu=(e,{presentationState:t,resources:n={},variables:r,runtime:o,saveSlots:i=[],autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,confirmDialog:f,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:b})=>{let{elements:A,animations:w}=e;if(!f?.resourceId)return e;let C=n.layouts?.[f.resourceId];if(!C)return console.warn(`ConfirmDialog layout not found: ${f.resourceId}`),e;Array.isArray(C.transitions)&&!b&&Cr({animations:w,transitions:C.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let R={id:"confirmDialog",type:"container",x:0,y:0,children:[xi({id:"confirmDialog-blocker",screen:h}),...C.elements||[]]},V=vi(p,n.characters,r),j=ce(R,xe({variables:r,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,confirmDialog:f,historyDialogue:V,characters:n.characters||{},skipTransitionsAndAnimations:b}),{functions:Re}),[E,...B]=j.children||[],U=Oe(je({...j,children:B},{isLineCompleted:g,skipMode:l,skipTransitionsAndAnimations:b}),n);return A.push({...U,children:E?[E,...U.children||[]]:U.children}),e},Lt=e=>(t,n)=>Bl(t,{...n,visualLayer:e}),nu=Lt(_e.BEHIND_BACKGROUND),ru=Lt(_e.BEHIND_CHARACTER),ou=Lt(_e.BEHIND_DIALOGUE),iu=Lt(_e.BEHIND_CHOICE),su=Lt(_e.FOREGROUND),_i=e=>Jt(Vl,[Wl,nu,jl,ru,Fl,ou,zl,iu,ql,Hl,Xl,su,Zl,Ql,Yl,Gl,Jl,eu,tu])(e);function Ri(e,t=""){let n=[],r=e.length,o=0,i=0,s=-1,l=()=>{let a=0,c=0,u;do u=parseInt(e[o++],36),a+=(u&15)<<c,c+=4;while(u&16);return a};for(;o<r;){let a=s+1+l();s=a+l(),n.push([a,s,t?parseInt(t[i++],36):0])}return n}function Oi(e,t,n){let r=0,o=t.length-1;for(;r<=o;){let i=r+o>>>1,s=n[i];if(e<t[i])o=i-1;else if(e>s>>>5)r=i+1;else return s&31}return 0}var ki="090001000h1v5g2903000hl2v6jh16ng1s210111110o35aa10u2k1g10l6600152113h2010u1q1r5aq3890o13181214r22k3158q2n1000v100h1k20000001207030001160721k171001h1j11610332010010321210090411021c1c02100o301201412230u1130b100h1j116111420120411001100k11l10051001h1j11611142011000321210072411021d0g10r3000000132120090o200200g1j11f2012031213711271t1001o301001000001121371b1f0c101h1l2011001031212000080a1t1001m40400102101600i11t301006c7i601008b6p41r10101041h3d0004115a1j290p3q223000511010100g1501010302003172030c0010016000e0i6v50n40n5tl12ir33s12t11u11cj30100060700010a90t220000l71i20m7203010241000502rd101004k300000006101027050920g3t22bk1300616g209030207u18c1000t10003010501b2o20000102000004g37070101o921c000640602001mcv3rg20000001o16d0c0m1fg6g2h30m10q55f1vm11c0ma0p1a42nc0ne1a090q3314902021204020112030318250105bb1201110i1021i15101131502141b15120511011k1155132040202510201010603060a1f02040104210b1g3290e0e0kn11vs12j11j3040pp12t80g6v1vmo7319g21g51gh103040n11010040j51i3f01q1h1d0m27p1a0000cs13200523j200010301010100v140018a4q2501010101c08000i1f12601011g3012215110u1a0001015000pcq181000100011000iji5fvc0u91g5bhg20ie0l94lo6002115303121s12240la1tj23h44tj11t45m4ah33q700000l3ep2021a200t220301012040a0i320j2040007f00100r20c100g3208000011531000s520201036020t900207l1101n311000000321210090a12634b910201l22001051020120011020000e1i520701020000n10h5001050000010000010001re0010323010001r11i520701000001q6000000107l600000230004gg12080001lc62027111n1000411230000000000t820321030030r10090n205001380800501020n2050c0001mc00002000000nc006150000i5l1100600010001q753011160000i441111000000rl11019100000c1h201043102n10ltk1f006eoss2b0202gs94r36si2033ku101m373h50b1rqs4113sli1t22m1uh2435070726u13k92rr7m34h380e0m141egl561g1261114k60ga6nn10t33sv13uf1jf0207150qt16t66pr60n23k6bf1f0e1l29g71c1e029j1n30p11ea0k1028139m16rb2v621122i52213040tf1u3b51n17127c0232041d120819052c28220104060306l5g3l4572g130152cqdl2c3o37a5o27u11c32d9m2cu2191obo57eh9gg1tv3",Li="262122424333333393233393339333333333393393bf3b3b3b3b3f3f3bffff33b3bb33ff3f33b3b3333333bffff3b33bb33f33bffff33b3bb33ff3f33b3bbb333b3ff33b333f33b3b3b3b3333b3bf33b3bb39333b33b33b3b3b333b333333b3b33333f3b33b3ffb3f3fff3f3b33f35dc33333f3b3b3b33323333b3bb3b33b3fb3b3333b33333bff3b3f33bfb3b3ff3b3b3b3b3b333b333b3323e22442344444444444444444444444444444444444444444444444444444444444444444444444444444443333333333b3b3bb33333b353bff3b3b3b3f3ff3b3b333bfff3f33333fb3bb3fb3b3bb33232333f333fff333333333b3b3333bb3b39393f3b3fbf33bb3b393b3b3b3333b33b33b3bbb33b33ffff3b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b3fffff3bb39b9b3b33b3bf3f3b33f3b3f93b33b3b3bb33b33b3b3b3333393b3b3b33b39bffb3b332333b333dd3b3333233332333333333333333333333333333444444444444a4444444444444344444444444444444444444444444444444444444444",$i="0001000000010010000000100000000000000000000000000001000000010014000100000001001000010101100101100000000000000000000100000001111000010000000110101001110111111111000100000021001000010000000100100001000000011010000100000001111000013000000100140001000000010010";var Ti=65535,$r=40960,fn=126976,Pi=new Uint8Array(12288),Vi=new Uint8Array(3072),ji=new Uint8Array(2816),Fi,Mi;{let e=(o,i,s,l,a)=>{let c=i+o.length-1;for(let u=s<i?i:s,d=l>c?c:l;u<=d;u++)o[u-i]=a},t=new Uint32Array(320),n=new Uint32Array(320),r=0;for(let[o,i,s]of Ri(ki,Li))e(Pi,0,o,i,s),e(Vi,$r,o,i,s),e(ji,fn,o,i,s),i>=65040&&!(o>=fn&&i<=129791)&&(t[r]=o,n[r++]=i<<5|s);Fi=t.slice(0,r),Mi=n.slice(0,r)}function Di(e){return e<12288?Pi[e]:e<$r?e<12336?e>=12330?3:0:e<12443?e===12336||e===12349?4:e>=12441?3:0:e===12951||e===12953?4:0:e<44032?Vi[e-$r]:e<55204?(e-44032)%28?8:7:e<57344?e<=55238?e>=55216?13:0:e>=55243&&e<=55291?12:0:e<65024?e===64286?3:0:e<65040?3:e>=fn&&e<129792?ji[e-fn]:e>=917504?e>921599?0:e>=917536&&e<917632||e>=917760&&e<918e3?3:2:Oi(e,Fi,Mi)}var Bi=Uint8Array.from($i,Number);function au(e){return e===2381||e===2509||e===2637||e===2765||e===2893||e===3149||e===3405||e===4153||e===6098||e===6752||e===6980||e===7083||e===43456||e===43766||e===68159||e===69939||e===70608||e===71998||e===72263||e===72345||e===73538}function Ni(e,t,n){switch(t){case 3:return e&24?n===8204?e&6:(e&24)===16||au(n)?e&6|16:e&6|8:e&6;case 4:return 2;case 10:return e&1^1;case 14:return(e&2)<<1|e&24;default:return 8}}function*Ui(e){let t=e.length;if(t===0)return;let n=e.codePointAt(0),r=n>Ti?2:1,o=Di(n),i=50200>>o&1?Ni(0,o,n):0,s=0,l=n,a=o;for(;r<t;){n=e.codePointAt(r);let c=n>Ti?2:1,u=Di(n),d=Bi[o<<4|u],f;d===0?f=!0:d===1?f=!1:d===2?f=!(i&1):d===3?f=!(i&4):f=(i&24)!==16,i=50200>>u&1&&(i!==0||u!==3)?Ni(i,u,n):0,f&&(yield{segment:e.slice(s,r),index:s,input:e,_hd:l,_catBegin:a===15?0:a,_catEnd:o===15?0:o},s=r,l=n,a=u),r+=c,o=u}yield{segment:e.slice(s),index:s,input:e,_hd:l,_catBegin:a===15?0:a,_catEnd:o===15?0:o}}function*zi(e){for(let t of Ui(e))yield t.segment}{let e=Ui("_");Bi._keep=[e,e.next()]}var qi=1e3,cu=1,lu=60,uu=3,du=.5,fu=2e4,pu=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,hu=/^\s+$/u,Hi,mu=e=>{let t=`${e??""}`.normalize("NFC"),n=globalThis.Intl?.Segmenter;return typeof n!="function"?Array.from(zi(t)):(Hi??=new n(void 0,{granularity:"grapheme"}),Array.from(Hi.segment(t),({segment:r})=>r))},gu=e=>mu(e).reduce((t,n)=>hu.test(n)?t+du:pu.test(n)?t+uu:t+1,0),Wi=({text:e="",baseDelay:t=qi,speed:n=cu}={})=>{let r=Number.isFinite(t)?Math.max(0,t):qi,o=Number.isFinite(n)&&n>0?n:1,i=gu(e)*lu/o,s=Math.max(r,fu);return Math.min(r+i,s)};var pn={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Xi=1,Tr=1,ft="choice",Fe="form",gn=()=>({manual:{...pn.manual},auto:{...pn.auto},applyMode:pn.applyMode}),Dr=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...gn()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},T=e=>{let t=se(e)?He(e):e;return structuredClone(t)},$=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Qi=(e,t)=>{if(typeof t!="string"||t.length===0)throw new Error("Achievement action requires a non-empty resourceId");let n=e.projectData.resources?.achievements?.[t];if(!n)throw new Error(`Achievement resource "${t}" not found`);if(n.type!=="boolean"&&n.type!=="number")throw new Error(`Achievement resource "${t}" has invalid type "${n.type}"`);return n},Tt=e=>String(e),Zi=()=>({sections:[],resources:[]}),yu=e=>$(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Zi(),bu=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Iu=({sectionId:e,lineId:t,content:n,dialogueState:r,characterName:o})=>({sectionId:e,lineId:t,content:n,text:bu(n),characterId:r.characterId,character:{...r.character||{},name:o},characterName:o}),Au=()=>({resourceId:void 0}),wu=e=>{if(!$(e))return e;let t={...e};return Object.prototype.hasOwnProperty.call(t,"requireComplete")&&!Object.prototype.hasOwnProperty.call(t,"requireLineCompleted")&&(t.requireLineCompleted=t.requireComplete),delete t.requireComplete,t},pt=(e,t)=>{let n=e?.story?.scenes??{};for(let[r,o]of Object.entries(n))if(o?.sections?.[t])return{sceneId:r,section:o.sections[t]};return{sceneId:void 0,section:void 0}},es=e=>{let t=e?.story?.scenes??{},n=new Map;for(let[r,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let l=n.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${r}". Section IDs must be globally unique.`);n.set(s,r)}}},ts=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},ns=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Xi)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Eu=(e,t={})=>{let n;try{n=ns(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:ts(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},xu=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Eu(t,n)])),rs=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:n})=>Of(n));return t.length>0?t:void 0},vu=e=>{!$(e)||!Array.isArray(e.timeline)||(e.returnabilityVersion=Tr,e.timeline.forEach(t=>{if(!$(t))return;typeof t.returnable!="boolean"&&delete t.returnable;let n=rs(t.executedActions);if(n){t.executedActions=n;return}delete t.executedActions}))},Yi=(e,t,n,r="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!$(e))throw new Error(`Malformed ${r}.${t}[${n}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${r}.${t}[${n}] 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 ${r}.sections[${n}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},Cu=(e,t="viewedRegistry")=>{if(e===void 0)return Zi();if(!$(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let n=e.sections??[],r=e.resources??[];return{sections:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Yi(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Yi(o,"resources",i,t);return[s.resourceId,s]})))}},os=(e,t,n)=>{if(!$(e))throw new Error(`Malformed save slot ${n}.`);let{sectionId:r,lineId:o}=e;if(typeof r!="string"||r.length===0)throw new Error(`Malformed save slot ${n}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${n}: missing lineId.`);let{sceneId:i,section:s}=pt(t,r);if(!s)throw new Error(`Malformed save slot ${n}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(a=>a.id===o))throw new Error(`Malformed save slot ${n}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},is=(e,t)=>e?.sectionId===t?.sectionId&&e?.lineId===t?.lineId,Su=(e,t)=>{let{section:n}=pt(e,t?.sectionId);return n?.lines?.find(r=>r.id===t?.lineId)},_u=(e,t)=>{let{section:n}=pt(e,t?.sectionId),r=n?.lines?.findIndex(i=>i.id===t?.lineId);if(typeof r!="number"||r<0)return null;let o=n.lines[r+1];return o?{sectionId:t.sectionId,lineId:o.id}:null},ss=(e,t,n)=>{if(typeof t?.sectionId!="string")return!1;let{section:r}=pt(e,t.sectionId);return is({sectionId:t.sectionId,lineId:r?.lines?.[0]?.id},n)},Ru=new Set(["jumpToLine","rollbackByOffset","rollbackToLine","sectionTransition","resetStoryAtSection"]),dt={always:"always",maybe:"maybe",never:"never"},Ou=e=>{if(!Object.prototype.hasOwnProperty.call(e??{},"when"))return dt.always;let t=e.when,n;if(t===null||typeof t=="boolean"||typeof t=="number")n=t;else if($(t)&&Object.keys(t).length===1&&Object.prototype.hasOwnProperty.call(t,"literal"))n=t.literal;else return dt.maybe;return n?dt.always:dt.never},as=(e,t)=>{if(!Array.isArray(e?.branches))return!1;for(let n of e.branches){let r=Ou(n);if(r!==dt.never){if(t(n))return!0;if(r===dt.always)return!1}}return!1},cs=e=>as(e,t=>Object.entries(t?.actions??{}).some(([n,r])=>n==="conditional"?cs(r):Ru.has(n))),ls=(e,t,n)=>as(t,r=>Object.entries(r?.actions??{}).some(([o,i])=>o==="sectionTransition"?ss(e,i,n):o==="conditional"?ls(e,i,n):!1)),ku=(e,t,n)=>{if(!t)return!0;let r=Su(n,e)?.actions;if(!$(r))return!0;if(ss(n,r.sectionTransition,t))return!1;let o=r.conditional;return o?!(ls(n,o,t)||!(r.choice?.resourceId||r.form?.resourceId)&&!cs(o)&&is(_u(n,e),t)):!0},Lu=(e,t,n)=>{if(!$(e)||!Array.isArray(e.timeline))return $t({pointer:t,replayStartIndex:1});let r=new WeakSet,o=e.timeline.flatMap((c,u)=>{if(!$(c))return[];try{let d=os(c,n,`rollback.timeline[${u}]`),f=mn({sectionId:d.sectionId,lineId:d.lineId,rollbackPolicy:c.rollbackPolicy,returnable:c.returnable});typeof c.returnable=="boolean"&&r.add(f);let p=rs(T(c.executedActions));return p&&(f.executedActions=p),[f]}catch{return[]}});if(o.length===0)return $t({pointer:t,replayStartIndex:1});e.returnabilityVersion!==Tr&&o.forEach((c,u)=>{!r.has(c)&&!ku(c,o[u+1],n)&&(c.returnable=!1)});let s=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):o.length-1;(s<0||s>=o.length)&&(s=o.length-1);let l=o[s];if(l?.sectionId!==t.sectionId||l?.lineId!==t.lineId){let c=o.findLastIndex(u=>u.sectionId===t.sectionId&&u.lineId===t.lineId);c>=0?s=c:(o.push(mn({sectionId:t.sectionId,lineId:t.lineId})),s=o.length-1)}let a=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),s):0;return{currentIndex:s,isRestoring:!1,replayStartIndex:a,timeline:o}},$u=(e,t,n)=>{if(!$(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=Vr(t),o=os(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!$(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);if(e.runtime!==void 0&&!$(e.runtime))throw new Error(`Malformed save slot contexts[${n}].runtime entry.`);let i=e.variables?st(T(e.variables),t.resources?.variables??{}):{},s=Hu({loadedContextRuntime:$(e.runtime)?T(e.runtime):{}}),l={currentPointerMode:"read",pointers:{read:o},configuration:$(e.configuration)?T(e.configuration):{},views:Array.isArray(e.views)?T(e.views):[],bgm:$(e.bgm)?T(e.bgm):{resourceId:void 0},variables:{...r,...i},rollback:Lu(e.rollback,o,t)};return s&&(l.runtime=s),l},Tu=(e,t)=>{if(!$(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((n,r)=>$u(n,t,r))}},Du=(e,t)=>{if(!$(e))throw new Error("Malformed save slot.");let n=ns(e.formatVersion);return{...e,formatVersion:n,state:Tu(e.state,t)}},Gi=(e,t,{required:n=!1}={})=>{if(e===void 0){if(n)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 r=T(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},Nu=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Gi(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Gi(e.cancelActions,"cancelActions")}},ht=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Pu=e=>($(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),mt=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},us=e=>{if(!(!$(e)||!e.animations))return{animations:T(e.animations)}},Vu=(e,t)=>{let n=us(t);if(n){e.global.pendingScreenTransition=n;return}delete e.global.pendingScreenTransition},ju=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},Fu=(e,t)=>{let n=e?.sectionId,r=e?.lineId;if(!(!n||!r||!t))return`${n}:${r}:${t}`},hn=e=>String(e??""),ds=(e,t)=>{let n=hn(t);return e?.trim===!0?n.trim():n},Mu=e=>$(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>$(t)).map(([t,n])=>[t,{id:t,...T(n)}])):{},Bu=(e,t)=>{if(!t||!$(e.global.formDrafts))return;let n=e.global.formDrafts[t];return $(n)?n:void 0},fs=(e,t)=>{let n=Pu(e);$(n[t])||(n[t]={values:{},touched:{},errors:{},submitted:!1});let r=n[t];return $(r.values)||(r.values={}),$(r.touched)||(r.touched={}),$(r.errors)||(r.errors={}),typeof r.submitted!="boolean"&&(r.submitted=!1),r},Nr=(e,t)=>{let n=ds(e,t);return e?.required===!0&&n.length===0?"required":null},Uu=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let r=le({state:e},{sectionId:t.sectionId})?.lines||[],o=r.findIndex(i=>i.id===t.lineId);return o<0?{}:Ye(r.slice(0,o+1).map(i=>i.actions||{}))},zu=({state:e,form:t,pointer:n})=>{if(!t?.resourceId)return null;let r=ju(t),o=Fu(n,r);if(!r||!o)return null;let i=Bu(e,o),s=Mu(t),l=bn({state:e}),a={},c=[],u={},d=!0;return Object.entries(s).forEach(([f,p])=>{let h=hn(l?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},f)?hn(i.values[f]):h,b=i?.touched?.[f]===!0,A=Nr(p,g),w=i?.submitted||b?A:null,C=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,R={id:f,variableId:p.variableId,value:g,initialValue:h,valid:!A,error:w,touched:b,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...C!==void 0?{maxLength:C}:{}};A&&(d=!1),a[f]=R,c.push(R),u[f]=g}),{id:r,key:o,resourceId:t.resourceId,animations:t.animations,valid:d,submitted:i?.submitted===!0,fields:a,fieldList:c,values:u,submitActions:{submitForm:{formKey:o,actions:T(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:T(t.cancelActions??{})}}}},Ze=[],Ki="line",Pr="interaction",mn=({sectionId:e,lineId:t,rollbackPolicy:n,returnable:r})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free",...typeof r=="boolean"?{returnable:r}:{}}),Vr=e=>{let{contextVariableDefaultValues:t}=Qt(e??{});return T(t)},ps=()=>({...T(St)}),hs=({loadedRuntime:e,runtimeIds:t,defaults:n={},path:r})=>{if(e===void 0)return{runtimeState:T(n),hasLoadedValues:!1};if(!$(e))throw new Error(`Malformed ${r}.`);let o=T(n),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=ms(s,T(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},qu=({loadedGlobalRuntime:e={}})=>hs({loadedRuntime:e,runtimeIds:or,defaults:Ge,path:"global.runtime"}).runtimeState,Hu=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:n}=hs({loadedRuntime:e,runtimeIds:ir,defaults:ps(),path:"context.runtime"});return n?t:void 0},yn=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Wu=e=>e.runtime?(ir.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=T(St[t]))}),e.runtime):(e.runtime=ps(),e.runtime),Yu=e=>Xo(e.global),Gu=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Yu(e)}})},Ku=e=>Jo[e],Ju=(e,t)=>{let n=Ku(e);if(n==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(n==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(n==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},ms=(e,t)=>{if(Ju(e,t),e==="autoForwardSpeed"&&t<=0)throw new Error("autoForwardSpeed requires a value greater than 0");return e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t},gs=(e,t,n)=>{let r=ms(t,n);if(t in St){let o=yn(e);if(!o)return r;let i=Wu(o);return i[t]=r,r}return e.global[t]=r,r},ys=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:T(e)},configuration:{},views:[],bgm:Au(),variables:Vr(t),rollback:$t({pointer:e})}),gt=e=>e?(e.currentPointerMode="read",$(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Xu=(e,{queueRender:t=!0}={})=>{let n=e.contexts?.[e.contexts.length-1],r=n?.pointers?.read;if(!n||!r?.sectionId||!r?.lineId)return null;let o=ys({pointer:r,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,Qu(e,{queueRender:t}),o},Qu=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,ht(e),mt(e),e.global.nextLineConfig=gn(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},bs=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},$t=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[mn({sectionId:e.sectionId,lineId:e.lineId})]:[]}},tt=(e,t={})=>{if(e?.rollback)return bs(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 n=e?.pointers?.read;return e.rollback=$t({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},jr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=tt(n);r.isRestoring||(r.currentIndex<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,r.currentIndex+1)),r.timeline.push(mn(t)),r.currentIndex=r.timeline.length-1)},Zu=({state:e})=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!Array.isArray(n?.timeline)||typeof n.currentIndex!="number"?null:{checkpointIndex:n.currentIndex,checkpoint:n.timeline[n.currentIndex]??null}},ed=({state:e},t={})=>{let{checkpointIndex:n,checkpointIdentity:r,sectionId:o,lineId:i}=t,l=e.contexts?.[e.contexts.length-1]?.rollback;if(!Number.isInteger(n)||!Array.isArray(l?.timeline)||typeof l.currentIndex!="number")return e;let a=l.timeline[n];return(se(a)?Vn(a):a)!==r||a?.sectionId!==o||a?.lineId!==i||(a.returnable=!1),e},td=({state:e},t={})=>{let{slotId:n,saveSlotIdentity:r,checkpointIndex:o,sectionId:i,lineId:s}=t,l=Tt(n),a=e.global.saveSlots?.[l],c=se(a)?Vn(a):a;if(!a||c!==r)return e;let u=a.state?.contexts,d=Array.isArray(u)?u.at(-1):null,f=d?.rollback,p=f?.timeline?.[o];return!Number.isInteger(o)||f?.currentIndex!==o||d?.pointers?.read?.sectionId!==i||d?.pointers?.read?.lineId!==s||p?.sectionId!==i||p?.lineId!==s||(p.returnable=!1,f.returnabilityVersion=Tr,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}})),e},nd=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;if(!n||n.isRestoring||!Array.isArray(n.timeline)||typeof n.currentIndex!="number")return null;let r=Ze[Ze.length-1],o=typeof r?.checkpointIndex=="number"?r.checkpointIndex:n.currentIndex;return o<0||o>=n.timeline.length?null:(typeof r?.checkpointIndex!="number"&&o<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,o+1)),n.timeline[o]??null)},rd=({state:e},t={})=>{let n=t?.source===Ki?Ki:Pr,o=e.contexts?.[e.contexts.length-1]?.rollback;return!o||o.isRestoring||!Array.isArray(o.timeline)||typeof o.currentIndex!="number"||o.currentIndex<0||o.currentIndex>=o.timeline.length?(Ze.push({checkpointIndex:null,source:n}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Ze.push({checkpointIndex:o.currentIndex,source:n}),e)},od=({state:e})=>(Ze.pop(),e),Se=(e,t,n)=>{let o=Ze[Ze.length-1]?.source??Pr;if(!kf(t,o))return;let i=nd(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:T(n)}))},Ji=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:l}of r){let a=e.projectData.resources?.variables?.[o],c=a?.scope,u=a?.type;if(Ne(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Zt(c,o),en(u,i,o),Qn(u,i,s,o,{roundTo:l}),c==="context"&&(n.variables[o]=tn(n.variables[o],i,s,{roundTo:l}))}},id=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:n,payload:r})=>{Lf(e,n,r)})},sd=(e,t)=>{let{sectionId:n,lineId:r}=t,s=le({state:e},{sectionId:n})?.lines?.find(l=>l.id===r)?.actions;s&&Object.entries(s).forEach(([l,a])=>{Ns(e,l,a)})},Is=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=tt(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Nt({state:e}),e.global.skipMode&&Me({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=Vr(e.projectData),delete n.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=T(pn),e.global.overlayStack=[],ht(e),mt(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let l=i;l<=t;l++)l>i&&Dr(e),sd(e,r.timeline[l]),id(e,r.timeline[l]);let s=gt(n);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},ad=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=n;es(t);let l=t.story.initialSceneId,a=t.story.scenes[l],c=a.initialSectionId,u=a.sections[c],d={sceneId:l,sectionId:c,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:f}=Qt(t),p={...f,...st(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:Cu(s,"accountViewedRegistry"),nextLineConfig:gn(),saveSlots:xu(r),overlayStack:[],variables:p,...qu({loadedGlobalRuntime:i})},contexts:[ys({pointer:d,projectData:t})]}},cd=({state:e})=>e.global.overlayStack||[],ld=({state:e})=>e.global.pendingEffects,As=({state:e})=>e.global.skipMode,ud=({state:e})=>e.global.autoMode,ws=({state:e})=>e.global.dialogueUIHidden,Es=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(!n)return[];let{sectionId:r,lineId:o}=n.pointers.read,i=le({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(d=>d.id===o),l=i.lines.slice(0,s+1),a=[],c={},u=vt({variables:{...e.global?.variables??{},...yn(e)?.variables??{}},runtime:Ke(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let d of l){let f=d.actions||{};if(c=Ye([c,f]),!f.dialogue)continue;let p=c.dialogue||{},h=Xt({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:u}),g=Iu({sectionId:r,lineId:d.id,content:f.dialogue.append===!0?p.content:f.dialogue.content,dialogueState:p,characterName:h});if(f.dialogue.append===!0&&a.length>0){a[a.length-1]={...a[a.length-1],content:g.content,text:g.text,characterId:g.characterId,character:g.character,characterName:g.characterName};continue}a.push(g)}return a},dd=({state:e})=>e.global.confirmDialog??null,Dt=({state:e},{pointer:t}={})=>{let n=t??Ie({state:e})?.pointer,r=Uu({state:e,pointer:n});return zu({state:e,form:r.form,pointer:n})},fd=({state:e},{pointer:t}={})=>!!Dt({state:e},{pointer:t}),Ae=({state:e},{pointer:t}={})=>{let n=Dt({state:e},{pointer:t});if(n)return{source:Fe,formId:n.id,formKey:n.key};let r=xs({state:e,pointer:t});return r?{source:ft,resourceId:r}:null},pd=({state:e,registry:t},n)=>{let{sectionId:r,lineId:o}=n,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===r);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let l=le({state:e},{sectionId:r});if(!l||!l.lines||!Array.isArray(l.lines))return s.lastLineId===o;let a=l.lines.findIndex(u=>u.id===s.lastLineId),c=l.lines.findIndex(u=>u.id===o);return a===-1||c===-1?s.lastLineId===o:c<=a},hd=({registry:e},t)=>{let{resourceId:n}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===n)},Fr=({state:e},t)=>pd({state:e,registry:e.global.accountViewedRegistry},t),md=({state:e},t)=>hd({registry:e.global.accountViewedRegistry},t),gd=({state:e})=>e.global.nextLineConfig,xs=({state:e,pointer:t}={})=>{let n=t??Ie({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=le({state:e},{sectionId:r})?.lines||[],l=s.findIndex(c=>c.id===o);if(l<0)return;let a;for(let c of s.slice(0,l+1)){let u=c?.actions;if(u?.cleanAll&&(a=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){a=void 0;continue}let d=u.choice;if(d?.resourceId){a=d.resourceId;continue}d?.animations||(a=void 0)}return a},vs=({state:e})=>!!xs({state:e}),yd=({state:e})=>structuredClone(e),bd=({state:e})=>T(e.projectData.resources?.achievements??{}),Id=({state:e},t)=>{let n=e.projectData.resources?.achievements?.[t?.resourceId];return n===void 0?void 0:T(n)},Cs=({state:e})=>e.global.saveSlots,Ad=({state:e},t)=>{let n=t?.slotId,r=Tt(n);return e.global.saveSlots[r]},Mr=({state:e})=>Ke(e),wd=({state:e},t)=>Pe(e,t?.runtimeId),bn=({state:e})=>{let t={...e.global?.variables??{},...yn(e)?.variables??{}};return vt({variables:t,runtime:Ke(e),variableConfigs:e.projectData.resources?.variables??{}})},Ie=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(n)return{currentPointerMode:"read",pointer:n.pointers?.read}},le=({state:e},t)=>{let{sectionId:n}=t;return pt(e.projectData,n).section},In=({state:e})=>{let t=Ie({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=le({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},Ss=({state:e})=>{let{sectionId:t,lineId:n}=Ie({state:e}).pointer,o=le({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n),l=o.slice(0,i+1).map(c=>{let u=c.actions||{},d={};return Object.keys(u).forEach(f=>{d[f]=u[f]}),d});return Ye(l)},Ed=e=>{let t=In({state:e})?.actions?.dialogue;if(t?.clear===!0||!Array.isArray(t?.content))return"";let n=bn({state:e});return t.content.map(r=>`${at(r?.text,{variables:n})??""}`).join("")},An=({state:e})=>Wi({text:Ed(e),baseDelay:Pe(e,"autoForwardDelay"),speed:Pe(e,"autoForwardSpeed")}),xd=({state:e})=>{let t=_s({state:e}),r=In({state:e})?.actions??{},o=Ye([t??{},r]);return er(t??{},o??{})},vd=({state:e},{sectionId:t})=>{let n=le({state:e},{sectionId:t});if(!n?.lines)return[];let r=[],o={};for(let i of n.lines){let s=i.actions||{},l=Ye([o,s]),a=er(o,l);r.push({id:i.id,changes:a,presentationState:l}),o=tr(l)}return r},Cd=({state:e},{sectionId:t,includePresentationState:n=!1})=>{let r=vd({state:e},{sectionId:t});return n?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},_s=({state:e})=>{let{sectionId:t,lineId:n}=Ie({state:e}).pointer,o=le({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===n);if(i<=0)return null;let l=o.slice(0,i).map(a=>{let c=a.actions||{},u={};return Object.keys(c).forEach(d=>{u[d]=c[d]}),u});return tr(Ye(l))},Br=({state:e},{slotsPerPage:t=6}={})=>{let o=((Mr({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let l=o+s,a=e.global.saveSlots&&e.global.saveSlots[Tt(l)]||{};i.push({...a,slotId:l})}return{saveSlots:i}},Sd=Cs,_d=Br,Rd=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!n||!Array.isArray(n.timeline)||typeof n.currentIndex!="number"?!1:n.currentIndex>=0&&n.currentIndex<n.timeline.length-1},Od=({state:e},t={})=>{let n=Ss({state:e}),r=_s({state:e}),o=In({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:T(i)}:o,l=i?.animations&&r===null?{}:r,{sectionId:a}=Ie({state:e}).pointer,{sceneId:c}=pt(e.projectData,a),u=Mr({state:e}),d=t?.activePersistentAnimations??[],f=t?.restoredPersistentAnimations??[],p=Dt({state:e}),h=vs({state:e}),g=bn({state:e}),{saveSlots:b}=Br({state:e}),A=Rd(e);return _i({presentationState:n,previousPresentationState:l,currentLineActions:s,resources:e.projectData.resources,currentSceneId:c,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:js({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||A,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:Es({state:e}),saveSlots:b,variables:g,runtime:u,activePersistentAnimations:d,restoredPersistentAnimations:f})},kd=({state:e},t)=>(e.global.confirmDialog=Nu(t),e.global.pendingEffects.push({name:"render"}),e),Ld=({state:e})=>(e.global.confirmDialog&&(ht(e),e.global.pendingEffects.push({name:"render"})),e),$d=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Se(e,"pushOverlay",t),e),Td=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Se(e,"popOverlay",void 0),e),Dd=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),Se(e,"replaceLastOverlay",t),e),Nd=({state:e})=>(e.global.overlayStack=[],ht(e),mt(e),e.global.pendingEffects.push({name:"render"}),Se(e,"clearOverlays",void 0),e),Pd=(e,{activeInteraction:t})=>{e.global.autoMode&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),t&&e.global.skipMode&&e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},wn=(e,t,{screenTransition:n}={})=>{e.global.isLineCompleted=!1,Vu(e,n),mt(e);let r=Ae({state:e},{pointer:t}),o=r?.source===ft,i=r?.source===Fe;return Pd(e,{activeInteraction:r}),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:r}},En=(e,t,n)=>{!(t?.source===ft||t?.source===Fe)||n||!e.global.skipMode||e.global.pendingEffects.push({name:"startSkipNextTimer"})},Rs=({state:e})=>(Ae({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:An({state:e})}}),e.global.pendingEffects.push({name:"render"})),e),Nt=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Vd=({state:e})=>{let t=e.global.autoMode;return Ae({state:e})&&!t||(t?Nt({state:e}):Rs({state:e})),e},Os=({state:e})=>(Ae({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),Me=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),jd=({state:e})=>{let t=As({state:e});return Ae({state:e})&&!t||(t?Me({state:e}):Os({state:e})),e},xn=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Se(e,"showDialogueUI",void 0),e),ks=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Se(e,"hideDialogueUI",void 0),e),Fd=({state:e})=>(ws({state:e})?xn({state:e}):ks({state:e}),e),Be=(e,t,n)=>(gs(e,t,n),Gu(e),e.global.pendingEffects.push({name:"render"}),e),Pt=(e,t,n,r)=>{let o=gs(e,t,n);return e.global.pendingEffects.push({name:"render"}),Se(e,r,{value:o}),e},Md=({state:e},t)=>Be(e,"dialogueTextSpeed",t?.value),Bd=({state:e},t)=>Be(e,"autoForwardDelay",t?.value),Ud=({state:e},t)=>Be(e,"autoForwardSpeed",t?.value),zd=({state:e},t)=>Be(e,"skipUnseenText",t?.value),qd=({state:e},t)=>Be(e,"skipTransitionsAndAnimations",t?.value),Hd=({state:e},t)=>Be(e,"soundVolume",t?.value),Wd=({state:e},t)=>Be(e,"musicVolume",t?.value),Yd=({state:e},t)=>Be(e,"muteAll",t?.value),Gd=({state:e},t)=>Pt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),Kd=({state:e})=>{let t=Pe(e,"saveLoadPagination")+1;return Pt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},Jd=({state:e})=>{let t=Pe(e,"saveLoadPagination")-1;return Pt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},Xd=({state:e},t)=>Pt(e,"menuPage",t?.value,"setMenuPage"),Qd=({state:e},t)=>Pt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Zd=({state:e})=>(e.global.pendingEffects=[],e),ef=({state:e},t)=>(e.global.pendingEffects.push(t),e),tf=({state:e},t)=>{let n=t?.resourceId;return Qi(e,n),e.global.pendingEffects.push({name:"completeAchievement",payload:{resourceId:n}}),e},nf=({state:e},t)=>{let n=t?.resourceId,r=Qi(e,n);if(r.type!=="number")throw new Error(`Achievement resource "${n}" does not support numeric progress`);let o=t?.current;if(!Number.isInteger(o)||o<0)throw new Error(`Achievement progress for "${n}" must be a non-negative integer`);if(!Number.isInteger(r.target)||r.target<1)throw new Error(`Achievement resource "${n}" must have a positive integer target`);let i=Math.min(o,r.target);return e.global.pendingEffects.push({name:"setAchievementProgress",payload:{resourceId:n,current:i,target:r.target,completed:i>=r.target}}),e},Ls=(e,{sectionId:t,resetStoryState:n=!1,screen:r})=>{let o=!!us(r),i=le({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(n&&!Xu(e,{queueRender:!o}))return e;let l=Ae({state:e});n&&e.global.skipMode&&Me({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let u=gt(a),d=u.read;n||et(e,{sectionId:d?.sectionId,lineId:d?.lineId}),a.rollback||tt(a,{compatibilityAnchor:!0}),u.read={sectionId:t,lineId:s.id},n?a.rollback=$t({pointer:u.read}):jr(e,{sectionId:t,lineId:s.id})}let{activeInteraction:c}=wn(e,a?.pointers?.read,{screenTransition:r});return En(e,l,c),e},rf=({state:e},t)=>Ls(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),$s=e=>(e.global.accountViewedRegistry=yu(e.global.accountViewedRegistry),e.global.accountViewedRegistry),Ur=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(n=>({scope:n.scope,path:n.path,op:n.op,value:T(n.value)}))}})},Ts=(e,t)=>{Ur(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(n=>({sectionId:n.sectionId,...n.lastLineId===void 0?{}:{lineId:n.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},of=(e,t,{sectionId:n,lineId:r})=>{if(!n||!r)return!1;let o=$(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===n);if(i){if(i.lastLineId===void 0)return!1;let s=le({state:e},{sectionId:n});if(s?.lines){let l=s.lines.findIndex(c=>c.id===i.lastLineId),a=s.lines.findIndex(c=>c.id===r);if(l===-1||a>l)return i.lastLineId===r?!1:(i.lastLineId=r,!0)}else return i.lastLineId===r?!1:(i.lastLineId=r,!0);return!1}else return o.sections.push({sectionId:n,lastLineId:r}),!0},et=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;of(e,$s(e),t)&&Ts(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},sf=({state:e},t)=>(et(e,t),e.global.pendingEffects.push({name:"render"}),e),af=({state:e},t)=>{let{resourceId:n}=t;if(e.global.accountViewedRegistry!==void 0){let r=$s(e);r.resources.find(i=>i.resourceId===n)||(r.resources.push({resourceId:n}),Ts(e,{sections:[],resources:[{resourceId:n}]}))}return e.global.pendingEffects.push({name:"render"}),e},Ds=({state:e},t)=>{let n=wu(t.manual),{auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;n&&r?(e.global.nextLineConfig={manual:n,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let a=e.global.nextLineConfig.auto?.enabled,c=Ae({state:e});return!l&&!c&&a===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!l&&a===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),Se(e,"setNextLineConfig",t),e},cf=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:r}=t,o=t?.savedAt,i=Tt(n),s=T(e.contexts);s?.forEach(c=>{gt(c),bs(c.rollback),vu(c.rollback)});let l={contexts:s},a={formatVersion:Xi,slotId:ts(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:l};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},lf=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=Tt(n),o=e.global.saveSlots[r];if(o){let i=Du(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=gn(),e.global.overlayStack=[],e.global.isLineCompleted=!0,ht(e),mt(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},uf=({state:e},t)=>{let{projectData:n}=t;es(n),e.projectData=n;let r=n?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=Qt(n??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...st(e.global.variables,r)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...st(s.variables,r)})}),ht(e),mt(e),e.global.pendingEffects.push({name:"render"}),e},df=({state:e},t)=>{let{sectionId:n,lineId:r}=t;if(!r)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=n||o.pointers.read?.sectionId;if(n&&!le({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=le({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(d=>d.id===r))return console.warn(`Line not found: ${r} in section ${i}`),e;let a=Ae({state:e}),c=gt(o);c.read={sectionId:i,lineId:r};let{activeInteraction:u}=wn(e,c.read);return En(e,a,u),e},ff=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return xn({state:e}),e;let n=Ae({state:e});if(n?.source===ft&&t?.bypassChoice!==!0||n?.source===Fe&&t?._interactionSource!==Fe)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=Ie({state:e})?.pointer,d=u?.sectionId,f=u?.lineId;d&&f&&et(e,{sectionId:d,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&!n&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:An({state:e})}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&!n&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let r=Ie({state:e})?.pointer,o=r?.sectionId,i=le({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],l=i?.lines||[],c=l.findIndex(u=>u.id===r?.lineId)+1;if(c<l.length){let u=l[c],d=!Pe(e,"skipUnseenText");if(e.global.skipMode&&d&&!Fr({state:e},{sectionId:o,lineId:u.id}))return Me({state:e}),e;if(s&&!s.rollback&&tt(s,{compatibilityAnchor:!0}),s){let p=gt(s),h=p.read?.lineId;h&&o&&et(e,{sectionId:o,lineId:h}),p.read={sectionId:o,lineId:u.id}}jr(e,{sectionId:o,lineId:u.id}),Dr(e);let{activeInteraction:f}=wn(e,{sectionId:o,lineId:u.id});En(e,n,f)}else e.global.autoMode&&Nt({state:e}),e.global.skipMode&&Me({state:e});return e},pf=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ae({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:An({state:e})}});let n=Ie({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&et(e,{sectionId:r,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},hf=({state:e},t)=>Ls(e,{sectionId:t?.sectionId,screen:t?.screen}),mf=({state:e},t)=>{let n=t?._conditionalContinuation===!0;if(e.global.dialogueUIHidden&&!n)return xn({state:e}),e;let r=Ae({state:e});if(r?.source===ft&&t?.bypassChoice!==!0||r?.source===Fe&&t?._interactionSource!==Fe||r&&r.source!==ft&&r.source!==Fe)return e;let o=Ie({state:e})?.pointer,i=o?.sectionId,s=le({state:e},{sectionId:i}),l=e.contexts[e.contexts.length-1],a=s?.lines||[],u=a.findIndex(d=>d.id===o?.lineId)+1;if(u<a.length){let d=a[u],f=!Pe(e,"skipUnseenText");if(e.global.skipMode&&f&&!Fr({state:e},{sectionId:i,lineId:d.id})&&(Me({state:e}),!n))return e;if(l&&!l.rollback&&tt(l,{compatibilityAnchor:!0}),l){let h=gt(l),g=h.read?.lineId;g&&i&&et(e,{sectionId:i,lineId:g}),h.read={sectionId:i,lineId:d.id}}jr(e,{sectionId:i,lineId:d.id}),Dr(e);let{activeInteraction:p}=wn(e,{sectionId:i,lineId:d.id});En(e,r,p)}else e.global.autoMode&&Nt({state:e}),e.global.skipMode&&Me({state:e}),e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},zr=(e,t={})=>{let n=Dt({state:e});return!n||t.formKey&&t.formKey!==n.key||t.formId&&t.formId!==n.id?null:n},gf=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let n=e.projectData.resources?.variables?.[t.variableId],r=n?.scope,o=n?.type;if(Ne(n))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(n?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return Zt(r,t.variableId),en(o,"set",t.variableId),{variableConfig:n,scope:r}},yf=(e,t)=>({id:e.id,key:e.key,valid:!0,values:T(t),fields:T(e.fields),fieldList:T(e.fieldList)}),bf=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ie({state:e})?.pointer,n=t?.sectionId,r=t?.lineId;n&&r&&et(e,{sectionId:n,lineId:r})},If=({state:e},t={})=>{let n=zr(e,t),r=t.field;if(!n?.fields?.[r])return e;let o=fs(e,n.key),i=hn(t.value),s=n.fields[r],l=Nr(s,i);return o.values[r]=i,o.touched[r]=!0,l?o.errors[r]=l:delete o.errors[r],e.global.pendingEffects.push({name:"render"}),e},Af=({state:e},t={})=>{let n=zr(e,t);if(!n)return{submitted:!1,valid:!1,reason:"inactive"};let r=fs(e,n.key);r.submitted=!0;let o={},i={};if(Object.entries(n.fields).forEach(([d,f])=>{let p=Object.prototype.hasOwnProperty.call(r.values,d)?r.values[d]:f.value,h=Nr(f,p);r.touched[d]=!0,h&&(i[d]=h),o[d]=ds(f,p)}),r.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:T(i),form:{id:n.id,key:n.key,values:T(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let l=!1,a=[],c=[];Object.entries(n.fields).forEach(([d,f])=>{let{scope:p}=gf(e,f),h=p==="context"?s.variables:e.global.variables,g=o[d];h[f.variableId]=tn(h[f.variableId],"set",g),p==="context"&&(l=!0,c.push({variableId:f.variableId,op:"set",value:g})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${f.variableId}`,op:"set",value:T(h[f.variableId])})}),l&&Se(e,"updateVariable",{id:"submitForm",operations:c}),Ur(e,a);let u=yf(n,o);return bf(e),delete e.global.formDrafts[n.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},wf=({state:e},t={})=>{let n=zr(e,t);return n?(delete e.global.formDrafts?.[n.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:n.id,key:n.key,values:T(n.values),fields:T(n.fields),fieldList:T(n.fieldList)}}):{cancelled:!1,reason:"inactive"}},Ef=({state:e},t)=>{let{id:n,operations:r=[]}=t;if(!n)throw new Error("updateVariable requires an id field");if(typeof n!="string"||!/^[a-zA-Z0-9]+$/.test(n))throw new Error(`updateVariable id must be alphanumeric, got: "${n}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],l=[];return r.forEach(({variableId:a,op:c,value:u,roundTo:d})=>{let f=e.projectData.resources?.variables?.[a],p=f?.scope,h=f?.type;if(Ne(f))throw new Error(`Cannot update computed variable: ${a}`);if(f?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);Zt(p,a),en(h,c,a),Qn(h,c,u,a,{roundTo:d});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let b={variableId:a,op:c,value:u};d!==void 0&&(b.roundTo=d),l.push(b)}g[a]=tn(g[a],c,u,{roundTo:d}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:T(g[a])})}),i&&Se(e,"updateVariable",{id:n,operations:l}),Ur(e,s),e.global.pendingEffects.push({name:"render"}),e},xf=e=>(t,n)=>e({state:t},n),vf=e=>({variables:vt({variables:{...e.global?.variables??{},...yn(e)?.variables??{}},runtime:Ke(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:Ke(e)}),Cf=e=>{if(!$(e))throw new Error("conditional action payload must be an object");if(!Array.isArray(e.branches))throw new Error("conditional action requires branches array");if(e.branches.length===0)throw new Error("conditional action requires at least one branch")},Sf=(e,t,n)=>{if(!$(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!$(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==n-1)throw new Error("conditional else branch must be the last branch")},_f=(e,t)=>{Cf(t);for(let n=0;n<t.branches.length;n+=1){let r=t.branches[n];if(Sf(r,n,t.branches.length),!(Object.prototype.hasOwnProperty.call(r,"when")&&!xt(r.when,vf(e)))){Object.entries(r.actions).forEach(([i,s])=>{Ns(e,i,s)});return}}},Rf={conditional:{replayLine:_f},updateVariable:{recordSources:[Pr],replayLine:Ji,replayRecorded:Ji,persistInSaveSlot:!0},setNextLineConfig:{replayLine:xf(Ds)}},vn=e=>Rf[e]??null,Of=e=>vn(e)?.persistInSaveSlot===!0,kf=(e,t)=>{let n=vn(e)?.recordSources;return Array.isArray(n)&&n.includes(t)},Lf=(e,t,n)=>{vn(t)?.replayRecorded?.(e,n)},Ns=(e,t,n)=>{vn(t)?.replayLine?.(e,n)},$f=e=>e?.returnable!==!1,Ps=(e,t)=>{if(t>=0)return e.currentIndex+t;let n=Math.abs(t);for(let r=e.currentIndex-1;r>=0;r-=1)if($f(e.timeline[r])&&(n-=1,n===0))return r;return-1},Vs=({state:e},t)=>{let{offset:n}=t;if(n===void 0||typeof n!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let r=e.contexts[e.contexts.length-1];if(!r)return null;let o=r.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=Ps(o,n);if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},js=({state:e})=>Vs({state:e},{offset:-1})!==null,Tf=({state:e},t)=>{let{offset:n=-1}=t;if(n>=0)throw new Error("rollbackByOffset requires a negative offset");let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let o=tt(r,{compatibilityAnchor:!r.rollback}),i=Ps(o,n);return i<0||i>=o.timeline.length?e:Is(e,i)},Df=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=tt(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===n&&a.lineId===r);if(l===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return l===i.currentIndex?e:Is(e,l)},Fs=e=>{let t=ad(e);return To(t,{selectPendingEffects:ld,selectSkipMode:As,selectAutoMode:ud,selectIsChoiceVisible:vs,selectIsFormVisible:fd,selectActiveInteraction:Ae,selectActiveForm:Dt,selectDialogueUIHidden:ws,selectDialogueHistory:Es,selectConfirmDialog:dd,selectIsLineAccountViewed:Fr,selectIsResourceAccountViewed:md,selectNextLineConfig:gd,selectSystemState:yd,selectAchievements:bd,selectAchievement:Id,selectSaveSlotMap:Cs,selectSaveSlots:Sd,selectSaveSlot:Ad,selectRuntime:Mr,selectRuntimeValue:wd,selectAllVariables:bn,selectCurrentPointer:Ie,selectSection:le,selectCurrentLine:In,selectPresentationState:Ss,selectAutoForwardTimerDelay:An,selectPresentationChanges:xd,selectSectionLineChanges:Cd,selectSaveSlotPage:Br,selectCurrentPageSlots:_d,selectRenderState:Od,selectOverlayStack:cd,selectLineIdByOffset:Vs,selectCanRollback:js,selectRollbackCursor:Zu,startAutoMode:Rs,stopAutoMode:Nt,toggleAutoMode:Vd,startSkipMode:Os,stopSkipMode:Me,toggleSkipMode:jd,showDialogueUI:xn,hideDialogueUI:ks,toggleDialogueUI:Fd,setDialogueTextSpeed:Md,setAutoForwardDelay:Bd,setAutoForwardSpeed:Ud,setSkipUnseenText:zd,setSkipTransitionsAndAnimations:qd,setSoundVolume:Hd,setMusicVolume:Wd,setMuteAll:Yd,setSaveLoadPagination:Gd,incrementSaveLoadPagination:Kd,decrementSaveLoadPagination:Jd,setMenuPage:Xd,setMenuEntryPoint:Qd,showConfirmDialog:kd,hideConfirmDialog:Ld,resetStoryAtSection:rf,clearPendingEffects:Zd,appendPendingEffect:ef,completeAchievement:tf,setAchievementProgress:nf,beginRollbackActionBatch:rd,endRollbackActionBatch:od,markRollbackCheckpointTransient:ed,markSavedRollbackCheckpointTransient:td,addViewedLine:sf,addViewedResource:af,setNextLineConfig:Ds,saveSlot:cf,loadSlot:lf,updateProjectData:uf,sectionTransition:hf,jumpToLine:df,nextLine:ff,markLineCompleted:pf,rollbackToLine:Df,rollbackByOffset:Tf,pushOverlay:$d,popOverlay:Td,replaceLastOverlay:Dd,clearOverlays:Nd,updateFormField:If,submitForm:Af,cancelForm:wf,updateVariable:Ef,nextLineFromSystem:mf},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var Nf="route-engine",Pf="projectPersistence";var Bs=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),ee=e=>Object.prototype.toString.call(e)==="[object Object]",Ms="variables.",Vf=(e={})=>{let t=ee(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!ee(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lineId=="string"?{lineId:n.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!ee(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},jf=(e={})=>{let t=ee(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!ee(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lastLineId=="string"?{lastLineId:n.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!ee(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},Ff=(e,t)=>{let n=jf(e),r=Vf(t),o=n.sections.map(s=>({...s})),i=n.resources.map(s=>({...s}));return r.sections.forEach(s=>{let l=o.find(a=>a.sectionId===s.sectionId);if(!l){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(l.lastLineId!==void 0){if(s.lineId===void 0){delete l.lastLineId;return}l.lastLineId=s.lineId}}),r.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},Us=(e={})=>{let t=ee(e)?e:{};return{saveSlots:ee(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:ee(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:ee(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:ee(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:ee(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Mf=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,n)=>{if(!ee(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${n}] entry.`);let r=t.path?.startsWith(Ms)?t.path.slice(Ms.length):null;if(r!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(r.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${n}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:r}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${n}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${n}].`)})},Bf=(e,t)=>{let n={};return Mf(t).forEach(r=>{if(r.path==="viewedRegistry"){n.accountViewedRegistry=Ff(n.accountViewedRegistry??e.accountViewedRegistry,r.value);return}let o=r.scope==="device"?"globalDeviceVariables":"globalAccountVariables";n[o]={...e[o],...n[o],[r.variableId]:r.value}}),n},qr=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},Uf=e=>{let t=qr(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},zf=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},qf=({indexedDB:e,databaseName:t,objectStoreName:n})=>new Promise((r,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(n)||s.createObjectStore(n,{keyPath:"namespace"})},i.onsuccess=()=>{r(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),Hf=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let a=r.transaction(t,"readonly").objectStore(t).get(n);a.onsuccess=()=>{o(a.result??null)},a.onerror=()=>{i(a.error??new Error(`Failed to read persisted namespace "${n}" from IndexedDB.`))}})},Vt=async({databasePromise:e,objectStoreName:t,namespace:n,patch:r})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),a=l.objectStore(t),c=a.get(n),u=!1,d=p=>{u||(u=!0,s(p))},f=()=>{u||(u=!0,i())};c.onerror=()=>{d(c.error??new Error(`Failed to read persisted namespace "${n}" before updating IndexedDB.`))},c.onsuccess=()=>{let p=Us(c.result),h=typeof r=="function"?r(p):r,g={namespace:n,version:1,...Bs(),...p,...h},b=a.put(g);b.onerror=()=>{d(b.error??new Error(`Failed to persist namespace "${n}" to IndexedDB.`))}},l.oncomplete=()=>{f()},l.onerror=()=>{d(l.error??new Error(`IndexedDB transaction failed while updating namespace "${n}".`))},l.onabort=()=>{d(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${n}".`))}})},Wf=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let s=r.transaction(t,"readwrite"),a=s.objectStore(t).delete(n),c=!1,u=f=>{c||(c=!0,i(f))},d=()=>{c||(c=!0,o())};a.onerror=()=>{u(a.error??new Error(`Failed to clear persisted namespace "${n}" from IndexedDB.`))},s.oncomplete=()=>{d()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${n}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${n}".`))}})},Hr=(e={})=>{let{indexedDB:t,databaseName:n=Nf,objectStoreName:r=Pf,namespace:o}=e,i=zf(t),s=Uf(o),l=qf({indexedDB:i,databaseName:n,objectStoreName:r});return{namespace:s,load:async()=>{let a=await Hf({databasePromise:l,objectStoreName:r,namespace:s});return{...Bs(),...Us(a)}},clear:async()=>Wf({databasePromise:l,objectStoreName:r,namespace:s}),saveSlots:async a=>Vt({databasePromise:l,objectStoreName:r,namespace:s,patch:{saveSlots:ee(a)?a:{}}}),saveGlobalDeviceVariables:async a=>Vt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:ee(a)?a:{}}}),saveGlobalAccountVariables:async a=>Vt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalAccountVariables:ee(a)?a:{}}}),saveGlobalRuntime:async a=>Vt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalRuntime:ee(a)?a:{}}}),applyScopedDataUpdates:async a=>Vt({databasePromise:l,objectStoreName:r,namespace:s,patch:c=>Bf(c,a)})}},Yf=Hr;var Gf=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Kf=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),zs="conditional",Gr=Symbol("conditionalAutoContinue"),Jf=new Set(["sectionTransition","resetStoryAtSection"]),Xf=new Set(["nextLine","nextLineFromSystem","resetStoryAtSection","sectionTransition"]),Qf=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),Wr="form",Zf=new Set(["submitForm","cancelForm"]),jt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Cn=e=>e?.type===Gr,Yr=(e,t)=>e?.sectionId===t?.sectionId&&e?.lineId===t?.lineId;function Kr(e){let t,n=0,r=null,o=0,i=!1,s=0,l=[],a=null,c=new Map,u=new Map,d=new Map,{handlePendingEffects:f}=e,p=(y=new Map,I=Date.now())=>new Map(Array.from(y.entries()).filter(([,x])=>I<x.expiresAt).map(([x,_])=>[x,{animation:structuredClone(_.animation),startedAt:_.startedAt,expiresAt:_.expiresAt}])),h=(y=new Map)=>Array.from(y.values()).map(I=>structuredClone(I.animation)),g=(y=Date.now())=>{c=new Map(Array.from(c.entries()).filter(([,I])=>y<I.expiresAt))},b=()=>{if(!(o>0||i)){i=!0;try{for(;t.selectPendingEffects().length>0;){let y=[...t.selectPendingEffects()];t.clearPendingEffects();try{f(y)}catch(I){throw t.clearPendingEffects(),y.forEach(x=>{t.appendPendingEffect(x)}),I}}}finally{i=!1}}},A=y=>{o+=1;try{return y()}finally{o-=1,b()}},w=({initialState:y,namespace:I})=>{t=Fs(y),n=0,r=qr(I),o=0,i=!1,s=0,l=[],a=null,c=new Map,u=new Map,d=new Map,t.appendPendingEffect({name:"handleLineActions"}),b()},C=()=>r,R=()=>t.selectPresentationState(),V=()=>t.selectPresentationChanges(),j=y=>t.selectSectionLineChanges(y),E=(y={})=>{n+=1;let I=Date.now();g(I);let x=u.size>0,_=p(c,I),D=x?p(u,I):new Map,q={...t.selectRenderState({activePersistentAnimations:h(_),restoredPersistentAnimations:h(D)}),id:`render-${n}`};return d.set(q.id,{builtAt:I,persistentAnimationSessions:new Map([...D.entries(),..._.entries()]),usedRestoredPersistentAnimationSessions:x}),q},B=(y={})=>E(y),U=(y={})=>E(y),J=y=>{let I=typeof y?.id=="string"&&y.id.length>0?y.id:null,x=I?d.get(I):null;I&&d.delete(I);let _=new Map;di(y?.animations).forEach(D=>{let H=cn(D);if(!H)return;let q=x?.persistentAnimationSessions?.get(H)??c.get(H),rt=Math.max(0,pi(D)),yt=q?.startedAt??x?.builtAt??Date.now();_.set(H,{animation:structuredClone(D),startedAt:yt,expiresAt:yt+rt})}),c=_,x?.usedRestoredPersistentAnimationSessions&&(u=new Map)},M=()=>t.selectSystemState(),Y=()=>t.selectAchievements(),G=y=>t.selectAchievement(y),X=()=>t.selectSaveSlotMap(),ve=y=>t.selectSaveSlot(y),te=y=>t.selectSaveSlotPage(y),ne=()=>t.selectSkipMode(),ue=()=>t.selectAutoMode(),de=()=>t.selectRuntime(),Q=()=>t.selectIsChoiceVisible(),re=()=>t.selectIsFormVisible(),fe=()=>t.selectActiveInteraction(),S=()=>t.selectPendingEffects().some(y=>y?.name==="handleLineActions"||y?.name==="render"),O=(y,I,x={})=>!jt(I)||y!=="nextLine"?I:x.bypassChoice===!0?{...I,bypassChoice:!0}:x.interactionSource===Wr?{...I,_interactionSource:Wr}:I,F=(y={})=>({type:Gr,payload:O("nextLine",{_conditionalContinuation:!0},y)}),oe=(y,I)=>Cn(y)?{type:Gr,payload:{...y.payload,...I.payload}}:I,ie=y=>{y.savedCheckpointOccurrences.forEach(I=>{t.markSavedRollbackCheckpointTransient(I)}),y.savedCheckpointOccurrences=[]},z=(y,I)=>{let x=a;return a=null,!x||!Yr(x.pointer,y)||x.checkpointIndex!==I?.checkpointIndex||x.checkpointIdentity!==I?.checkpoint?[]:x.savedCheckpointOccurrences},Le=y=>{y.markCurrentCheckpointTransient&&(t.markRollbackCheckpointTransient({checkpointIndex:y.rollbackCursor?.checkpointIndex,checkpointIdentity:y.rollbackCursor?.checkpoint,sectionId:y.pointer?.sectionId,lineId:y.pointer?.lineId}),ie(y))},nt=(y,I,x)=>Xf.has(y)?y==="resetStoryAtSection"?x?.checkpoint!==I?.checkpoint:x?.checkpoint!==I?.checkpoint&&x?.checkpointIndex>I?.checkpointIndex:!1,Ws=y=>{let I=l.at(-1);if(!I?.markCurrentCheckpointTransient)return;let x=t.selectSaveSlot({slotId:y?.slotId});x&&I.savedCheckpointOccurrences.push({slotId:y.slotId,saveSlotIdentity:x,checkpointIndex:I.rollbackCursor?.checkpointIndex,sectionId:I.pointer?.sectionId,lineId:I.pointer?.lineId})},Ys=(y,I,x)=>{let _=l.at(-1);if(!_)return;let D=t.selectCurrentPointer()?.pointer,H=nt(y,I,x);if(Yr(_.pointer,D)){let q=x?.checkpoint!==I?.checkpoint||x?.checkpointIndex!==I?.checkpointIndex;(H||q&&Qf.has(y))&&(Le(_),_.pointer=D,_.rollbackCursor=x,_.markCurrentCheckpointTransient=H,_.savedCheckpointOccurrences=[]);return}Le(_),_.pointer=D,_.rollbackCursor=t.selectRollbackCursor?.()??null,_.markCurrentCheckpointTransient=H,_.savedCheckpointOccurrences=[]},Ft=(y,I)=>{if(!t[y])return;Jf.has(y)&&(s+=1),Gf.has(y)&&(Kf.has(y)?u=p(c):u=new Map,c=new Map);let x=t.selectRollbackCursor?.()??null,_=t[y](I),D=t.selectRollbackCursor?.()??null;return y==="saveSlot"&&Ws(I),Ys(y,x,D),b(),_},Gs=(y,I,x)=>{let _=t.selectCurrentPointer()?.pointer;I!==_||x!==s||(t.appendPendingEffect({name:"clearAutoNextTimer"}),t.appendPendingEffect({name:"clearNextLineConfigTimer"}),Ft("nextLineFromSystem",y.payload))},Xr=(y,I={})=>A(()=>{let x,_=t.selectCurrentPointer()?.pointer??null,D=t.selectRollbackCursor?.()??null,H=s,q={pointer:_,rollbackCursor:D,markCurrentCheckpointTransient:I.rollbackSource==="line",savedCheckpointOccurrences:I.savedCheckpointOccurrences?.slice()??[]};l.push(q);try{t.beginRollbackActionBatch({source:I.rollbackSource});try{x=y()}finally{t.endRollbackActionBatch({})}Cn(x)&&Gs(x,_,H)}finally{l.pop(),(!Yr(_,q.pointer)||D?.checkpoint!==q.rollbackCursor?.checkpoint)&&q.markCurrentCheckpointTransient&&q.savedCheckpointOccurrences.length>0&&(a={pointer:q.pointer,checkpointIndex:q.rollbackCursor?.checkpointIndex,checkpointIdentity:q.rollbackCursor?.checkpoint,savedCheckpointOccurrences:q.savedCheckpointOccurrences})}}),Qr=(y,I,x,_={})=>{if(y===zs)return Xr(()=>{let D=_n(x),H=nr({[y]:I},D);return Zr(H[y],x,_)},_);Ft(y,I)},Ks=(y,I)=>{Qr(y,I)},_n=y=>{if(!y)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(y,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:I,...x}=y,_=t.selectAllVariables?t.selectAllVariables():void 0;return{...x,_event:I,variables:_,runtime:t.selectRuntime?t.selectRuntime():{}}},Js=y=>{if(!jt(y))throw new Error("conditional action payload must be an object");if(!Array.isArray(y.branches))throw new Error("conditional action requires branches array");if(y.branches.length===0)throw new Error("conditional action requires at least one branch")},Xs=(y,I,x)=>{if(!jt(y))throw new Error(`conditional branch at index ${I} must be an object`);if(!jt(y.actions))throw new Error(`conditional branch at index ${I} requires actions object`);if(!Object.prototype.hasOwnProperty.call(y,"when")&&I!==x-1)throw new Error("conditional else branch must be the last branch")},Zr=(y,I,x)=>{Js(y);let _=F(x);for(let D=0;D<y.branches.length;D+=1){let H=y.branches[D];Xs(H,D,y.branches.length);let q=_n(I);if(Object.prototype.hasOwnProperty.call(H,"when")&&!xt(H.when,q))continue;let yt=Rn(H.actions,I,x);return Cn(yt)?oe(_,yt):_}return _},Qs=(y,I)=>({...y??{},_form:I}),Zs=(y,I,x,_)=>{let D=Ft(y,I),H=D?.submitted===!0&&D.valid===!0,q=D?.cancelled===!0;if(!(!H&&!q)&&jt(I.actions))return Rn(I.actions,Qs(x,D.form),{..._,interactionSource:Wr})},ea=(y,I,x,_)=>{let D=_n(x),q=nr({[y]:I},D)[y];if(y===zs)return Zr(q,x,_);let rt=O(y,q,_);if(Zf.has(y))return Zs(y,rt,x,_);Ft(y,rt)},Rn=(y,I,x)=>{let _;return Object.entries(y).forEach(([D,H])=>{let q=ea(D,H,I,x);Cn(q)&&(_=oe(_,q))}),_},eo=(y,I,x={})=>Xr(()=>Rn(y,I,x),x),ta=y=>{let I=t.selectCurrentPointer()?.pointer;if(y!==I||t.selectActiveInteraction())return;let x=t.selectNextLineConfig();x?.auto?.enabled&&x.auto.trigger==="fromStart"&&t.appendPendingEffect({name:"nextLineConfigTimer",payload:{delay:x.auto.delay}})};return{init:w,handleAction:Qr,handleInternalAction:Ks,handleActions:eo,selectRenderState:B,prepareRenderState:U,commitRenderState:J,selectPresentationState:R,selectPresentationChanges:V,selectSectionLineChanges:j,selectSystemState:M,selectAchievements:Y,selectAchievement:G,selectSaveSlotMap:X,selectSaveSlot:ve,selectSaveSlotPage:te,selectSaveSlots:X,selectRuntime:de,selectIsChoiceVisible:Q,selectIsFormVisible:re,selectActiveInteraction:fe,selectHasPendingRenderWork:S,handleLineActions:()=>A(()=>{let y=t.selectCurrentPointer()?.pointer,I=t.selectRollbackCursor?.()??null,x=z(y,I),_=t.selectCurrentLine(),D=!1;return _?.actions&&(eo(_.actions,void 0,{rollbackSource:"line",savedCheckpointOccurrences:x}),D=!0),ta(y),D}),getNamespace:C}}var Jr=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},ep=80,Hs=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{if(e.selectHasPendingRenderWork?.())return;let o=e.prepareRenderState?.(r)??e.selectRenderState(r);n?.(o),t.render(o),e.commitRenderState?.(o)},tp=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&Hs({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},np=({engine:e,ticker:t,autoTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(t.remove(i),n.setCallback(null),n.setElapsed(0),Sn(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},rp=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},op=({engine:e,ticker:t,skipTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r?.delay??ep;n.getElapsed()>=l&&(n.setElapsed(0),Sn(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},ip=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},sp=({engine:e,ticker:t,nextLineConfigTimerState:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(n.setElapsed(0),Sn(e,"nextLineFromSystem",{}),t.remove(i),n.getCallback()===i&&n.setCallback(null))};n.setCallback(i),t.add(i)},ap=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},cp=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveSlots(t?.saveSlots))},lp=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalDeviceVariables(t?.globalDeviceVariables))},up=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalAccountVariables(t?.globalAccountVariables))},dp=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalRuntime(t?.globalRuntime))},fp=({enqueuePersistenceWrite:e},t)=>{e(n=>{if(typeof n.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return n.applyScopedDataUpdates(t?.updates)})},qs={render:Hs,saveSlots:cp,saveGlobalDeviceVariables:lp,saveGlobalAccountVariables:up,saveGlobalRuntime:dp,applyScopedDataUpdates:fp,handleLineActions:tp,startAutoNextTimer:np,clearAutoNextTimer:rp,startSkipNextTimer:op,clearSkipNextTimer:ip,nextLineConfigTimer:sp,clearNextLineConfigTimer:ap},pp=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Sn=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},hp=(e=[])=>{let t=new Set,n=[];for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!pp.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},mp=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let a=Jr(),c=Jr(),u=Jr(),d=s??null,f=Promise.resolve(),p=null,h=null,g=!1,b=0,A=S=>{if(o){o(S);return}console.error("RouteEngine persistence write failed.",S)},w=()=>{if(d)return d;let S=e();return d=Hr({indexedDB:i,namespace:l??S?.getNamespace?.()}),d},C=S=>{f=f.catch(()=>{}).then(()=>{let O=w();return S(O)}).catch(O=>{A(O)})},R=S=>{let O=typeof S?.id=="string"&&S.id.length>0?S.id:null;b+=1,p=O,g=!1},V=()=>b,j=(S={})=>{if(S?.aborted===!0)return!1;let O=typeof S?.id=="string"&&S.id.length>0?S.id:null;return O?O!==p||O===h?!1:(h=O,!0):p!==null||g?!1:(g=!0,!0)},E=(S,O={})=>{if(S!=="renderComplete"||!j(O))return!1;let F=e();return Sn(F,"markLineCompleted",{}),!0},B=new Set(["updateFormField","submitForm","cancelForm"]),U=new Set(["updateVariable"]),J=S=>typeof S?.selectActiveInteraction=="function"?S.selectActiveInteraction():typeof S?.selectIsChoiceVisible=="function"&&S.selectIsChoiceVisible()?{source:"choice"}:null,M=S=>S?._formKey??S?.formKey,Y=(S,O)=>M(S)===O?.formKey,G=(S,O)=>!S||typeof S!="object"||Array.isArray(S)?!1:S._interactionSource===O?.source,X=(S,O)=>G(S,O)?O.source==="form"?Y(S,O):!0:!1,ve=(S,O)=>!S||typeof S!="object"||Array.isArray(S)||O?.source!=="form"?!1:Y(S,O),te=(S={})=>Object.keys(S).some(O=>B.has(O)),ne=(S={},O)=>Object.entries(S).some(([F,oe])=>B.has(F)&&ve(oe,O)),ue=(S={})=>Object.keys(S).length>0&&Object.keys(S).every(O=>U.has(O)),de=(S={},O)=>{let F=S?.actions;return O?.source==="form"?!F||typeof F!="object"||Array.isArray(F)?!1:ne(F,O)?!0:te(F)?!1:ue(F):X(S,O)?!0:!F||typeof F!="object"||Array.isArray(F)?!1:Object.values(F).some(oe=>X(oe,O))},Q=(S,O={})=>{if(!O?.actions)return!1;let F=J(S);return!F||F.source==="choice"?!1:!de(O,F)},re=({preprocessPayload:S,onEvent:O}={})=>async(F,oe={})=>{let ie=e();if(Q(ie,oe))return O?.(F,oe);let z=await S?.(F,oe)??oe;if(Q(ie,z))return O?.(F,z);if(E(F,z),z?.actions){let Le=z?._event?{_event:z._event}:z?.event?{_event:z.event}:void 0,nt;z?.bypassChoice===!0?nt={bypassChoice:!0}:z?._interactionSource&&(nt={interactionSource:z._interactionSource}),nt?ie.handleActions(z.actions,Le,nt):ie.handleActions(z.actions,Le)}return O?.(F,z)},fe=S=>{let O=e(),F=hp(S),oe=F.some(z=>z.name==="handleLineActions");F.forEach(z=>{if(!qs[z.name]&&!r)throw new Error(`Unhandled pending effect "${z.name}".`)});let ie={engine:O,routeGraphics:t,ticker:n,autoTimer:a,skipTimer:c,nextLineConfigTimerState:u,trackRenderDispatch:R,getRenderDispatchCount:V,enqueuePersistenceWrite:C};for(let z of F){if(oe&&z.name==="render")continue;let Le=qs[z.name];if(Le){Le(ie,z.payload);continue}r(z,ie)}};return fe.handleRouteGraphicsEvent=E,fe.createRouteGraphicsEventHandler=re,fe},gp=mp;var yp=(e,t={})=>{let{resources:n={}}=t;return _r(e,n)};var Kh=Kr;export{sr as DEFAULT_VISUAL_LAYER,ct as RENDER_LAYER,_e as VISUAL_LAYER,gp as createEffectsHandler,Yf as createIndexedDbPersistence,Kh as default,Zn as formatDate,uc as resolveComputedVariables,yp as resolveLayoutReferences};
1
+ var na=Object.defineProperty;var ra=(e,t)=>{for(var n in t)na(e,n,{get:t[n],enumerable:!0})};var ao=Symbol.for("immer-nothing"),no=Symbol.for("immer-draftable"),he=Symbol.for("immer-state");function ge(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var ot=Object.getPrototypeOf;function se(e){return!!e&&!!e[he]}function ze(e){return e?co(e)||Array.isArray(e)||!!e[no]||!!e.constructor?.[no]||Ht(e)||Wt(e):!1}var oa=Object.prototype.constructor.toString();function co(e){if(!e||typeof e!="object")return!1;let t=ot(e);if(t===null)return!0;let n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return n===Object?!0:typeof n=="function"&&Function.toString.call(n)===oa}function jn(e){return se(e)||ge(15,e),e[he].base_}function Bt(e,t){qt(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function qt(e){let t=e[he];return t?t.type_:Array.isArray(e)?1:Ht(e)?2:Wt(e)?3:0}function $n(e,t){return qt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function lo(e,t,n){let r=qt(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function ia(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Ht(e){return e instanceof Map}function Wt(e){return e instanceof Set}function Ue(e){return e.copy_||e.base_}function Tn(e,t){if(Ht(e))return new Map(e);if(Wt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=co(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[he];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let s=o[i],l=r[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(r[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(ot(e),r)}else{let r=ot(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function Fn(e,t=!1){return Yt(e)||se(e)||!ze(e)||(qt(e)>1&&(e.set=e.add=e.clear=e.delete=sa),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>Fn(r,!0))),e}function sa(){ge(2)}function Yt(e){return Object.isFrozen(e)}var aa={};function qe(e){let t=aa[e];return t||ge(0,e),t}var bt;function uo(){return bt}function ca(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function ro(e,t){t&&(qe("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Dn(e){Nn(e),e.drafts_.forEach(la),e.drafts_=null}function Nn(e){e===bt&&(bt=e.parent_)}function oo(e){return bt=ca(bt,e)}function la(e){let t=e[he];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function io(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[he].modified_&&(Dn(t),ge(4)),ze(e)&&(e=Ut(t,e),t.parent_||zt(t,e)),t.patches_&&qe("Patches").generateReplacementPatches_(n[he].base_,e,t.patches_,t.inversePatches_)):e=Ut(t,n,[]),Dn(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==ao?e:void 0}function Ut(e,t,n){if(Yt(t))return t;let r=t[he];if(!r)return Bt(t,(o,i)=>so(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return zt(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let o=r.copy_,i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Bt(i,(l,a)=>so(e,r,o,l,a,n,s)),zt(e,o,!1),n&&e.patches_&&qe("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function so(e,t,n,r,o,i,s){if(se(o)){let l=i&&t&&t.type_!==3&&!$n(t.assigned_,r)?i.concat(r):void 0,a=Ut(e,o,l);if(lo(n,r,a),se(a))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(ze(o)&&!Yt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Ut(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&zt(e,o)}}function zt(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Fn(t,n)}function ua(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:uo(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=Mn;n&&(o=[r],i=It);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var Mn={get(e,t){if(t===he)return e;let n=Ue(e);if(!$n(n,t))return da(e,n,t);let r=n[t];return e.finalized_||!ze(r)?r:r===kn(e.base_,t)?(Ln(e),e.copy_[t]=Vn(r,e)):r},has(e,t){return t in Ue(e)},ownKeys(e){return Reflect.ownKeys(Ue(e))},set(e,t,n){let r=fo(Ue(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=kn(Ue(e),t),i=o?.[he];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(ia(n,o)&&(n!==void 0||$n(e.base_,t)))return!0;Ln(e),Pn(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return kn(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Ln(e),Pn(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=Ue(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ge(11)},getPrototypeOf(e){return ot(e.base_)},setPrototypeOf(){ge(12)}},It={};Bt(Mn,(e,t)=>{It[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});It.deleteProperty=function(e,t){return It.set.call(this,e,t,void 0)};It.set=function(e,t,n){return Mn.set.call(this,e[0],t,n,e[0])};function kn(e,t){let n=e[he];return(n?Ue(n):e)[t]}function da(e,t,n){let r=fo(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function fo(e,t){if(!(t in e))return;let n=ot(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=ot(n)}}function Pn(e){e.modified_||(e.modified_=!0,e.parent_&&Pn(e.parent_))}function Ln(e){e.copy_||(e.copy_=Tn(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var fa=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){let i=n;n=t;let s=this;return function(a=i,...c){return s.produce(a,u=>n.call(this,u,...c))}}typeof n!="function"&&ge(6),r!==void 0&&typeof r!="function"&&ge(7);let o;if(ze(t)){let i=oo(this),s=Vn(t,void 0),l=!0;try{o=n(s),l=!1}finally{l?Dn(i):Nn(i)}return ro(i,r),io(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===ao&&(o=void 0),this.autoFreeze_&&Fn(o,!0),r){let i=[],s=[];qe("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ge(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,a=>t(a,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){ze(e)||ge(8),se(e)&&(e=He(e));let t=oo(this),n=Vn(e,void 0);return n[he].isManual_=!0,Nn(t),n}finishDraft(e,t){let n=e&&e[he];(!n||!n.isManual_)&&ge(9);let{scope_:r}=n;return ro(r,t),io(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){let o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));let r=qe("Patches").applyPatches_;return se(e)?r(e,t):this.produce(e,o=>r(o,t))}};function Vn(e,t){let n=Ht(e)?qe("MapSet").proxyMap_(e,t):Wt(e)?qe("MapSet").proxySet_(e,t):ua(e,t);return(t?t.scope_:uo()).drafts_.push(n),n}function He(e){return se(e)||ge(10,e),po(e)}function po(e){if(!ze(e)||Yt(e))return e;let t=e[he],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Tn(e,t.scope_.immer_.useStrictShallowCopy_)}else n=Tn(e,!0);return Bt(n,(r,o)=>{lo(n,r,po(o))}),t&&(t.finalized_=!1),n}var me=new fa,Bn=me.produce,wp=me.produceWithPatches.bind(me),Ep=me.setAutoFreeze.bind(me),xp=me.setUseStrictShallowCopy.bind(me),vp=me.applyPatches.bind(me),Cp=me.createDraft.bind(me),Sp=me.finishDraft.bind(me);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},k={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},it={NOT:0};var v=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},pe=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Un=e=>{if(!e||e.trim()==="")throw new v("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new v(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${n}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let n of t)if(e.trim().endsWith(n))throw new v(`Incomplete comparison expression - missing right operand (got: '${e}')`)},ho=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,n]=e.split(" in ");if(!n||n.trim()==="")throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);let r=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of r){if(!o)throw new 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 mo=(e,t,n=!1)=>{if(t===null)return new pe(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new pe(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new pe(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new pe(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},go=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new pe(`Unknown function '${e}' (${n})`)};var pa=(e,t,n={})=>{let r={},o={};n&&typeof n=="object"&&(n.functions!==void 0||n.partials!==void 0?(r=n.functions||{},o=n.partials||{}):typeof n=="object"&&(r=n));let s=L(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},L=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return K(e.var,n,r);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return K(e.path,n,r);if(e.type===m.INTERPOLATION)return ma(e.parts,t,n,r);switch(e.type){case m.FUNCTION:return bo(e,t,n,r);case m.BINARY:return Io(e,t,n,r);case m.UNARY:return Ao(e,t,n,r);case m.CONDITIONAL:return ya(e,t,n,r);case m.LOOP:return Ea(e,t,n,r);case m.OBJECT:return va(e,t,n,r);case m.ARRAY:return Ca(e,t,n,r);case m.PARTIAL:return Sa(e,t,n,r);case m.PATH_REFERENCE:return _a(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},yo=new Map,ha=e=>{let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(i==="]"){if(r&&n){let s=n.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let l=s.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:s});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},K=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=yo.get(e);if(!r){let i=[],s="",l=0;for(let a=0;a<e.length;a++){let c=e[a];c==="["?(l++,s+=c):c==="]"?(l--,s+=c):c==="."&&l===0?s&&(i.push(s),s=""):s+=c}s&&i.push(s),r=[];for(let a of i){let c=ha(a.trim());r.push(...c)}yo.set(e,r)}let o=t;for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="property"&&s.value in n){o=n[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},ma=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},bo=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw go(e.name,o);let s=e.args.map(l=>L(l,t,n,r));return i(...s)},$e=(e,t,n,r)=>{if(e.var&&!e.type)return K(e.var,n,r);switch(e.type){case m.VARIABLE:return K(e.path,n,r);case m.LITERAL:return e.value;case m.BINARY:return Io(e,t,n,r);case m.UNARY:return Ao(e,t,n,r);case m.FUNCTION:return bo(e,t,n,r);default:return L(e,t,n,r)}},Io=(e,t,n,r)=>{if(e.op===k.AND||e.op===k.OR){let s=$e(e.left,t,n,r),l=$e(e.right,t,n,r);switch(e.op){case k.AND:return s&&l;case k.OR:return s||l}}let o=L(e.left,t,n,r),i=L(e.right,t,n,r);switch(e.op){case k.EQ:return o==i;case k.NEQ:return o!=i;case k.GT:return o>i;case k.LT:return o<i;case k.GTE:return o>=i;case k.LTE:return o<=i;case k.IN:return Array.isArray(i)?i.includes(o):!1;case k.ADD:if(typeof o!="number"||typeof i!="number")throw new pe(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case k.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new pe(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Ao=(e,t,n,r)=>{let o=e.op===it.NOT?$e(e.operand,t,n,r):L(e.operand,t,n,r);if(e.op===it.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},ga=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(K(o.path,n,r)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?L(a.parsedKey,t,n,r):a.key,u=a.value;if(u.type===m.LITERAL)l[c]=u.value;else if(u.type===m.VARIABLE)l[c]=K(u.path,n,r);else if(u.type===m.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===m.VARIABLE){let p=K(f.path,n,r);d.push(p!=null?String(p):"")}else{let p=L(f,t,n,r);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=L(u,t,n,r)}return l}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?L(a.parsedKey,t,n,r):a.key,u=a.value;if(u.type===m.LITERAL)l[c]=u.value;else if(u.type===m.VARIABLE)l[c]=K(u.path,n,r);else if(u.type===m.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===m.VARIABLE){let p=K(f.path,n,r);d.push(p!=null?String(p):"")}else{let p=L(f,t,n,r);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=L(u,t,n,r)}return l}}}return null},ya=(e,t,n,r)=>{let o=ga(e,t,n,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||$e(s,t,n,r))return L(e.bodies[i],t,n,r)}return wo},ba=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===m.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===m.VARIABLE){let o=n.conditions[0].path,i=n.bodies[0];if(o.startsWith(r+".")){let s=o.substring(r.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let a of i.properties)if(a.parsedKey)return null;let l=[];for(let a=0;a<t.length;a++){let c=t[a];if(c[s]){let u={};for(let d of i.properties){let f=d.key,p=d.value;if(p.type===m.LITERAL)u[f]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===r)u[f]=c;else if(h.startsWith(r+".")){let g=h.substring(r.length+1);u[f]=c[g]}else return null}else if(p.type===m.INTERPOLATION){let h=[],g=!0;for(let b of p.parts)if(typeof b=="string")h.push(b);else if(b.type===m.VARIABLE){let A=b.path;if(A===r)h.push(c!=null?String(c):"");else if(A.startsWith(r+".")){let w=A.substring(r.length+1),C=c[w];h.push(C!=null?String(C):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[f]=h.join("")}else return null}l.push(u)}}return l}}}return null},Ia=(e,t)=>{let n=e.body,r=e.itemVar,o=ba(e,t);if(o!==null)return o;if(n.type===m.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let l of n.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of n.properties){let a=l.key,c=l.value;if(c.type===m.LITERAL)i.push({key:a,type:"literal",value:c.value});else if(c.type===m.VARIABLE){let u=c.path;if(u===r)i.push({key:a,type:"item"});else if(u.startsWith(r+".")){let d=u.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:a,type:"prop",prop:d});else{s=!1;break}}else{s=!1;break}}else if(c.type===m.INTERPOLATION&&c.parts.length===1){let u=c.parts[0];if(u.type===m.VARIABLE){let d=u.path;if(d===r)i.push({key:a,type:"item_string"});else if(d.startsWith(r+".")){let f=d.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:a,type:"prop_string",prop:f});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let l=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let a=0;a<t.length;a++){let c=t[a];l[a]={id:c.id,title:c.title!=null?String(c.title):"",completed:c.completed}}else for(let a=0;a<t.length;a++){let c=t[a],u={};for(let d of i)if(d.type==="literal")u[d.key]=d.value;else if(d.type==="item")u[d.key]=c;else if(d.type==="prop")u[d.key]=c[d.prop];else if(d.type==="item_string")u[d.key]=c!=null?String(c):"";else if(d.type==="prop_string"){let f=c[d.prop];u[d.key]=f!=null?String(f):""}l[a]=u}return l}}return null},Aa=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let l=e.itemVar,a=e.indexVar;for(let c=0;c<o.length;c++){let u=o[c],d={},f={...r,[l]:u,...a&&{[a]:c}};f.__paths__||(f.__paths__=r.__paths__||{});let p=e.iterable.path||"";if(r&&r.__paths__&&p){let h=p.split("."),g=h[0];g in r.__paths__&&(p=r.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}f.__paths__={...f.__paths__,[l]:`${p}[${c}]`,...a&&{[a]:c}};for(let h of s.properties){let g=h.parsedKey?L(h.parsedKey,t,n,f):h.key,b=h.value;if(b.type===m.LITERAL)d[g]=b.value;else if(b.type===m.VARIABLE){let A=b.path;if(A===l)d[g]=u;else if(A===a)d[g]=c;else if(A.startsWith(l+".")){let w=A.substring(l.length+1);!w.includes(".")&&!w.includes("[")?d[g]=u[w]:d[g]=K(A,n,{...r,[l]:u,...a&&{[a]:c}})}else d[g]=K(A,n,{...r,[l]:u,...a&&{[a]:c}})}else if(b.type===m.INTERPOLATION){let A=[];for(let w of b.parts)if(typeof w=="string")A.push(w);else if(w.type===m.VARIABLE){let C=w.path,R;if(C===l)R=u;else if(C===a)R=c;else if(C.startsWith(l+".")){let V=C.substring(l.length+1);!V.includes(".")&&!V.includes("[")?R=u[V]:R=K(C,n,{...r,[l]:u,...a&&{[a]:c}})}else R=K(C,n,{...r,[l]:u,...a&&{[a]:c}});A.push(R!=null?String(R):"")}else{let C={...r,[l]:u,...a&&{[a]:c}},R=L(w,t,n,C);A.push(R!=null?String(R):"")}d[g]=A.join("")}else{let A={...r,[l]:u,...a&&{[a]:c}};d[g]=L(b,t,n,A)}}i.push(d)}return i}return null},wa=(e,t,n)=>{let r=e.body;if(r.type===m.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===m.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===m.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===m.OBJECT&&s.properties.length===2){let l=s.properties[0],a=s.properties[1];if(l.key==="id"&&l.value.type===m.VARIABLE&&l.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===m.CONDITIONAL){let c=[];for(let u=0;u<t.length;u++){let d=t[u];if(d.visible){let f={id:d.id};d.highlighted?(f.highlight=!0,f.message=`This item is highlighted: ${d.name}`):(f.highlight=!1,f.message=d.name),c.push(f)}}return c}}}}return null},Ea=(e,t,n,r)=>{let o=L(e.iterable,t,n,r);if(!Array.isArray(o)){let c,u=!1;if(e.iterable.type===m.FUNCTION){u=!0;let f=e.iterable.args.map(p=>p.type===m.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===m.VARIABLE?p.path:p.type===m.FUNCTION?`${p.name}(...)`:"?").join(", ");c=`${e.iterable.name}(${f})`}else c=e.iterable.path||"undefined";let d=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${c}`;throw mo(d,o,u)}if(!e.indexVar){let c=wa(e,o,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=Ia(e,o);if(c!==null)return c}let i=Aa(e,t,n,r,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(r&&r.__paths__&&l){let c=l.split("."),u=c[0];u in r.__paths__&&(l=r.__paths__[u],c.length>1&&(l+="."+c.slice(1).join(".")))}let a=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(c=>c.type===m.OBJECT&&c.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let c=0;c<o.length;c++){let u=e.indexVar?{...r,[e.itemVar]:o[c],[e.indexVar]:c}:{...r,[e.itemVar]:o[c]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${c}]`},e.indexVar&&(u.__paths__[e.indexVar]=c);let d=L(e.body,t,n,u);if(Array.isArray(d)&&d.length===1&&!a){let f=d[0];s.push(f===void 0?{}:f)}else s.push(d===void 0?{}:d)}return s},xa=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let l={},a={},c=!0;for(let u of s.properties){let d=u.parsedKey?L(u.parsedKey,t,n,r):u.key,f=u.value;if(f.type===m.LITERAL)a[d]=f.value;else if(f.type===m.VARIABLE)a[d]=K(f.path,n,r);else if(f.type===m.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=K(h.path,n,r);p.push(g!=null?String(g):"")}else{c=!1;break}if(!c)break;a[d]=p.join("")}else if(f.type===m.OBJECT&&f.properties.length<=5){let p={};for(let h of f.properties){let g=h.key,b=h.value;if(b.type===m.LITERAL)p[g]=b.value;else if(b.type===m.VARIABLE)p[g]=K(b.path,n,r);else if(b.type===m.INTERPOLATION){let A=[];for(let w of b.parts)if(typeof w=="string")A.push(w);else if(w.type===m.VARIABLE){let C=K(w.path,n,r);A.push(C!=null?String(C):"")}else{c=!1;break}if(!c)break;p[g]=A.join("")}else{c=!1;break}}if(!c)break;a[d]=p}else{c=!1;break}}if(c)return l[i]=a,l}}return null},va=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!$e(e.whenCondition,o,n,r))return;let i=xa(e,t,n,r);if(i!==null)return i;if(e.fast){let c={};for(let u of e.properties){let d=u.parsedKey?L(u.parsedKey,t,n,r):u.key,f=u.value;if(f.type===m.LITERAL)c[d]=f.value;else if(f.type===m.VARIABLE)c[d]=K(f.path,n,r);else if(f.type===m.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=K(h.path,n,r);p.push(g!=null?String(g):"")}else{let g=L(h,t,n,r);p.push(g!=null?String(g):"")}c[d]=p.join("")}else c[d]=L(f,t,n,r)}return c}let s={},l=null,a=!1;for(let c of e.properties)if(!c.key.startsWith("$if ")&&!c.key.match(/^\$if\s+\w+.*:?$/)&&!c.key.startsWith("$elif")&&!c.key.startsWith("$else")&&!c.key.startsWith("$for ")){a=!0;break}for(let c of e.properties)if(c.key.startsWith("$if ")||c.key.match(/^\$if\s+\w+.*:?$/)){let u=L(c.value,t,n,r);if(!a&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(c.key.startsWith("$for ")){if(e.properties.length===1)return L(c.value,t,n,r)}else{let u=c.value;if(u&&u.type===m.OBJECT&&u.properties){let d=u.properties.find(f=>f.key.startsWith("$for "));if(d){let f=L(d.value,t,n,r);f!==void 0&&(s[c.key]=f)}else{let f=L(c.value,t,n,r);f!==void 0&&(s[c.key]=f)}}else{let d=c.parsedKey?L(c.parsedKey,t,n,r):c.key,f=L(c.value,t,n,r);f!==void 0&&(s[d]=f)}}return s},wo={},Ca=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=L(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,n,r);s!==wo&&s!==void 0&&o.push(s)}return o},Sa=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},a=t.functions||t;if(s&&!$e(s,a,n,r))return;if(!l[o])throw new pe(`Partial '${o}' is not defined`);let c=r._partialStack||[];if(c.includes(o))throw new pe(`Circular partial reference detected: ${o}`);let u=l[o],d=n,f={...r,_partialStack:[...c,o]};if(r){d={...n};for(let p of Object.keys(r))p.startsWith("_")||(d[p]=r[p])}if(i){let p=L(i,t,n,r);d={...d,...p}}return L(u,t,d,f)},_a=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),s=i[0],l=i.slice(1);if(!r||!(s in r))throw new pe(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(s in r.__paths__))throw new pe(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=r.__paths__[s];if(typeof a=="number"){if(l.length>0)throw new pe(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return l.length>0&&(a+="."+l.join(".")),a};var zn=pa;var Ra=/\$\{([^}]*)\}/g,Oa=/#\{([^}]*)\}/g,xo=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=ka(o,t);return{isFunction:!0,type:m.FUNCTION,name:r,args:i}},ka=(e,t={})=>e.trim()?La(e).map(r=>$a(r.trim(),t)):[],La=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],a=s>0?e[s-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,n+=l):o&&l===i&&a!=="\\"?(o=!1,i="",n+=l):!o&&l==="("?(r++,n+=l):!o&&l===")"?(r--,n+=l):!o&&l===","&&r===0?(t.push(n),n=""):n+=l}return n&&t.push(n),t},$a=(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 n=xo(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:l,type:a}of o){let c=0;for(;c<r.length;){let u=We(r.substring(c),l);if(u===-1)break;let d=c+u;d>i&&(i=d,s={op:l,type:a}),c=d+l.length}}if(i!==-1)try{return Z(r,t)}catch{return{type:m.VARIABLE,path:r}}return{type:m.VARIABLE,path:r}},vo=/^\w+\(.*\)$/,Ta=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Da=e=>{if(!(!e||e.trim()===""||vo.test(e))&&Ta.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}"`)},Eo=e=>{let t=e.trim();if(vo.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}},At=(e,t={})=>{let n=e.trim();Da(n);let r=xo(n,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};if(n.includes("[")&&!/[\s+\-*/%|&?:]/.test(n)){let o=0;for(let i of n)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:n}},qn=(e,t={})=>{let n=e,r=[];(e.includes("\\${")||e.includes("\\#{"))&&(n=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),n=n.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),n=n.replace(/\\(\$\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${r.length}__`;return r.push(u),d}),n=n.replace(/\\(#\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${r.length}__`;return r.push(u),d}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...n.matchAll(Ra)],i=[...n.matchAll(Oa)],s=[...o.map(c=>({match:c,type:"variable"})),...i.map(c=>({match:c,type:"pathref"}))].sort((c,u)=>c.match.index-u.match.index);if(s.length===0){let c=n;for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);return{type:m.LITERAL,value:c}}if(s.length===1&&s[0].match[0]===n&&r.length===0){let{match:c,type:u}=s[0];try{return u==="variable"?At(c[1],t):Eo(c[1])}catch(d){if(d.message==="Invalid array index syntax")return{type:m.LITERAL,value:n};throw d}}let l=[],a=0;for(let{match:c,type:u}of s){let[d,f]=c,p=c.index;if(p>a){let h=n.substring(a,p);for(let g=0;g<r.length;g++)h=h.replace(`__ESCAPED_${g}__`,r[g]);h&&l.push(h)}try{let h;u==="variable"?h=At(f.trim(),t):h=Eo(f.trim()),l.push(h)}catch(h){if(h.message==="Invalid array index syntax")l.push(d);else throw h}a=p+d.length}if(a<n.length){let c=n.substring(a);for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);c&&l.push(c)}return{type:m.INTERPOLATION,parts:l}};var Yn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),_o=e=>Object.keys(e),ae=e=>e.join("."),Te=(e,t,n)=>{let r=_o(e).filter(o=>!t.has(o));if(r.length>0)throw new v(`Unexpected key '${r[0]}' in condition JSON at '${ae(n)}'`)},De=(e,t)=>typeof e=="string"?qn(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Pa(e,t):Va(e,t):{type:m.LITERAL,value:e},Na=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new v("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new v("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new v("Empty $each body not allowed");if(n.$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 ${r}`]:n}},Pa=(e,t)=>{let n=[],r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let a=Na(i),c=Object.keys(a);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let u=So(c[0],a[c[0]],t,!0);n.push(u),r=!0;continue}}catch(a){throw a instanceof v?a:new v(a.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let a=So(l[0],i[l[0]],t);n.push(a),r=!0;continue}}let s=De(i,t);n.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)&&(r=!0)}return{type:m.ARRAY,items:n,fast:!r}},Va=(e,t)=>{let n=[],r=!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 a=["$if","$elif","$else","$for"],c=[];for(let[A]of i)for(let w of a)if(A===w||A.startsWith(w+" ")||A.startsWith(w+"#")){c.push(w);break}if(c.length>0)throw new v(`Cannot use $partial with ${c.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:d,...f}=e,p={},h=!1;for(let[A,w]of Object.entries(f)){let C=A;(A.startsWith("\\$")||A.startsWith("$$"))&&(C=A.slice(1)),p[C]=w,h=!0}let g=null;if(h&&(g=De(p,t),g.type===m.OBJECT)){let A=!1;for(let w of g.properties)if(w.value.type===m.VARIABLE||w.value.type===m.INTERPOLATION||w.value.type===m.FUNCTION||w.value.type===m.CONDITIONAL||w.value.type===m.OBJECT&&!w.value.fast||w.value.type===m.ARRAY&&!w.value.fast){A=!0;break}A&&(g.fast=!1)}let b={type:m.PARTIAL,name:u,data:g};return d!==void 0&&(b.whenCondition=Co(d,t)),b}for(let[a,c]of i)if(a==="$when"){if(o!==null)throw new v("Multiple '$when' directives on the same object are not allowed");if(c==null)throw new v("Missing condition expression after '$when'");o=Co(c,t),r=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new v("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[a,c]=i[s];if(a==="$when"){s++;continue}if(a==="$each")throw new v("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let u=ja(i,s,t);n.push({key:a,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let u=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",d=u?`:${u}`:"";throw new v(`$for loops must be inside arrays - use '- $for${d} item in items:' instead of '$for${d} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(a.startsWith("$elif ")||a.startsWith("$else"))throw new v(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new v("Missing condition expression after '$if'");{let u=De(c,t);(u.type===m.FUNCTION||u.type===m.CONDITIONAL||u.type===m.PARTIAL||u.type===m.OBJECT&&!u.fast||u.type===m.ARRAY&&!u.fast)&&(r=!0);let d=qn(a,t),f={key:a,value:u};(d.type!==m.LITERAL||d.value!==a)&&(f.parsedKey=d),n.push(f),s++}}}let l={type:m.OBJECT,properties:n,fast:!r};return o&&(l.whenCondition=o),l},ja=(e,t,n={})=>{let r=[],o=[],i=t,[s,l]=e[i],a=null,c;if(s.startsWith("$if#")){let d=s.match(/^\$if#(\w+)\s+(.+)$/);if(d)a=d[1],c=d[2];else throw new v(`Invalid conditional syntax: ${s}`)}else c=s.substring(4),c.endsWith(":")&&(c=c.slice(0,-1).trim());Un(c);let u=Z(c,n);for(r.push(u),o.push(De(l,n)),i++;i<e.length;){let[d,f]=e[i],p=!1,h;if(a?d.startsWith(`$elif#${a} `)?(h=d.substring(`$elif#${a} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(d===`$else#${a}`||d===`$else#${a}:`)&&(p=!0,h=null):d.startsWith("$elif ")?(h=d.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(d==="$else"||d==="$else:")&&(p=!0,h=null),p){if(h===null)r.push(null);else{Un(h);let g=Z(h,n);r.push(g)}if(o.push(De(f,n)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:r,bodies:o,id:a},nextIndex:i}},Hn={eq:k.EQ,neq:k.NEQ,gt:k.GT,gte:k.GTE,lt:k.LT,lte:k.LTE,in:k.IN,add:k.ADD,sub:k.SUBTRACT},Wn={all:k.AND,any:k.OR},Fa=new Set(["var","literal","call","not",...Object.keys(Hn),...Object.keys(Wn)]),Ma=(e,t,n)=>{if(!Array.isArray(e))throw new v(`Condition JSON operator '${t}' at '${ae(n)}' requires an array`);if(e.length!==2)throw new v(`Condition JSON operator '${t}' at '${ae(n)}' requires exactly 2 operands`);return e},Ba=(e,t,n,r,o)=>{if(!Array.isArray(e))throw new v(`Condition JSON operator '${t}' at '${ae(o)}' requires an array`);if(e.length===0)throw new v(`Condition JSON operator '${t}' at '${ae(o)}' requires at least 1 condition`);return e.map((s,l)=>Ce(s,r,[...o,l])).reduce((s,l)=>({type:m.BINARY,op:n,left:s,right:l}))},Ua=(e,t,n)=>{let r,o;if(typeof e.call=="string")r=e.call,o=e.args??[],Te(e,new Set(["call","args"]),n);else if(Yn(e.call))r=e.call.name,o=e.call.args??[],Te(e,new Set(["call"]),n),Te(e.call,new Set(["name","args"]),[...n,"call"]);else throw new v(`Condition JSON call at '${ae(n)}' requires a function name`);if(typeof r!="string"||r.trim()==="")throw new v(`Condition JSON call at '${ae(n)}' requires a non-empty function name`);if(!/^\w+$/.test(r))throw new v(`Invalid condition JSON function name '${r}' at '${ae(n)}'`);if(!Array.isArray(o))throw new v(`Condition JSON call '${r}' at '${ae(n)}' requires args to be an array`);return{type:m.FUNCTION,name:r,args:o.map((i,s)=>Ce(i,t,[...n,"args",s]))}},Ce=(e,t={},n=["$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 '${ae(n)}' must be wrapped in an operator or { literal: [...] }`);if(!Yn(e))throw new v(`Invalid condition JSON value at '${ae(n)}'`);let r=_o(e);if(r.length===0)throw new v(`Condition JSON object at '${ae(n)}' must contain an operator`);let o=r.filter(s=>Fa.has(s));if(o.length===0)throw new v(`Unknown condition JSON operator '${r[0]}' at '${ae(n)}'`);if(o.length>1)throw new v(`Condition JSON at '${ae(n)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(Te(e,new Set(["var"]),n),typeof e.var!="string"||e.var.trim()==="")throw new v(`Condition JSON var at '${ae(n)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return Te(e,new Set(["literal"]),n),{type:m.LITERAL,value:e.literal};if(i==="call")return Ua(e,t,n);if(i==="not")return Te(e,new Set(["not"]),n),{type:m.UNARY,op:it.NOT,operand:Ce(e.not,t,[...n,"not"])};if(i in Wn)return Te(e,new Set([i]),n),Ba(e[i],i,Wn[i],t,[...n,i]);if(i in Hn){Te(e,new Set([i]),n);let s=Ma(e[i],i,[...n,i]);return{type:m.BINARY,op:Hn[i],left:Ce(s[0],t,[...n,i,0]),right:Ce(s[1],t,[...n,i,1])}}throw new v(`Unknown condition JSON operator '${i}' at '${ae(n)}'`)},Co=(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 Z(e,t)}return Yn(e)||Array.isArray(e)?Ce(e,t):{type:m.LITERAL,value:e}},Z=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let c=e.slice(1,-1),u=0,d=!0;for(let f=0;f<c.length;f++)if(c[f]==="("?u++:c[f]===")"&&u--,u<0){d=!1;break}if(d&&u===0)return Z(c,t)}let n=We(e,"||");if(n!==-1)return{type:m.BINARY,op:k.OR,left:Z(e.substring(0,n).trim(),t),right:Z(e.substring(n+2).trim(),t)};let r=We(e,"&&");if(r!==-1)return{type:m.BINARY,op:k.AND,left:Z(e.substring(0,r).trim(),t),right:Z(e.substring(r+2).trim(),t)};let o=[{op:">=",type:k.GTE},{op:"<=",type:k.LTE},{op:"==",type:k.EQ},{op:"!=",type:k.NEQ},{op:">",type:k.GT},{op:"<",type:k.LT},{op:" in ",type:k.IN}];for(let{op:c,type:u}of o){let d=We(e,c);if(d!==-1)return{type:m.BINARY,op:u,left:Z(e.substring(0,d).trim(),t),right:Z(e.substring(d+c.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:k.ADD},{op:" - ",type:k.SUBTRACT}];for(let{op:c,type:u}of l){let d=0;for(;d<e.length;){let f=We(e.substring(d),c);if(f===-1)break;let p=d+f;p>i&&(i=p,s={op:c,type:u}),d=p+c.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:Z(e.substring(0,i).trim(),t),right:Z(e.substring(i+s.op.length).trim(),t)};let a=[" * "," / "," % "];for(let c of a)if(We(e,c)!==-1)throw new v(`Arithmetic operations are not allowed in conditionals: "${c}"`);return e.startsWith("!")?{type:m.UNARY,op:it.NOT,operand:Z(e.substring(1).trim(),t)}:Ro(e,t)},We=(e,t)=>{let n=0,r=0;for(;r<=e.length-t.length;){if(e[r]==="(")n++;else if(e[r]===")")n--;else if(n===0&&e.substring(r,r+t.length)===t)return r;r++}return-1},za=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}},Ro=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return At(n,t);let o=za(n);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:m.VARIABLE,path:n};try{return At(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},qa=(e,t=!1)=>{let n=t?"$each":"$for";try{ho(e)}catch(r){if(r instanceof v&&t){let o=r.message.replace(/\$for/g,"$each");throw new v(o.replace("Parse Error: ",""))}throw r}},So=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let b=r?"$each":"$for";throw new v(`Invalid loop syntax (got: '${e.replace("$for",b)}')`)}let s=i[1],l=i[2].trim();qa(l,r);let a=l.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let b=r?"$each":"$for";throw new v(`Invalid loop syntax - missing 'in' keyword (got: '${b} ${l}')`)}let c=a[1].trim(),u=a[2].trim(),d,f=null;if(c.includes(",")){let b=c.split(",").map(A=>A.trim());if(b.length!==2)throw new v(`Invalid loop variables: ${c}. Expected format: "item" or "item, index"`);d=b[0],f=b[1]}else d=c;let p=["this","undefined","null","true","false"];if(p.includes(d))throw new v(`Reserved variable name: ${d}`);if(f&&p.includes(f))throw new v(`Reserved variable name: ${f}`);let h=Ro(u,n),g=De(t,n);return{type:m.LOOP,itemVar:d,indexVar:f,iterable:h,body:g,flatten:s!=="nested"}};var Ha=(e,t={})=>{let{functions:n={}}=t;return De(e,n)},Gt=Ha;var wt={};ra(wt,{now:()=>Wa});var Wa=()=>Date.now();var Ya=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...wt,...r},s=Gt(e,{functions:i}),l={};for(let[a,c]of Object.entries(o))l[a]=Gt(c,{functions:i});return zn(s,t,{functions:i,partials:l})},ce=Ya;var Ga=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Ka=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Ja=(e,t)=>{if(Ga(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new v("Empty condition expression");return Z(e,t)}return Ce(e,t)},Xa=(e,t={},n={})=>{let r=Ka(n),o={...wt,...r},i=Ja(e,o);return!!$e(i,{functions:o,partials:{}},t,{})},Gn=Xa;var vt=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return Gn(e,t)},Qa=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Do=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=a=>a,transformActionFirstArgument:l=a=>a}=n;for(let[a,c]of Object.entries(t))a!=="createInitialState"&&(a.startsWith("select")?o[a]=(...u)=>c(s(r),...u):i[a]=(...u)=>{let d;return r=Bn(r,p=>{let h=c(l(p),...u);d=h!==void 0&&!se(h)?h:void 0}),d});return{...o,...i}},Xt=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return Bn(r,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var Za=(e,t)=>{if(e.default!==void 0)return e.default;let n=["number","boolean","string","object"];if(!n.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${n.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},be=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),Et=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),No=e=>{let t=se(e)?He(e):e;return structuredClone(t)},ec=({characterId:e,resourceCharacter:t,variables:n={}}={})=>{if(!be(t,"nameVariableId"))return;let r=t.nameVariableId,o=n?.[r];if(typeof o!="string")throw new Error(`Character "${e}" nameVariableId "${r}" must resolve to a string variable`);return o},Qt=({characterId:e,character:t,characterName:n,characters:r={},variables:o={}}={})=>{let i=e?r?.[e]:void 0;if(t?.name!==void 0)return t.name;if(n!==void 0)return n;let s=ec({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},Ne=e=>be(e,"computed"),st=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([n])=>!Ne(t[n]))),tc=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),Kn=(e,t)=>{let n=e;for(let r of t){if(n==null)return;n=n[r]}return n},nc=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let n=tc(e),[r,o,...i]=n;if(r==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return Kn(s,i)}return r==="runtime"?Kn(t.runtime,n.slice(1)):Kn(t,n)},rc=(e,t,n)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(n!==void 0&&t.length!==n)throw new Error(`Computed expression operator "${e}" requires ${n} operand(s)`)},Oo=(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`)},oc=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},we=(e,t,n,r)=>(rc(e,t,r),t.map(o=>Jt(o,n))),ye=(e,t,n,r)=>{let o=we(e,t,n,r);return o.forEach(i=>oc(e,i)),o},ic=(e,t,n)=>{switch(e){case"var":return nc(t,n);case"add":{let[r,o]=ye(e,t,n,2);return r+o}case"sub":{let[r,o]=ye(e,t,n,2);return r-o}case"mul":{let[r,o]=ye(e,t,n,2);return r*o}case"div":{let[r,o]=ye(e,t,n,2);return r/o}case"mod":{let[r,o]=ye(e,t,n,2);return r%o}case"neg":{let[r]=ye(e,t,n,1);return-r}case"round":{let[r]=ye(e,t,n,1);return Math.round(r)}case"floor":{let[r]=ye(e,t,n,1);return Math.floor(r)}case"ceil":{let[r]=ye(e,t,n,1);return Math.ceil(r)}case"min":{let[r,o]=ye(e,t,n,2);return Math.min(r,o)}case"max":{let[r,o]=ye(e,t,n,2);return Math.max(r,o)}case"clamp":{let[r,o,i]=ye(e,t,n,3);return Math.min(i,Math.max(o,r))}case"eq":{let[r,o]=we(e,t,n,2);return r==o}case"neq":{let[r,o]=we(e,t,n,2);return r!=o}case"gt":{let[r,o]=we(e,t,n,2);return r>o}case"gte":{let[r,o]=we(e,t,n,2);return r>=o}case"lt":{let[r,o]=we(e,t,n,2);return r<o}case"lte":{let[r,o]=we(e,t,n,2);return r<=o}case"in":{let[r,o]=we(e,t,n,2);return Array.isArray(o)?o.includes(r):!1}case"and":case"all":return Oo(e,t),t.every(r=>!!Jt(r,n));case"or":case"any":return Oo(e,t),t.some(r=>!!Jt(r,n));case"not":{let[r]=we(e,t,n,1);return!r}case"length":{let[r]=we(e,t,n,1);return typeof r=="string"||Array.isArray(r)?r.length:Et(r)?Object.keys(r).length:0}case"includes":{let[r,o]=we(e,t,n,2);return typeof r=="string"||Array.isArray(r)?r.includes(o):!1}case"literal":return No(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},Jt=(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 n=Object.entries(e);if(n.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[r,o]]=n;return ic(r,o,t)},sc=(e,t={})=>vt(e,{variables:t.variables,runtime:t.runtime}),ac=(e,t)=>{if(!Et(e))throw new Error(`${t} must be an object`);let n=be(e,"expr"),r=be(e,"value");if(n===r)throw new Error(`${t} must contain exactly one of expr or value`)},Jn=(e,t,n)=>(ac(e,t),be(e,"value")?No(e.value):Jt(e.expr,n)),cc=(e,t={},n="unknown")=>{if(!Et(e))throw new Error(`Computed variable "${n}" computed must be an object`);let r=be(e,"expr"),o=be(e,"value");if(be(e,"branches")){if(r||o)throw new Error(`Computed variable "${n}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${n}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${n}" branches must not be empty`);if(!Et(e.default))throw new Error(`Computed variable "${n}" requires default`);for(let s=0;s<e.branches.length;s+=1){let l=e.branches[s];if(!Et(l))throw new Error(`Computed variable "${n}" branch ${s} must be an object`);if(!be(l,"when"))throw new Error(`Computed variable "${n}" branch ${s} requires when`);if(sc(l.when,t))return Jn(l,`Computed variable "${n}" branch ${s}`,t)}return Jn(e.default,`Computed variable "${n}" default`,t)}if(r===o)throw new Error(`Computed variable "${n}" must contain exactly one of expr, value, or branches`);return Jn(e,`Computed variable "${n}"`,t)},lc=(e,t,n)=>{switch(t){case"number":if(typeof n!="number"||!Number.isFinite(n))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(n)?"array":typeof n}`);return;case"boolean":if(typeof n!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(n)?"array":typeof n}`);return;case"string":if(typeof n!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(n)?"array":typeof n}`);return;case"object":if(n===null||typeof n!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof n}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},Ct=({variables:e={},runtime:t={},variableConfigs:n={},eager:r=!0}={})=>{let o=st(e,n),i=Object.entries(n).filter(([,d])=>Ne(d)).map(([d])=>d),s={},l=[],a=d=>{if(be(s,d))return s[d];let f=n[d];if(!Ne(f))return o[d];let p=l.indexOf(d);if(p>=0){let h=[...l.slice(p),d].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}l.push(d);try{let h=cc(f.computed,u,d);return lc(d,f.type,h),s[d]=h,h}finally{l.pop()}},c=new Proxy({},{get:(d,f)=>{if(typeof f=="string")return a(f)},has:(d,f)=>typeof f=="string"&&(be(o,f)||i.includes(f)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(d,f)=>{if(!(typeof f!="string"||!be(o,f)&&!i.includes(f)))return{enumerable:!0,configurable:!0}}}),u={variables:c,runtime:t,resolveVariable:a};return r?(i.forEach(d=>{a(d)}),{...o,...s}):c},uc=({variables:e={},runtime:t={},variableConfigs:n,projectData:r}={})=>Ct({variables:e,runtime:t,variableConfigs:n??r?.resources?.variables??{},eager:!0}),Zt=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{if(Ne(o))return;let i=Za(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},en=(e,t)=>{let n=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!n.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${n.join(", ")}`)},tn=(e,t,n)=>{let r={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=r[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${n}`);if(!Object.values(r).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${n}" of type "${e}". Valid operations: ${o.join(", ")}`)},dc=2,ko=12,Po=(e=dc)=>{if(!Number.isInteger(e)||e<0||e>ko)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${ko}.`);return e},fc=(e,t)=>{let n=10**t;return Math.round((e+Number.EPSILON)*n)/n},Kt=e=>typeof e=="number"&&Number.isFinite(e),Zn=(e,t,n,r,o={})=>{if(e==="number"){if(t==="set"&&!Kt(n))throw new Error(`Operation "set" requires value to be a number for variable "${r}".`);if(t==="multiply"&&!Kt(n))throw new Error(`Operation "multiply" requires value to be a number for variable "${r}".`);if(t==="divide"&&!Kt(n))throw new Error(`Operation "divide" requires value to be a number for variable "${r}".`);if(t==="divide"){if(n===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${r}".`);Po(o.roundTo)}}},nn=(e,t,n,r={})=>{let o=(s,l,a)=>{let c=s??l;if(!Kt(c))throw new Error(`Operation "${t}" requires ${a} to be a number.`);return c},i=s=>{let l=o(s,void 0,"value");if(l===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return l};switch(t){case"set":return n;case"multiply":return o(e,1,"current value")*o(n,void 0,"value");case"divide":return fc(o(e,0,"current value")/i(n),Po(r.roundTo));case"increment":return o(e,0,"current value")+o(n,1,"value");case"decrement":return o(e,0,"current value")-o(n,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var er=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let n=new Date(e),r=s=>String(s).padStart(2,"0"),o=String(n.getFullYear()),i={DD:r(n.getDate()),MM:r(n.getMonth()+1),MMM:Qa[n.getMonth()],YYYY:o,YY:o.slice(-2),HH:r(n.getHours()),mm:r(n.getMinutes()),ss:r(n.getSeconds())};return t.replace(/YYYY|MMM|YY|MM|DD|HH|mm|ss/g,s=>i[s])},pc=(e,t)=>{let n=i=>i?.ui,r=n(e),o=n(t);return JSON.stringify(r)===JSON.stringify(o)?null:r&&!o?{changeType:"delete",data:e}:o&&!r?{changeType:"add",data:t}:o&&r?{changeType:"update",data:t}:null},xt=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,hc=(e,t)=>{let n=e?.character?.sprite,r=t?.character?.sprite,o=xt(n)?n:void 0,i=xt(r)?r:void 0;return JSON.stringify(o)===JSON.stringify(i)?null:o&&!i?{changeType:"delete",data:o}:i&&!o?{changeType:"add",data:i}:i&&o?{changeType:"update",data:i}:null},Lo=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};e.transformId!==void 0&&(t.transformId=e.transformId);for(let n of["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"])e[n]!==void 0&&(t[n]=e[n]);for(let n of["animationName","animationSpeed","loop"])e[n]!==void 0&&(t[n]=e[n]);return t},$o=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},To=(e,t)=>t&&!e?{changeType:"add",data:t}:e&&!t?{changeType:"delete",data:e}:e&&t&&JSON.stringify(e)!==JSON.stringify(t)?{changeType:"update",data:t}:null,mc=(e,t)=>{let n={},r=To(Lo(e),Lo(t)),o=To($o(e),$o(t));return r&&(n.resource=r),o&&(n.color=o),Object.keys(n).length>0?n:null},tr=(e={},t={})=>{let n={},r=["sfx","voice"],o=a=>{let c=e[a],u=t[a];u&&!c?n[a]={changeType:"add",data:u}:c&&!u?r.includes(a)||(n[a]={changeType:"delete",data:c}):c&&u&&JSON.stringify(c)!==JSON.stringify(u)&&(n[a]={changeType:"update",data:u})},i=mc(e.background,t.background);i&&(n.background=i),o("screen"),o("bgm"),o("voice");let s=pc(e.dialogue,t.dialogue);s&&(n.dialogue=s);let l=hc(e.dialogue,t.dialogue);return l&&(n.dialogueSprite=l),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},nr=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,!t.background.resourceId&&!t.background.colorId&&delete t.background);let n=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};n("layout"),n("choice"),n("form"),n("screen"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let r=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(l=>{let a={...l};return delete a.animations,i(a)?a:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return r("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),r("visual",o=>o.resourceId||o.transformId),t},gc=(e,t)=>{if(!e||!t)return;let n=e;for(let r of t.split(".")){if(n==null||!(r in Object(n)))return;n=n[r]}return n},yc=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let n=e.slice(7),r=gc(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},bc={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"])},Vo=(e,t)=>{let n=e[e.length-1];return n?bc[n]?.has(t)===!0:!1},Xn=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Xn(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Vo(n,r)?o:Xn(o,t,[...n,r])])):yc(e,t),Qn=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Qn(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Vo(n,r)?o:Qn(o,t,[...n,r])])):typeof e=="string"?ce(e,t):e,rr=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let n=Xn(e,t._event);return Qn(n,t)};var W=e=>structuredClone(se(e)?He(e):e),P=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),jo=e=>e?.animations?.playback?.continuity==="persistent",N=(e,t)=>P(e??{},t)&&e[t]!==void 0,St=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:W(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Ic=e=>N(e,"opacity")||N(e,"blur"),qo=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Ho=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],or=["animationName","animationSpeed","loop"],Ac=e=>qo.some(t=>N(e,t)),Wo=e=>e?.text&&N(e.text,"content")&&N(e.text,"textStyleId"),Yo=e=>N(e,"text"),wc=(e,t)=>e.resourceId?!0:Wo(e)?!t?.text:!1,Ec=(e,t)=>{let n={...W(e),...t};return t.text&&e.text&&(n.text={...W(e.text),...W(t.text)}),n},xc=(e,t)=>{if(Yo(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!Wo(e)&&!t?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},Fo=e=>Ho.some(t=>N(e,t)),Mo=e=>or.some(t=>N(e,t)),vc=(e,t,{hasAuthoredTransformId:n=!1}={})=>{if(!t)return e;for(let r of Ho)!n&&!N(e,r)&&N(t,r)&&(e[r]=t[r]),P(e,r)&&e[r]===void 0&&delete e[r];return e},Go=(e,t,n)=>{let r=e[n];return r?.id===t?.id?r:e.find(o=>o.id===t?.id)},Cc=(e,t)=>{if(!t)return e;for(let n of qo)!N(e,n)&&N(t,n)&&(e[n]=t[n]),P(e,n)&&e[n]===void 0&&delete e[n];return e},Sc=(e,t)=>(t&&(!N(e,"opacity")&&N(t,"opacity")&&(e.opacity=t.opacity),!N(e,"blur")&&N(t,"blur")&&(e.blur=W(t.blur)),P(e,"opacity")&&e.opacity===void 0&&delete e.opacity,P(e,"blur")&&e.blur===void 0&&delete e.blur),e),Ko=(e,t,n=[],{hasPatchFn:r=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,l)=>{let a=Go(n,s,l),c=t(s,a),u=Ic(s),d=Ac(s),f=r(s),p=P(s,"animations"),h=W(s);return!c&&(u||d||f)&&a&&(h=o?o(a,h):{...W(a),...h},p||delete h.animations),Sc(Cc(h,a),a)}).filter(s=>t(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},_c=e=>{if(e){if(e.character&&P(e.character,"name"))return e.character.name;if(P(e,"characterName"))return e.characterName}},Jo=e=>!!e?.character&&P(e.character,"sprite"),Rc=e=>{let t={},n=!1,r=_c(e);return r!==void 0&&(t.name=r,n=!0),Jo(e)&&(t.sprite=W(e.character.sprite),n=!0),n?t:void 0},Bo=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Uo=({dialogueState:e,dialogueAction:t,persistCharacter:n})=>P(t,"persistSprite")?t.persistSprite===!0:P(e,"persistSprite")?e.persistSprite===!0:n&&!P(t,"characterId"),zo=({previousCharacter:e,characterFields:t,hasCharacterId:n,persistCharacter:r,persistSprite:o,hasExplicitPersistSprite:i,isAppendingAdvDialogueContent:s})=>{let l={},a=e??{},c=t??{},u=s&&!n,d=u&&!i;return P(c,"name")?l.name=c.name:(r&&!n||u)&&P(a,"name")&&(l.name=W(a.name)),P(c,"sprite")?l.sprite=W(c.sprite):(o||d)&&P(a,"sprite")&&(l.sprite=W(a.sprite)),Object.keys(l).length>0?l:void 0},Oc=({dialogueState:e,content:t,append:n=!1})=>{if(!n||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let r=Array.isArray(e.content)?e.content:[];r.length>0?e.initialRevealedContent=r.map(o=>W(o)):delete e.initialRevealedContent,e.content=[...r,...t]},kc=()=>({}),Lc=(e,t)=>{if(!t.screen)return;let n=N(t.screen,"opacity"),r=N(t.screen,"blur"),o=P(t.screen,"animations");if(!n&&!r){o||delete e.screen;return}let i=e.screen,s={};if(n?s.opacity=t.screen.opacity:N(i,"opacity")&&(s.opacity=i.opacity),r?s.blur=W(t.screen.blur):N(i,"blur")&&(s.blur=W(i.blur)),P(s,"opacity")&&s.opacity===void 0&&delete s.opacity,P(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},$c=(e,t)=>{if(t.background){let n=N(t.background,"resourceId"),r=N(t.background,"colorId"),o=N(t.background,"opacity"),i=N(t.background,"blur"),s=N(t.background,"transformId"),l=Fo(t.background),a=Mo(t.background),{animationsOnly:c,state:u}=St(t.background,p=>N(p,"resourceId")||N(p,"colorId")||N(p,"opacity")||N(p,"blur")||N(p,"transformId")||Fo(p)||Mo(p));if(c){e.background=e.background?{...W(e.background),...u}:u;return}if(!n&&!r&&!o&&!i&&!s&&!l&&!a){delete e.background;return}let d=e.background,f=W(t.background);if(!n&&d?.resourceId){f.resourceId=d.resourceId,!P(f,"transformId")&&d.transformId&&(f.transformId=d.transformId);for(let p of or)!N(f,p)&&N(d,p)&&(f[p]=d[p])}vc(f,d,{hasAuthoredTransformId:s}),!r&&d?.colorId&&(f.colorId=d.colorId),!o&&N(d,"opacity")&&(f.opacity=d.opacity),!i&&N(d,"blur")&&(f.blur=W(d.blur)),P(f,"resourceId")&&f.resourceId===void 0&&delete f.resourceId,P(f,"colorId")&&f.colorId===void 0&&delete f.colorId,P(f,"animations")&&f.animations===void 0&&delete f.animations,P(f,"transformId")&&f.transformId===void 0&&delete f.transformId,P(f,"opacity")&&f.opacity===void 0&&delete f.opacity,P(f,"blur")&&f.blur===void 0&&delete f.blur;for(let p of or)P(f,p)&&f[p]===void 0&&delete f[p];if(!f.resourceId&&!f.colorId){delete e.background;return}d?.resourceId===f.resourceId&&d?.transformId===f.transformId&&!P(f,"animations")&&jo(d)&&(f.animations=W(d.animations)),e.background=f}else e.background?.animations&&!jo(e.background)&&(e.background.animations={})},Tc=(e,t)=>{if(!t.dialogue){if(e.dialogue&&(Bo(e.dialogue),e.dialogue.mode==="adv")){e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,delete e.dialogue.textSpeed;let u=e.dialogue.persistCharacter===!0,d=Uo({dialogueState:e.dialogue,dialogueAction:{},persistCharacter:u});u||delete e.dialogue.characterId,e.dialogue.character=zo({previousCharacter:e.dialogue.character,characterFields:{},hasCharacterId:!1,persistCharacter:u,persistSprite:d,hasExplicitPersistSprite:!1,isAppendingAdvDialogueContent:!1}),e.dialogue.character||delete e.dialogue.character}return}e.dialogue||(e.dialogue={});let n=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:u,state:d}=St(t.dialogue.ui,f=>!!f.resourceId);u?e.dialogue.ui={...e.dialogue.ui,...d}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let r=t.dialogue.append===!0&&n!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&Oc({dialogueState:e.dialogue,content:t.dialogue.content,append:r}),P(t.dialogue,"textSpeed")?e.dialogue.textSpeed=t.dialogue.textSpeed:delete e.dialogue.textSpeed;let o=P(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=Uo({dialogueState:e.dialogue,dialogueAction:t.dialogue,persistCharacter:o});P(t.dialogue,"persistSprite")&&(e.dialogue.persistSprite=i);let s=P(t.dialogue,"characterId"),l=Rc(t.dialogue),a=Jo(t.dialogue);s?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!r&&delete e.dialogue.characterId;let c=zo({previousCharacter:e.dialogue.character,characterFields:l,hasCharacterId:s,persistCharacter:o,persistSprite:i,hasExplicitPersistSprite:P(t.dialogue,"persistSprite"),isAppendingAdvDialogueContent:r});if(c?e.dialogue.character=c:delete e.dialogue.character,a||Bo(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 u={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.textSpeed!==void 0&&(u.textSpeed=e.dialogue.textSpeed),e.dialogue.character&&(u.character=W(e.dialogue.character)),e.dialogue.lines.push(u)}},Dc=(e,t)=>{if(t.sfx){let n=Array.isArray(t.sfx.items)&&t.sfx.items.length>0,r=Array.isArray(t.sfx.channels)&&t.sfx.channels.length>0;if(!n&&!r){delete e.sfx;return}e.sfx=W(t.sfx)}else e.sfx&&delete e.sfx},Nc=(e,t)=>{if(t.bgm){let n=Array.isArray(t.bgm.sounds);if(!t.bgm.resourceId&&!n||n&&t.bgm.sounds.length===0){e.bgm=void 0;return}e.bgm=W(t.bgm),t.bgm.resourceId&&(e.bgm.loop=t.bgm.loop??!0)}},Pc=(e,t)=>{if(t.visual){let n=e.visual?.items||[];t.visual.items?.forEach((i,s)=>{xc(i,Go(n,i,s))});let{hasValidItems:r,processedItems:o}=Ko(t.visual.items,wc,n,{hasPatchFn:Yo,mergeItemFn:Ec});r?e.visual={items:o}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},Vc=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:n,processedItems:r}=Ko(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);n?e.character={items:r}:delete e.character},jc=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Fc=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=St(t.layout,o=>!!o.resourceId);if(n){e.layout=r;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},Mc=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=St(t.choice,o=>!!o.resourceId);if(n){e.choice={...e.choice,...r};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},Bc=(e,t)=>{if(t.form){let{animationsOnly:n,state:r}=St(t.form,o=>!!o.resourceId);if(n){e.form={...e.form,...r};return}if(!t.form.resourceId){delete e.form;return}e.form=W(t.form)}else e.form&&delete e.form},Uc=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},zc=(e,t)=>{if(t.voice){let n=Array.isArray(t.voice.sounds);if(!t.voice.resourceId&&!n||n&&t.voice.sounds.length===0){delete e.voice;return}e.voice=W(t.voice)}else e.voice&&delete e.voice},qc=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},Ye=e=>Xt(kc,[qc,Lc,$c,Dc,Nc,Pc,Tc,Vc,jc,Fc,Mc,Bc,Uc,zc])(e);var at=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=ce(e,t);return n&&typeof n=="object"?e:n};var Hc=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},autoForwardSpeed:{source:"global.autoForwardSpeed"},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"}}),Ge=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,autoForwardSpeed:1,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),_t=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Xo=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",autoForwardSpeed:"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"}),ir=Object.freeze(["dialogueTextSpeed","autoForwardDelay","autoForwardSpeed","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),sr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Wc=(e,t)=>{if(t.startsWith("global.")){let n=t.slice(7);return e?.global?.[n]}if(t.startsWith("context.runtime.")){let n=t.slice(16),r=Array.isArray(e?.contexts)?e.contexts:[];return r[r.length-1]?.runtime?.[n]}},Ke=e=>Object.fromEntries(Object.entries(Hc).map(([t,n])=>{let r=Wc(e,n.source),o=r!==void 0?r:Ge[t]??_t[t];return[t,o]})),Pe=(e,t)=>Ke(e)[t],Qo=(e={})=>Object.fromEntries(ir.map(t=>[t,e[t]??Ge[t]]));var ct=Object.freeze({VISUAL_BEHIND_BACKGROUND:10,BACKGROUND:20,VISUAL_BEHIND_CHARACTER:30,CHARACTER:40,VISUAL_BEHIND_DIALOGUE:50,DIALOGUE:60,VISUAL_BEHIND_CHOICE:70,CHOICE:80,VISUAL_FOREGROUND:90}),_e=Object.freeze({BEHIND_BACKGROUND:ct.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:ct.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:ct.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:ct.VISUAL_BEHIND_CHOICE,FOREGROUND:ct.VISUAL_FOREGROUND}),ar=_e.BEHIND_DIALOGUE,cr=Object.freeze(Object.values(_e).sort((e,t)=>e-t));var Re={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:er},Yc=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,Gc=(e,t)=>{let n=String(t||"").trim();if(!n)return;let r=n.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of r){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},an=(e,t,n)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),l=Yc.exec(s);if(l){let[,a,c,u]=l,d=Gc(t,u);if(!Array.isArray(d))continue;let f=Array.isArray(i[s])?i[s]:[];d.forEach((p,h)=>{let g={...t,[a]:p};c&&(g[c]=h),f.forEach(b=>{let A=an(b,g,n),w=ce(A,g,n);Array.isArray(w)?o.push(...w):o.push(w)})});continue}}o.push(an(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=an(i,t,n)}),r},Cr=({animationType:e,animationId:t,animationPath:n})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${n}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},Kc=({id:e,targetId:t,animation:n,playback:r,animationPath:o="animation"})=>{let i=structuredClone(n);if(Cr({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,r!==void 0){let s=Zc(r,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},Jc=(e,{animationId:t="animation",animationPath:n="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Cr({animationType:e.type,animationId:t,animationPath:n}),e.type},Xc=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Qc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Zc=(e,t="animation.playback")=>{if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`[${t}] playback must be an object.`);if(e.continuity!==void 0&&e.continuity!=="render"&&e.continuity!=="persistent")throw new Error(`[${t}] playback.continuity must be "render" or "persistent".`);if(e.speed!==void 0&&(typeof e.speed!="number"||!Number.isFinite(e.speed)||e.speed<=0))throw new Error(`[${t}] playback.speed must be a finite number greater than 0.`);let n={};return e.continuity!==void 0&&(n.continuity=e.continuity),e.speed!==void 0&&e.speed!==1&&(n.speed=e.speed),Object.keys(n).length>0?n:void 0},el=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},Je=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),ui=e=>e?.playback?.continuity==="persistent",gr=e=>Array.isArray(e)?e.map(gr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,n)=>(t[n]=gr(e[n]),t),{}),ln=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return t.playback&&(delete t.playback.continuity,t.playback.speed===1&&delete t.playback.speed,Object.keys(t.playback).length===0&&delete t.playback),JSON.stringify(gr(t))},di=(e=[])=>e.filter(t=>ui(t)).map(t=>structuredClone(t)),fi=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,n)=>{let r=typeof n?.duration=="number"&&Number.isFinite(n.duration)?n.duration:0;return t+r},0):0,lr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,n)=>Math.max(t,fi(n)),0),pi=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(lr(e.tween),lr(e.prev?.tween),lr(e.next?.tween),fi(e.mask?.progress))/el(e),Zo=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let n=new Set(t.map(ln).filter(Boolean));return e.some(r=>{if(!ui(r))return!1;let o=ln(r);return o?n.has(o):!1})},Ee=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:n,activePersistentAnimations:r,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||n?!1:i&&!t||Zo({animationInstances:e,activePersistentAnimations:r})?!0:i?!1:Zo({animationInstances:e,activePersistentAnimations:o}),tl=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),nl=(e,t)=>{if(tl(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},rl=({resources:e,animationId:t,playback:n,instanceId:r,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?Kc({id:r,targetId:o,animation:s,playback:n,animationPath:i}):null},ol=(e,{defaultTargetId:t,defaultId:n,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Cr({animationType:o.type,animationId:o.id??n,animationPath:r}),o.id??=n,o.targetId??=t,o},Sr=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r,animationPathPrefix:o=r})=>{t.forEach((i,s)=>{e.push(ol(i,{defaultTargetId:n,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},yr=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(n=>n===null||typeof n!="object"||Array.isArray(n)))throw new Error(`${t} must be an array of objects`);return e},il=({content:e,path:t,variables:n})=>yr(e,t).reduce((r,o)=>{let i=at(o.text,{variables:n});return r+`${i??""}`.length},0),ei=(e=[])=>{let t=new Map;for(let n of e)n?.id&&t.set(n.id,(t.get(n.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,n])=>n>1).map(([n])=>n))},rn=(e,t=0,n=new Set)=>{if(!n.has(e?.id))return`character-container-${e.id}`;let r=e?.sprites?.map(({resourceId:o})=>o)||[];return r.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${r.join("-")}`},on=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return n},sl=(e,t={})=>{if(!t?.transformId)return;let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for background`);return n},al=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],cl=(e={})=>al.some(t=>Je(e,t)),hi=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.spritesheets?.[t])return"spritesheet-animation";if(e.layouts?.[t])return"container"}},cn=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},ll=(e={})=>e.textStyles||{},ul=(e={})=>e.images||{},dl=.5,fl=(e={},t,n)=>{if(t){if(!e.animations?.[t])throw new Error(`Animation '${t}' not found in spritesheet resource '${n}'`);return t}return Object.keys(e.animations??{})[0]},mi=({id:e,resourceId:t,spritesheet:n,animationName:r,animationSpeed:o,loop:i,transform:s={}}={})=>{let l=fl(n,r,t),a=l?n.animations?.[l]:void 0;if(!a){console.warn(`Spritesheet animation not found: ${t}`);return}return{id:e,type:"spritesheet-animation",...s,width:n.width,height:n.height,src:n.fileId,atlas:n.jsonData,playback:{frames:a.frames,animationSpeed:o??a.animationSpeed??dl,loop:i??a.loop??!0}}},gi=({id:e,item:t,resources:n={}}={})=>{let r=n.images?.[t.resourceId];if(r)return{type:"sprite",id:e,src:r.fileId,width:r.width,height:r.height,x:0,y:0};let o=n.spritesheets?.[t.resourceId];if(o)return mi({id:e,resourceId:t.resourceId,spritesheet:o,animationName:t.animationName,animationSpeed:t.animationSpeed,loop:t.loop,transform:{x:0,y:0}});console.warn(`Character sprite resource not found: ${t.resourceId}`)},pl=(e={})=>e.colors||{},hl=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,kt=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,ut=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},ur=(e,t,n)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);return e},dr=(e,t,n,r,{minimum:o}={})=>{if(e===void 0)return r;if(typeof e!="number"||!Number.isFinite(e)||o!==void 0&&e<o){let i=o===void 0?"a finite number":`a finite number >= ${o}`;throw new Error(`shadow.${t} for text style "${n}" must be ${i}`)}return e},fn=(e,t)=>{if(typeof e!="string"||!hl.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(n=>n.repeat(2)).join("")}`:e},ti=(e,t,n)=>{let r=fn(e,n);if(t===1)return r;let o=Number.parseInt(r.slice(1,3),16),i=Number.parseInt(r.slice(3,5),16),s=Number.parseInt(r.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},ml=(e={},t)=>{let n=ll(e)?.[t];if(!n)throw new Error(`Text style "${t}" not found`);let o=(Array.isArray(n.fontId)?n.fontId:[n.fontId]).map(a=>{let c=e.fonts?.[a];if(!c)throw new Error(`Font "${a}" not found for text style "${t}"`);return c.fileId}),i=e.colors?.[n.colorId];if(!i)throw new Error(`Color "${n.colorId}" not found for text style "${t}"`);let s=ur(n.colorAlpha,"colorAlpha",t),l={fontFamily:Array.isArray(n.fontId)?o.join(", "):o[0],fontSize:n.fontSize??16,fontWeight:n.fontWeight??"400",fontStyle:n.fontStyle??"normal",lineHeight:n.lineHeight??1.2,fill:ti(i.hex,s,`Color "${n.colorId}" for text style "${t}"`)};if(n.align!==void 0&&(l.align=n.align),n.wordWrap!==void 0&&(l.wordWrap=n.wordWrap),n.breakWords!==void 0&&(l.breakWords=n.breakWords),n.wordWrapWidth!==void 0&&(l.wordWrapWidth=n.wordWrapWidth),n.strokeColorId){let a=e.colors?.[n.strokeColorId];if(!a)throw new Error(`Stroke color "${n.strokeColorId}" not found for text style "${t}"`);let c=ur(n.strokeAlpha,"strokeAlpha",t);l.strokeColor=ti(a.hex,c,`Stroke color "${n.strokeColorId}" for text style "${t}"`)}else if(n.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);if(n.strokeWidth!==void 0&&(l.strokeWidth=n.strokeWidth),n.shadow!==void 0){let a=e.colors?.[n.shadow.colorId];if(!a)throw new Error(`Shadow color "${n.shadow.colorId}" not found for text style "${t}"`);l.shadow={color:fn(a.hex,`Shadow color "${n.shadow.colorId}" for text style "${t}"`),alpha:ur(n.shadow.alpha,"shadow.alpha",t),blur:dr(n.shadow.blur,"blur",t,0,{minimum:0}),offsetX:dr(n.shadow.offsetX,"offsetX",t,2),offsetY:dr(n.shadow.offsetY,"offsetY",t,2)}}return l},br=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>br(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${n}". Use textStyleId instead`);let r={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(r[o]=br(i,t,kt(n,o)));return e.textStyleId!==void 0&&(ut(e.textStyleId,n,"textStyleId"),r.textStyle=ml(t,e.textStyleId)),r},_r=(e={},t)=>{let n=pl(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return fn(n.hex,`Color "${t}"`)},yi=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",fr=(e,t,n)=>{let r=e?.[t];if(!(!r||typeof r!="object"||Array.isArray(r))&&Object.prototype.hasOwnProperty.call(r,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${n}". Use ${yi(`${t}.fill`)} instead`)},gl=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Lt(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;let r={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(r[o]=Lt(i,t,kt(n,o)));return e.colorId!==void 0&&(ut(e.colorId,n,"colorId"),r.fill=_r(t,e.colorId)),r},Lt=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Lt(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${n}". Use ${yi("fill")} instead`);fr(e,"hover",n),fr(e,"click",n),fr(e,"rightClick",n)}let r={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){r[o]=gl(i,t,kt(n,o));continue}r[o]=Lt(i,t,kt(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(ut(e.colorId,n,"colorId"),r.fill=_r(t,e.colorId)),r},pr=(e={},t)=>{let n=ul(e)?.[t];return n||null},bi=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",ni=(e,t,n,r)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,r))throw new Error(`Inline ${t}.${r} is not allowed in sprite layout elements at "${n}". Use ${bi(`${t}.${r}`)} instead`)},ri=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},Ir=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Ir(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${n}". Use ${bi(o)} instead`);ni(e,"hover",n,"src"),ni(e,"click",n,"src")}let r={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(r[o]=Ir(i,t,kt(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){ut(e.imageId,n,"imageId");let o=pr(t,e.imageId),i=o?.fileId??e.imageId;r.src=i,r.width===void 0&&o?.width!==void 0&&(r.width=o.width),r.height===void 0&&o?.height!==void 0&&(r.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(ut(e.hoverImageId,n,"hoverImageId"),ri(r,"hover",pr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(ut(e.clickImageId,n,"clickImageId"),ri(r,"click",pr(t,e.clickImageId)?.fileId??e.clickImageId)),r},Rr=(e,t={},n="root")=>Ir(Lt(br(e,t,n),t,n),t,n),Oe=Rr,Qe=(e=[])=>e.find(t=>t.id==="story"),yl="#000000",Ar="bg-cg-background-color",bl=({resources:e={},background:t={},screen:n})=>t?.colorId===void 0?fn(n?.backgroundColor??yl,"screen.backgroundColor"):_r(e,t.colorId),Ii=(e={})=>{if(Je(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Il=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},oi=(e={},{includeDefaultAlpha:t=!1}={})=>{let n=Ii(e),r=Il(e),o={};return(t||n!==void 0)&&(o.alpha=n??1),r&&(o.blur=r),o},Al=(e={})=>{if(Je(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},wl=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Ai=(e={})=>{let t=Al(e),n=wl(e),r={};return t!==void 0&&(r.alpha=t),n&&(r.blur=n),r},Rt=(e={})=>Ai(e),Ve=(e={},t={})=>{let n={x:t.x??e.x,y:t.y??e.y,anchorX:t.anchorX??e.anchorX,anchorY:t.anchorY??e.anchorY,rotation:t.rotation??e.rotation,scaleX:t.scaleX??e.scaleX,scaleY:t.scaleY??e.scaleY},r=t.originX??e.originX,o=t.originY??e.originY;return r!==void 0&&(n.originX=r),o!==void 0&&(n.originY=o),n},El=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],Or=(e={})=>e.text&&Je(e.text,"content")&&Je(e.text,"textStyleId"),ii=(e={})=>{if(e.resourceId)return e.resourceId;if(Or(e))return"text"},xl=e=>{if(e.text){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!Or(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let t of El)if(Je(e.text,t))throw new Error(`Visual item "${e.id}" text.${t} is reserved for the visual item`)}},vl=({resources:e,background:t,screen:n={width:1920,height:1080},includeOpacity:r=!1})=>{let o={id:Ar,type:"rect",x:0,y:0,width:n?.width??1920,height:n?.height??1080,fill:bl({resources:e,background:t,screen:n})};if(r){let i=Ii(t);i!==void 0&&(o.alpha=i)}return o},Cl=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.spritesheets?.[t]||e.layouts?.[t]):!1,si=({resources:e={},resourceId:t,colorId:n})=>{let r=hi(e,t);return t&&(r||n===void 0)?{resourceId:t,targetId:cn({resourceId:t,kind:r})}:n!==void 0?{resourceId:Ar,targetId:Ar}:{resourceId:void 0,targetId:void 0}},wi=100,Xe=wi,Sl="channel:bgm",_l="channel:voice",Rl="default",Ol=e=>String(e).replaceAll("%","%25").replaceAll(":","%3A"),Ot=(...e)=>e.map(Ol).join(":"),un=(e,t,n)=>{let r=new Set;e.forEach(({id:o})=>{if(r.has(o)){let i=n?` in ${n}`:"";throw new Error(`Duplicate ${t} id "${o}"${i}.`)}r.add(o)})},kl=(e,t)=>e*t/wi,Ei=(e={},t)=>e?.[t]??Ge[t],kr=(e={},t,n=Xe)=>kl(n,Ei(e,t)),Lr=({id:e,volume:t,muted:n,pan:r,children:o,runtime:i})=>({id:e,type:"audio-channel",volume:t,muted:!!i?.muteAll||(n??!1),pan:r??0,children:o}),sn=(e,t,n,r)=>e[n]!==void 0?e[n]:t[n]!==void 0?t[n]:r,Ll=["muted","pan","playbackRate","startAt","endAt"],$r=({id:e,sound:t,resource:n,defaultLoop:r=!1})=>{let o={id:e,type:"sound",src:n.fileId,loop:sn(t,n,"loop",r),volume:sn(t,n,"volume",Xe),startDelayMs:sn(t,n,"startDelayMs",0)};Ll.forEach(s=>{let l=sn(t,n,s,void 0);l!==void 0&&(o[s]=l)});let i=o.startAt??0;if(o.endAt!==void 0&&o.endAt!==null&&o.endAt<i)throw new Error(`Sound "${e}" endAt (${o.endAt}) must be greater than or equal to startAt (${i}).`);return o},xe=({variables:e,runtime:t,saveSlots:n=[],dialogueState:r,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,confirmDialog:d,form:f,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:b,skipTransitionsAndAnimations:A}={})=>{let w={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,autoForwardSpeed:t?.autoForwardSpeed??1,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??l??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},C=Pl({dialogueState:r,includeInactiveAdvDialogue:o,characters:h,variables:e,runtime:w}),R={variables:e,runtime:w,saveSlots:n,isChoiceVisible:a,isFormVisible:c,canRollback:u,confirmDialog:d,form:f,historyDialogue:p,characters:h};return C&&(R.dialogue=C,R.dialogueLines=C.lines),R},ai=100,dn=(e,t)=>{if(Array.isArray(e))return e.map(r=>dn(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=dn(n[r],t)}),n.type==="text-revealing"?t(n):n},$l=e=>dn(e,t=>({...t,revealEffect:"none"})),Tl=e=>dn(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,ai):ai;return{...t,speed:r,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:r}:{}}}),je=(e,{isLineCompleted:t=!1,skipMode:n=!1,skipTransitionsAndAnimations:r=!1}={})=>t||r?$l(e):n?Tl(e):e,xi=({id:e,screen:t={width:1920,height:1080}})=>({id:e,type:"rect",fill:"transparent",width:t.width,height:t.height,x:0,y:0,click:{payload:{actions:{}}}}),wr=e=>{if(Array.isArray(e))return e.map(wr);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=wr(s);let n=t.click?.payload;if(!n||typeof n!="object"||Array.isArray(n))return t;let r=n.actions,o=r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"nextLine")?{...r.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...n,bypassChoice:!0,...o?{actions:{...r,nextLine:o}}:{}}}}},Dl=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),ci="submit",hr=(e,t,n={})=>{let r=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},o=r.actions&&typeof r.actions=="object"?r.actions:{},i=n.replaceActions===!0?t:{...o,...t};return{...e||{},payload:{...r,actions:i}}},Er=(e,t,n={})=>{if(Array.isArray(e))return e.map(c=>Er(c,t,n));if(!e||typeof e!="object")return e;let r=typeof e.type=="string",o=r&&e.formRole===ci,i=r&&n.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},l={};for(let[c,u]of Object.entries(e))l[c]=Er(u,t,c==="children"?s:{});let a=l;if(a.type==="input"&&typeof a.field=="string"){let c=t?.fields?.[a.field];if(c){let u={updateFormField:{formKey:t.key,field:c.id,value:"_event.value"}};a={...a,value:c.value,placeholder:a.placeholder===void 0?c.placeholder:a.placeholder,multiline:a.multiline===void 0?c.multiline:a.multiline,...a.maxLength===void 0&&c.maxLength!==void 0?{maxLength:c.maxLength}:{},change:hr(a.change,u),submit:hr(a.submit,t.submitActions)}}}return a.formRole===ci||i?{...a,click:hr(a.click,t.submitActions,{replaceActions:!0})}:a},xr=(e,t)=>{if(Array.isArray(e))return e.map(r=>xr(r,t));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e))n[r]=xr(o,t);for(let r of Dl){let o=n[r]?.payload;!o||typeof o!="object"||Array.isArray(o)||(n[r]={...n[r],payload:{...o,_interactionSource:"form"}})}return n},vr=({characterId:e,character:t,characterName:n,characters:r={},variables:o={}}={})=>{let i=e?r?.[e]:void 0,s=Qt({characterId:e,character:t,characterName:n,characters:r,variables:o});return{...i||{},...t||{},name:s}},vi=(e=[],t={},n={})=>e.map(r=>{let o=vr({characterId:r.characterId,character:r.character,characterName:r.characterName,characters:t,variables:n}),i=typeof r.text=="string"?r.text:Array.isArray(r.content)?r.content.map(s=>s?.text??"").join(""):"";return{...r,text:i,character:o,characterName:o.name}}),Nl=e=>!(!e||e.mode==="adv"&&e.content===void 0),Pl=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:n={},variables:r,runtime:o}={})=>{if(!t&&!Nl(e))return;let i=e.content===void 0?[{text:""}]:yr(e.content,"dialogue.content"),s=e.content===void 0?0:il({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:r}),l=o?.dialogueTextSpeed??Ge.dialogueTextSpeed,a=e.textSpeed??l,c=(e.lines||[]).map((d,f)=>{let p=yr(d.content,`dialogue.lines[${f}].content`),h=vr({characterId:d.characterId,character:d.character,characterName:d.characterName,characters:n,variables:r});return{...d,textSpeed:d.textSpeed??l,content:p.map(g=>({...g,text:at(g.text,{variables:r})})),character:h,characterName:h.name}}),u=vr({characterId:e.characterId,character:e.character,characters:n,variables:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,persistSprite:e.persistSprite,character:u,textSpeed:a,content:i.map(d=>({...d,text:at(d.text,{variables:r})})),initialRevealedCharacters:s,lines:c}},Ci=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=ce(e,n,{functions:Re});return Oe(je(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},mr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),li=({renderStateKeyboard:e,keyboard:t,phase:n})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([r,o])=>{let i=e[r]??{},s=n==="keydown"?o?.keydown:o?.keyup;if(n==="keydown"&&s&&typeof s=="object"){e[r]={...i,keydown:{payload:mr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[r].keyup={payload:mr(o.keyup)});return}e[r]={...i,[n]:{payload:mr(o)}}})},Vl=(e={},t={})=>{let n={};return li({renderStateKeyboard:n,keyboard:e,phase:"keydown"}),li({renderStateKeyboard:n,keyboard:t,phase:"keyup"}),Object.keys(n).length>0?n:void 0},ke=({animationsDef:e,resources:t,previousResourceId:n,currentResourceId:r,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l})=>{if(!e)return[];let a=[],c=({instanceId:A,targetId:w})=>{let C=rl({resources:t,animationId:p,playback:h,instanceId:A,targetId:w,animationPath:s});C&&a.push(C)},u=n!=null&&n!==!1,d=r!=null&&r!==!1,f=o&&i&&o===i;nl(e,s);let p=Xc(e),h=Qc(e),g=t?.animations?.[p],b=Jc(g,{animationId:p,animationPath:s});if(b==="update")return d&&i?c({instanceId:`${l}-animation-update`,targetId:i}):u&&o&&c({instanceId:`${l}-animation-update`,targetId:o}),a;if(b==="transition"){let A=`${l}-animation-transition`,w=h?.continuity==="persistent"?A:`${l}-animation-in`;if(u&&d&&f)return c({instanceId:A,targetId:i}),a;u&&c({instanceId:`${l}-animation-out`,targetId:o}),d&&c({instanceId:w,targetId:i})}return a},jl=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Fl=(e,{presentationState:t,previousPresentationState:n,currentLineActions:r,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:a,runtime:c,activePersistentAnimations:u,restoredPersistentAnimations:d,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:b,form:A,saveSlots:w=[]})=>{let{elements:C,animations:R}=e;if(t.background){let V=r===void 0?!0:Je(r?.background??{},"animations"),j=C.find(ue=>ue.id==="story");if(!j)return e;let E=sl(o,t.background),B=E||cl(t.background),U=n?.background?.resourceId,J=n?.background?.colorId,M=t.background.resourceId??(t.background.animations?U:void 0),Y=t.background.colorId??(t.background.animations?J:void 0),G=Cl(o,M),X={...t.background,colorId:Y};if((Y!==void 0||G)&&j.children.push(vl({resources:o,background:X,screen:i,includeOpacity:!G})),M){let{images:ue={},videos:de={},spritesheets:Q={}}=o,re=hi(o,M),fe;if(re==="sprite"?fe=ue[M]:re==="video"?fe=de[M]:re==="spritesheet-animation"&&(fe=Q[M]),fe){let S=re==="video",O=re==="spritesheet-animation",F={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...E},oe={...oi(t.background,{includeDefaultAlpha:!0}),...Ve(F,t.background)},ie;O?ie=mi({id:cn({resourceId:M,kind:re}),resourceId:M,spritesheet:fe,animationName:t.background.animationName,animationSpeed:t.background.animationSpeed,loop:t.background.loop,transform:oe}):ie={id:cn({resourceId:M,kind:re}),type:S?"video":"sprite",src:fe.fileId,width:fe.width,height:fe.height,...oe},S&&(ie.loop=t.background.loop??!1,ie.volume=fe.volume??50),ie&&j.children.push(ie)}}if(M){let{layouts:ue={}}=o,de=ue[M];if(de){let Q={id:cn({resourceId:M,kind:"container"}),type:"container",children:de.elements,...oi(t.background)};B&&Object.assign(Q,Ve({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...E},t.background));let re=ce(Q,xe({variables:a,runtime:c,saveSlots:w,dialogueState:t.dialogue,isLineCompleted:s,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:b,form:A,characters:o.characters||{},skipTransitionsAndAnimations:l}),{functions:Re});j.children.push(Oe(je(re,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:l}),o))}}let ve=si({resources:o,resourceId:U,colorId:J}),te=si({resources:o,resourceId:M,colorId:Y}),ne=ke({animationsDef:t.background.animations,resources:o,previousResourceId:ve.resourceId,currentResourceId:te.resourceId,previousTargetId:ve.targetId,currentTargetId:te.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});Ee({animationInstances:ne,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:u,restoredPersistentAnimations:d,isAuthoredOnCurrentLine:V})&&R.push(...ne)}return e},Ml=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:a}=e;if(t.character&&r){let c=l.find(h=>h.id==="story");if(!c)return e;let u=t.character.items||[],d=n?.character?.items||[],f=ei(u),p=ei(d);for(let h=0;h<u.length;h++){let g=u[h],{transformId:b,sprites:A}=g,w=d.find(M=>M.id===g.id),C=d.findIndex(M=>M.id===g.id),R=w?.sprites&&w.sprites.length>0,V=A&&A.length>0,j=C>=0?rn(w,C,p):void 0,E=ke({animationsDef:g.animations,resources:r,previousResourceId:j,currentResourceId:V?rn(g,h,f):void 0,previousTargetId:j,currentTargetId:V?rn(g,h,f):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!A&&!b&&R&&Ee({animationInstances:E,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...E);continue}if(g.animations&&!A&&!b)continue;if(!A||A.length===0||!b){console.warn("Character item missing sprites or transformId:",g);continue}let B=rn(g,h,f),U=r.transforms[b];if(!U){console.warn("Transform not found:",b);continue}let J={type:"container",id:B,...Ve(U,g),...Rt(g),children:[]};for(let M of A){let Y=gi({id:`${B}-${M.id}`,item:M,resources:r});Y&&J.children.push(Y)}c.children.push(J),Ee({animationInstances:E,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...E)}}return e},Si=(e,t)=>{if(!cr.includes(e))throw new Error(`${t} must be one of: ${cr.join(", ")}.`)},Bl=(e,t)=>{let n=!!e.resourceId||Or(e),r=e.layer??(n?void 0:t?.layer)??ar;return Si(r,`Visual item "${e.id}" layer`),r},Ul=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:l,activePersistentAnimations:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,saveSlots:g=[],visualLayer:b})=>{let{elements:A,animations:w}=e;if(t.visual&&r){let C=A.find(E=>E.id==="story");if(!C)return e;let R=t.visual.items,V=n?.visual?.items||[],j=xe({variables:s,runtime:l,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,characters:r.characters||{},skipTransitionsAndAnimations:i});b!==void 0&&Si(b,"visualLayer");for(let E of R){let B=V.find(G=>G.id===E.id),U=Bl(E,B);if(b!==void 0&&U!==b)continue;if(xl(E),E.text){let G=on(r,E),X={...structuredClone(E.text),id:`visual-${E.id}`,type:"text",...Ve(G,E)};Object.assign(X,Rt(E)),C.children.push(Oe(ce(X,j,{functions:Re}),r))}if(E.resourceId){let{images:G={},videos:X={},spritesheets:ve={}}=r,te=ve[E.resourceId];if(te){let ne=on(r,E),ue=E.animationName;if(ue){let de=te.animations?.[ue];if(!de)throw new Error(`Animation '${ue}' not found in spritesheet resource '${E.resourceId}'`);let Q=Rt(E),re={id:`visual-${E.id}`,type:"spritesheet-animation",...Ve(ne,E),width:E.width??te.width,height:E.height??te.height,alpha:Q.alpha??E.alpha??1,src:te.fileId,atlas:te.jsonData,playback:{frames:de.frames,animationSpeed:E.animationSpeed??de.animationSpeed??.5,loop:E.loop??de.loop??!0}};Q.blur&&(re.blur=Q.blur),C.children.push(structuredClone(re))}}else{let ne=G[E.resourceId]||X[E.resourceId];if(ne){let ue=X[E.resourceId]!==void 0,de=on(r,E),Q={id:`visual-${E.id}`,type:ue?"video":"sprite",src:ne.fileId,width:ne.width,height:ne.height,...Ve(de,E)};Object.assign(Q,Rt(E)),ue&&(Q.loop=ne.loop??!1,Q.volume=ne.volume??50),C.children.push(Q)}}}if(E.resourceId){let{layouts:G={}}=r,X=G[E.resourceId];if(X){let ve=on(r,E),te={id:`visual-${E.id}`,type:"container",children:structuredClone(X.elements),...Ve(ve,E)};Object.assign(te,Rt(E));let ne=ce(te,j,{functions:Re});C.children.push(Oe(je(ne,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),r))}}let J=ii(B),M=ii(E),Y=ke({animationsDef:E.animations,resources:r,previousResourceId:J,currentResourceId:M,previousTargetId:J?`visual-${E.id}`:void 0,currentTargetId:M?`visual-${E.id}`:void 0,animationPath:`visual.items[${E.id}].animations`,idPrefix:E.id});Ee({animationInstances:Y,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:a})&&w.push(...Y)}}return e},lt="dialogue-character-sprite",zl=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=Qe(e.elements);if(!a)return e;let c=t.dialogue?.character?.sprite,u=n?.dialogue?.character?.sprite,d=xt(c),f=xt(u),p=ke({animationsDef:c?.animations,resources:r,previousResourceId:f?lt:void 0,currentResourceId:d?lt:void 0,previousTargetId:f?lt:void 0,currentTargetId:d?lt:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!d)return c?.animations&&f&&Ee({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e;let h=r.transforms?.[c.transformId];if(!h)return console.warn("Transform not found:",c.transformId),e;let g={type:"container",id:lt,...Ve(h),children:[]};for(let b of c.items){let A=gi({id:`${lt}-${b.id}`,item:b,resources:r});A&&g.children.push(A)}return a.children.push(g),Ee({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e},ql=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,skipOnlyViewedLines:d,isLineCompleted:f,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:b,saveSlots:A=[]})=>{let{elements:w,animations:C}=e;if(!t.dialogue||o)return e;let R=w.find(j=>j.id==="story");if(!R)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:j={}}=r,E=j[t.dialogue.ui.resourceId];if(E){let B={elements:E.elements},U=xe({variables:h,runtime:g,saveSlots:A,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:f,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,characters:r.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:d,skipTransitionsAndAnimations:p}),J={functions:Re},M=an(B,U,J),Y=ce(M,U,J),G=Oe(je(Y?.elements,{isLineCompleted:f,skipMode:s,skipTransitionsAndAnimations:p}),r);if(Array.isArray(G))for(let X of G)R.children.push(X);else G&&R.children.push(G)}}zl(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:b});let V=ke({animationsDef:t.dialogue.ui?.animations,resources:r,previousResourceId:n?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:n?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return Ee({animationInstances:V,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:b})&&C.push(...V),e},Hl=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:b=[]})=>{let{elements:A,animations:w}=e;if(t.choice&&r){let C=Qe(A);if(!C)return e;let R=r?.layouts[t.choice.resourceId];if(R&&R.elements){let j={elements:R.elements},E=ce(j,{...xe({variables:l,runtime:a,saveSlots:b,dialogueState:t.dialogue,isLineCompleted:i,autoMode:c,skipMode:u,isChoiceVisible:d??!!t.choice,isFormVisible:f,canRollback:p,form:h,characters:r.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:Re}),B=wr(Oe(je(E?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r));if(Array.isArray(B))for(let U of B)C.children.push(U);else B&&C.children.push(B)}let V=ke({animationsDef:t.choice.animations,resources:r,previousResourceId:n?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:n?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});Ee({animationInstances:V,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&w.push(...V)}return e},Wl=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:b})=>{let{elements:A,animations:w}=e;if(!b?.resourceId||!r)return e;let C=Qe(A);if(!C)return e;let R=r?.layouts?.[b.resourceId];if(!R)return console.warn(`Form layout not found: ${b.resourceId}`),e;let V={id:"form-container",type:"container",x:0,y:0,children:R.elements||[]},j={...xe({variables:l,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,characters:r.characters||{},skipTransitionsAndAnimations:s,form:b}),form:b},E=ce(V,j,{functions:Re}),B=xr(Oe(je(Er(E,b),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r),b);B&&C.children.push(B);let U=ke({animationsDef:b.animations,resources:r,previousResourceId:n?.form?.resourceId,currentResourceId:b.resourceId,previousTargetId:n?.form?.resourceId?"form-container":void 0,currentTargetId:b.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return Ee({animationInstances:U,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&w.push(...U),e},Yl=(e,{presentationState:t,resources:n={},variables:r,runtime:o,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,saveSlots:f=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=n.controls?.[t.control.resourceId];if(!h)return e;let g=Vl(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 b=Qe(e.elements);if(!b)return e;let A={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return b.children.push(Ci({container:A,resources:n,templateData:xe({variables:r,runtime:o,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,characters:n.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:l,skipTransitionsAndAnimations:p})),e},Gl=(e,{presentationState:t,resources:n,runtime:r,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&n){if(!Qe(i))return e;let a=t.bgm,c=!Array.isArray(a.sounds),u=c?a.resourceId?[{id:"default",resourceId:a.resourceId,loop:a.loop??!0,volume:a.volume,startDelayMs:a.startDelayMs??0}]:[]:a.sounds,d=[];if(c||un(u,"BGM sound"),u.forEach(p=>{let h=n.sounds?.[p.resourceId];h&&d.push($r({id:Ot("bgm",c?"default":p.id),sound:p,resource:h,defaultLoop:!0}))}),d.length===0)return e;let f=xe({variables:o,runtime:r}).runtime;s.push(Lr({id:Sl,volume:kr(f,"musicVolume",c?Xe:a.volume??Xe),muted:a.muted,pan:a.pan,children:d,runtime:f}))}return e},Kl=(e,{presentationState:t,resources:n,runtime:r})=>{let{audio:o}=e;if(t.sfx&&n){let i=t.sfx,s=!Array.isArray(i.channels),l=s?[{id:Rl,sounds:i.items??[]}]:i.channels;s||un(l,"SFX channel"),l.forEach(a=>{let c=[];s||un(a.sounds,"SFX sound",`SFX channel "${a.id}"`),a.sounds.forEach((u,d)=>{let f=n.sounds?.[u.resourceId];f&&c.push($r({id:s?Ot("sfx","default",d,u.id):Ot("sfx",a.id,u.id),sound:u,resource:f}))}),c.length!==0&&o.push(Lr({id:Ot("channel","sfx",a.id),volume:kr(r,"soundVolume",a.volume??Xe),muted:a.muted,pan:a.pan,children:c,runtime:r}))})}return e},Jl=(e,t,n)=>{if(!(!t||!n))return e?.voices?.[t]?.[n]},Xl=(e,{presentationState:t,resources:n,currentSceneId:r,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let l=t.voice,a=!Array.isArray(l.sounds),c=a?l.resourceId?[{id:"default",resourceId:l.resourceId,loop:l.loop??!1,volume:Xe,startDelayMs:l.startDelayMs??0}]:[]:l.sounds,u=[];if(a||un(c,"Voice sound"),c.forEach(f=>{let p=Jl(n,r,f.resourceId);p&&u.push($r({id:Ot("voice",r,a?"default":f.id),sound:f,resource:p}))}),u.length===0)return e;let d=xe({variables:i,runtime:o}).runtime;return s.push(Lr({id:_l,volume:a?l.volume??Ei(d,"soundVolume"):kr(d,"soundVolume",l.volume??Xe),muted:l.muted,pan:l.pan,children:u,runtime:d})),e},Ql=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,saveSlots:f=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:b,animations:A}=e;if(t.layout){let V=Qe(b);if(!V)return e;let j=r.layouts[t.layout.resourceId];if(!j)return e;Array.isArray(j.transitions)&&!p&&!h&&Sr({animations:A,transitions:j.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let E={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:j.elements||[]};V.children.push(Ci({container:E,resources:r,templateData:xe({variables:o,runtime:i,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,characters:r.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:l,skipTransitionsAndAnimations:h}))}let w=n?.layout?.resourceId,C=t.layout?.resourceId,R=ke({animationsDef:t.layout?.animations,resources:r,previousResourceId:w,currentResourceId:C,previousTargetId:w?`layout-${w}`:void 0,currentTargetId:C?`layout-${C}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return Ee({animationInstances:R,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&A.push(...R),e},Zl=(e,{currentLineActions:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=t?.screen?.animations;if(!a)return e;let c=n!=null,u=ke({animationsDef:a,resources:r,previousResourceId:c?"story":void 0,currentResourceId:"story",previousTargetId:c?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return Ee({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...u),e},eu=(e,{presentationState:t})=>{let n=Qe(e.elements);return!n||!t?.screen||Object.assign(n,Ai(t.screen)),e},tu=(e,{presentationState:t,resources:n={},variables:r,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,overlayStack:d=[],dialogueHistory:f=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:b})=>{let{elements:A,animations:w}=e;return d&&d.length>0&&d.forEach((C,R)=>{let V=n.layouts[C.resourceId];if(!V){console.warn(`Overlay layout not found: ${C.resourceId}`);return}Array.isArray(V.transitions)&&(b||Sr({animations:w,transitions:V.transitions,defaultTargetId:`overlayStack-${R}`,idPrefix:`overlayStack-${R}`,animationPathPrefix:`overlayStack[${R}]`}));let j={id:`overlayStack-${R}`,type:"container",x:0,y:0,children:[xi({id:`overlayStack-${R}-blocker`,screen:h}),...V.elements||[]]},E=vi(f,n.characters,r),B=xe({variables:r,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,historyDialogue:E,characters:n.characters||{},skipTransitionsAndAnimations:b}),U=ce(j,B,{functions:Re}),[J,...M]=U.children||[],Y=Oe(je({...U,children:M},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:b}),n);A.push({...Y,children:J?[J,...Y.children||[]]:Y.children})}),e},nu=(e,{presentationState:t,resources:n={},variables:r,runtime:o,saveSlots:i=[],autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,confirmDialog:f,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:b})=>{let{elements:A,animations:w}=e;if(!f?.resourceId)return e;let C=n.layouts?.[f.resourceId];if(!C)return console.warn(`ConfirmDialog layout not found: ${f.resourceId}`),e;Array.isArray(C.transitions)&&!b&&Sr({animations:w,transitions:C.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let R={id:"confirmDialog",type:"container",x:0,y:0,children:[xi({id:"confirmDialog-blocker",screen:h}),...C.elements||[]]},V=vi(p,n.characters,r),j=ce(R,xe({variables:r,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,confirmDialog:f,historyDialogue:V,characters:n.characters||{},skipTransitionsAndAnimations:b}),{functions:Re}),[E,...B]=j.children||[],U=Oe(je({...j,children:B},{isLineCompleted:g,skipMode:l,skipTransitionsAndAnimations:b}),n);return A.push({...U,children:E?[E,...U.children||[]]:U.children}),e},$t=e=>(t,n)=>Ul(t,{...n,visualLayer:e}),ru=$t(_e.BEHIND_BACKGROUND),ou=$t(_e.BEHIND_CHARACTER),iu=$t(_e.BEHIND_DIALOGUE),su=$t(_e.BEHIND_CHOICE),au=$t(_e.FOREGROUND),_i=e=>Xt(jl,[Yl,ru,Fl,ou,Ml,iu,ql,su,Hl,Wl,Ql,au,eu,Zl,Gl,Kl,Xl,tu,nu])(e);function Ri(e,t=""){let n=[],r=e.length,o=0,i=0,s=-1,l=()=>{let a=0,c=0,u;do u=parseInt(e[o++],36),a+=(u&15)<<c,c+=4;while(u&16);return a};for(;o<r;){let a=s+1+l();s=a+l(),n.push([a,s,t?parseInt(t[i++],36):0])}return n}function Oi(e,t,n){let r=0,o=t.length-1;for(;r<=o;){let i=r+o>>>1,s=n[i];if(e<t[i])o=i-1;else if(e>s>>>5)r=i+1;else return s&31}return 0}var ki="090001000h1v5g2903000hl2v6jh16ng1s210111110o35aa10u2k1g10l6600152113h2010u1q1r5aq3890o13181214r22k3158q2n1000v100h1k20000001207030001160721k171001h1j11610332010010321210090411021c1c02100o301201412230u1130b100h1j116111420120411001100k11l10051001h1j11611142011000321210072411021d0g10r3000000132120090o200200g1j11f2012031213711271t1001o301001000001121371b1f0c101h1l2011001031212000080a1t1001m40400102101600i11t301006c7i601008b6p41r10101041h3d0004115a1j290p3q223000511010100g1501010302003172030c0010016000e0i6v50n40n5tl12ir33s12t11u11cj30100060700010a90t220000l71i20m7203010241000502rd101004k300000006101027050920g3t22bk1300616g209030207u18c1000t10003010501b2o20000102000004g37070101o921c000640602001mcv3rg20000001o16d0c0m1fg6g2h30m10q55f1vm11c0ma0p1a42nc0ne1a090q3314902021204020112030318250105bb1201110i1021i15101131502141b15120511011k1155132040202510201010603060a1f02040104210b1g3290e0e0kn11vs12j11j3040pp12t80g6v1vmo7319g21g51gh103040n11010040j51i3f01q1h1d0m27p1a0000cs13200523j200010301010100v140018a4q2501010101c08000i1f12601011g3012215110u1a0001015000pcq181000100011000iji5fvc0u91g5bhg20ie0l94lo6002115303121s12240la1tj23h44tj11t45m4ah33q700000l3ep2021a200t220301012040a0i320j2040007f00100r20c100g3208000011531000s520201036020t900207l1101n311000000321210090a12634b910201l22001051020120011020000e1i520701020000n10h5001050000010000010001re0010323010001r11i520701000001q6000000107l600000230004gg12080001lc62027111n1000411230000000000t820321030030r10090n205001380800501020n2050c0001mc00002000000nc006150000i5l1100600010001q753011160000i441111000000rl11019100000c1h201043102n10ltk1f006eoss2b0202gs94r36si2033ku101m373h50b1rqs4113sli1t22m1uh2435070726u13k92rr7m34h380e0m141egl561g1261114k60ga6nn10t33sv13uf1jf0207150qt16t66pr60n23k6bf1f0e1l29g71c1e029j1n30p11ea0k1028139m16rb2v621122i52213040tf1u3b51n17127c0232041d120819052c28220104060306l5g3l4572g130152cqdl2c3o37a5o27u11c32d9m2cu2191obo57eh9gg1tv3",Li="262122424333333393233393339333333333393393bf3b3b3b3b3f3f3bffff33b3bb33ff3f33b3b3333333bffff3b33bb33f33bffff33b3bb33ff3f33b3bbb333b3ff33b333f33b3b3b3b3333b3bf33b3bb39333b33b33b3b3b333b333333b3b33333f3b33b3ffb3f3fff3f3b33f35dc33333f3b3b3b33323333b3bb3b33b3fb3b3333b33333bff3b3f33bfb3b3ff3b3b3b3b3b333b333b3323e22442344444444444444444444444444444444444444444444444444444444444444444444444444444443333333333b3b3bb33333b353bff3b3b3b3f3ff3b3b333bfff3f33333fb3bb3fb3b3bb33232333f333fff333333333b3b3333bb3b39393f3b3fbf33bb3b393b3b3b3333b33b33b3bbb33b33ffff3b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b3fffff3bb39b9b3b33b3bf3f3b33f3b3f93b33b3b3bb33b33b3b3b3333393b3b3b33b39bffb3b332333b333dd3b3333233332333333333333333333333333333444444444444a4444444444444344444444444444444444444444444444444444444444",$i="0001000000010010000000100000000000000000000000000001000000010014000100000001001000010101100101100000000000000000000100000001111000010000000110101001110111111111000100000021001000010000000100100001000000011010000100000001111000013000000100140001000000010010";var Ti=65535,Tr=40960,pn=126976,Pi=new Uint8Array(12288),Vi=new Uint8Array(3072),ji=new Uint8Array(2816),Fi,Mi;{let e=(o,i,s,l,a)=>{let c=i+o.length-1;for(let u=s<i?i:s,d=l>c?c:l;u<=d;u++)o[u-i]=a},t=new Uint32Array(320),n=new Uint32Array(320),r=0;for(let[o,i,s]of Ri(ki,Li))e(Pi,0,o,i,s),e(Vi,Tr,o,i,s),e(ji,pn,o,i,s),i>=65040&&!(o>=pn&&i<=129791)&&(t[r]=o,n[r++]=i<<5|s);Fi=t.slice(0,r),Mi=n.slice(0,r)}function Di(e){return e<12288?Pi[e]:e<Tr?e<12336?e>=12330?3:0:e<12443?e===12336||e===12349?4:e>=12441?3:0:e===12951||e===12953?4:0:e<44032?Vi[e-Tr]:e<55204?(e-44032)%28?8:7:e<57344?e<=55238?e>=55216?13:0:e>=55243&&e<=55291?12:0:e<65024?e===64286?3:0:e<65040?3:e>=pn&&e<129792?ji[e-pn]:e>=917504?e>921599?0:e>=917536&&e<917632||e>=917760&&e<918e3?3:2:Oi(e,Fi,Mi)}var Bi=Uint8Array.from($i,Number);function cu(e){return e===2381||e===2509||e===2637||e===2765||e===2893||e===3149||e===3405||e===4153||e===6098||e===6752||e===6980||e===7083||e===43456||e===43766||e===68159||e===69939||e===70608||e===71998||e===72263||e===72345||e===73538}function Ni(e,t,n){switch(t){case 3:return e&24?n===8204?e&6:(e&24)===16||cu(n)?e&6|16:e&6|8:e&6;case 4:return 2;case 10:return e&1^1;case 14:return(e&2)<<1|e&24;default:return 8}}function*Ui(e){let t=e.length;if(t===0)return;let n=e.codePointAt(0),r=n>Ti?2:1,o=Di(n),i=50200>>o&1?Ni(0,o,n):0,s=0,l=n,a=o;for(;r<t;){n=e.codePointAt(r);let c=n>Ti?2:1,u=Di(n),d=Bi[o<<4|u],f;d===0?f=!0:d===1?f=!1:d===2?f=!(i&1):d===3?f=!(i&4):f=(i&24)!==16,i=50200>>u&1&&(i!==0||u!==3)?Ni(i,u,n):0,f&&(yield{segment:e.slice(s,r),index:s,input:e,_hd:l,_catBegin:a===15?0:a,_catEnd:o===15?0:o},s=r,l=n,a=u),r+=c,o=u}yield{segment:e.slice(s),index:s,input:e,_hd:l,_catBegin:a===15?0:a,_catEnd:o===15?0:o}}function*zi(e){for(let t of Ui(e))yield t.segment}{let e=Ui("_");Bi._keep=[e,e.next()]}var qi=1e3,lu=1,uu=60,du=3,fu=.5,pu=2e4,hu=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,mu=/^\s+$/u,Hi,gu=e=>{let t=`${e??""}`.normalize("NFC"),n=globalThis.Intl?.Segmenter;return typeof n!="function"?Array.from(zi(t)):(Hi??=new n(void 0,{granularity:"grapheme"}),Array.from(Hi.segment(t),({segment:r})=>r))},yu=e=>gu(e).reduce((t,n)=>mu.test(n)?t+fu:hu.test(n)?t+du:t+1,0),Wi=({text:e="",baseDelay:t=qi,speed:n=lu}={})=>{let r=Number.isFinite(t)?Math.max(0,t):qi,o=Number.isFinite(n)&&n>0?n:1,i=yu(e)*uu/o,s=Math.max(r,pu);return Math.min(r+i,s)};var hn={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Xi=1,Dr=1,ft="choice",Fe="form",yn=()=>({manual:{...hn.manual},auto:{...hn.auto},applyMode:hn.applyMode}),Nr=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...yn()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},T=e=>{let t=se(e)?He(e):e;return structuredClone(t)},$=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Qi=(e,t)=>{if(typeof t!="string"||t.length===0)throw new Error("Achievement action requires a non-empty resourceId");let n=e.projectData.resources?.achievements?.[t];if(!n)throw new Error(`Achievement resource "${t}" not found`);if(n.type!=="boolean"&&n.type!=="number")throw new Error(`Achievement resource "${t}" has invalid type "${n.type}"`);return n},Dt=e=>String(e),Zi=()=>({sections:[],resources:[]}),bu=e=>$(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Zi(),Iu=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Au=({sectionId:e,lineId:t,content:n,dialogueState:r,characterName:o})=>({sectionId:e,lineId:t,content:n,text:Iu(n),characterId:r.characterId,character:{...r.character||{},name:o},characterName:o}),wu=()=>({resourceId:void 0}),Eu=e=>{if(!$(e))return e;let t={...e};return Object.prototype.hasOwnProperty.call(t,"requireComplete")&&!Object.prototype.hasOwnProperty.call(t,"requireLineCompleted")&&(t.requireLineCompleted=t.requireComplete),delete t.requireComplete,t},pt=(e,t)=>{let n=e?.story?.scenes??{};for(let[r,o]of Object.entries(n))if(o?.sections?.[t])return{sceneId:r,section:o.sections[t]};return{sceneId:void 0,section:void 0}},es=e=>{let t=e?.story?.scenes??{},n=new Map;for(let[r,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let l=n.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${r}". Section IDs must be globally unique.`);n.set(s,r)}}},ts=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},ns=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Xi)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},xu=(e,t={})=>{let n;try{n=ns(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:ts(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},vu=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,xu(t,n)])),rs=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:n})=>kf(n));return t.length>0?t:void 0},Cu=e=>{!$(e)||!Array.isArray(e.timeline)||(e.returnabilityVersion=Dr,e.timeline.forEach(t=>{if(!$(t))return;typeof t.returnable!="boolean"&&delete t.returnable;let n=rs(t.executedActions);if(n){t.executedActions=n;return}delete t.executedActions}))},Yi=(e,t,n,r="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!$(e))throw new Error(`Malformed ${r}.${t}[${n}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${r}.${t}[${n}] 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 ${r}.sections[${n}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},Su=(e,t="viewedRegistry")=>{if(e===void 0)return Zi();if(!$(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let n=e.sections??[],r=e.resources??[];return{sections:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Yi(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Yi(o,"resources",i,t);return[s.resourceId,s]})))}},os=(e,t,n)=>{if(!$(e))throw new Error(`Malformed save slot ${n}.`);let{sectionId:r,lineId:o}=e;if(typeof r!="string"||r.length===0)throw new Error(`Malformed save slot ${n}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${n}: missing lineId.`);let{sceneId:i,section:s}=pt(t,r);if(!s)throw new Error(`Malformed save slot ${n}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(a=>a.id===o))throw new Error(`Malformed save slot ${n}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},is=(e,t)=>e?.sectionId===t?.sectionId&&e?.lineId===t?.lineId,_u=(e,t)=>{let{section:n}=pt(e,t?.sectionId);return n?.lines?.find(r=>r.id===t?.lineId)},Ru=(e,t)=>{let{section:n}=pt(e,t?.sectionId),r=n?.lines?.findIndex(i=>i.id===t?.lineId);if(typeof r!="number"||r<0)return null;let o=n.lines[r+1];return o?{sectionId:t.sectionId,lineId:o.id}:null},ss=(e,t,n)=>{if(typeof t?.sectionId!="string")return!1;let{section:r}=pt(e,t.sectionId);return is({sectionId:t.sectionId,lineId:r?.lines?.[0]?.id},n)},Ou=new Set(["jumpToLine","rollbackByOffset","rollbackToLine","sectionTransition","resetStoryAtSection"]),dt={always:"always",maybe:"maybe",never:"never"},ku=e=>{if(!Object.prototype.hasOwnProperty.call(e??{},"when"))return dt.always;let t=e.when,n;if(t===null||typeof t=="boolean"||typeof t=="number")n=t;else if($(t)&&Object.keys(t).length===1&&Object.prototype.hasOwnProperty.call(t,"literal"))n=t.literal;else return dt.maybe;return n?dt.always:dt.never},as=(e,t)=>{if(!Array.isArray(e?.branches))return!1;for(let n of e.branches){let r=ku(n);if(r!==dt.never){if(t(n))return!0;if(r===dt.always)return!1}}return!1},cs=e=>as(e,t=>Object.entries(t?.actions??{}).some(([n,r])=>n==="conditional"?cs(r):Ou.has(n))),ls=(e,t,n)=>as(t,r=>Object.entries(r?.actions??{}).some(([o,i])=>o==="sectionTransition"?ss(e,i,n):o==="conditional"?ls(e,i,n):!1)),Lu=(e,t,n)=>{if(!t)return!0;let r=_u(n,e)?.actions;if(!$(r))return!0;if(ss(n,r.sectionTransition,t))return!1;let o=r.conditional;return o?!(ls(n,o,t)||!(r.choice?.resourceId||r.form?.resourceId)&&!cs(o)&&is(Ru(n,e),t)):!0},$u=(e,t,n)=>{if(!$(e)||!Array.isArray(e.timeline))return Tt({pointer:t,replayStartIndex:1});let r=new WeakSet,o=e.timeline.flatMap((c,u)=>{if(!$(c))return[];try{let d=os(c,n,`rollback.timeline[${u}]`),f=gn({sectionId:d.sectionId,lineId:d.lineId,rollbackPolicy:c.rollbackPolicy,returnable:c.returnable});typeof c.returnable=="boolean"&&r.add(f);let p=rs(T(c.executedActions));return p&&(f.executedActions=p),[f]}catch{return[]}});if(o.length===0)return Tt({pointer:t,replayStartIndex:1});e.returnabilityVersion!==Dr&&o.forEach((c,u)=>{!r.has(c)&&!Lu(c,o[u+1],n)&&(c.returnable=!1)});let s=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):o.length-1;(s<0||s>=o.length)&&(s=o.length-1);let l=o[s];if(l?.sectionId!==t.sectionId||l?.lineId!==t.lineId){let c=o.findLastIndex(u=>u.sectionId===t.sectionId&&u.lineId===t.lineId);c>=0?s=c:(o.push(gn({sectionId:t.sectionId,lineId:t.lineId})),s=o.length-1)}let a=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),s):0;return{currentIndex:s,isRestoring:!1,replayStartIndex:a,timeline:o}},Tu=(e,t,n)=>{if(!$(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=jr(t),o=os(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!$(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);if(e.runtime!==void 0&&!$(e.runtime))throw new Error(`Malformed save slot contexts[${n}].runtime entry.`);let i=e.variables?st(T(e.variables),t.resources?.variables??{}):{},s=Wu({loadedContextRuntime:$(e.runtime)?T(e.runtime):{}}),l={currentPointerMode:"read",pointers:{read:o},configuration:$(e.configuration)?T(e.configuration):{},views:Array.isArray(e.views)?T(e.views):[],bgm:$(e.bgm)?T(e.bgm):{resourceId:void 0},variables:{...r,...i},rollback:$u(e.rollback,o,t)};return s&&(l.runtime=s),l},Du=(e,t)=>{if(!$(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((n,r)=>Tu(n,t,r))}},Nu=(e,t)=>{if(!$(e))throw new Error("Malformed save slot.");let n=ns(e.formatVersion);return{...e,formatVersion:n,state:Du(e.state,t)}},Gi=(e,t,{required:n=!1}={})=>{if(e===void 0){if(n)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 r=T(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},Pu=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Gi(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Gi(e.cancelActions,"cancelActions")}},ht=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Vu=e=>($(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),mt=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},us=e=>{if(!(!$(e)||!e.animations))return{animations:T(e.animations)}},ju=(e,t)=>{let n=us(t);if(n){e.global.pendingScreenTransition=n;return}delete e.global.pendingScreenTransition},Fu=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},Mu=(e,t)=>{let n=e?.sectionId,r=e?.lineId;if(!(!n||!r||!t))return`${n}:${r}:${t}`},mn=e=>String(e??""),ds=(e,t)=>{let n=mn(t);return e?.trim===!0?n.trim():n},Bu=e=>$(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>$(t)).map(([t,n])=>[t,{id:t,...T(n)}])):{},Uu=(e,t)=>{if(!t||!$(e.global.formDrafts))return;let n=e.global.formDrafts[t];return $(n)?n:void 0},fs=(e,t)=>{let n=Vu(e);$(n[t])||(n[t]={values:{},touched:{},errors:{},submitted:!1});let r=n[t];return $(r.values)||(r.values={}),$(r.touched)||(r.touched={}),$(r.errors)||(r.errors={}),typeof r.submitted!="boolean"&&(r.submitted=!1),r},Pr=(e,t)=>{let n=ds(e,t);return e?.required===!0&&n.length===0?"required":null},zu=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let r=le({state:e},{sectionId:t.sectionId})?.lines||[],o=r.findIndex(i=>i.id===t.lineId);return o<0?{}:Ye(r.slice(0,o+1).map(i=>i.actions||{}))},qu=({state:e,form:t,pointer:n})=>{if(!t?.resourceId)return null;let r=Fu(t),o=Mu(n,r);if(!r||!o)return null;let i=Uu(e,o),s=Bu(t),l=In({state:e}),a={},c=[],u={},d=!0;return Object.entries(s).forEach(([f,p])=>{let h=mn(l?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},f)?mn(i.values[f]):h,b=i?.touched?.[f]===!0,A=Pr(p,g),w=i?.submitted||b?A:null,C=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,R={id:f,variableId:p.variableId,value:g,initialValue:h,valid:!A,error:w,touched:b,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...C!==void 0?{maxLength:C}:{}};A&&(d=!1),a[f]=R,c.push(R),u[f]=g}),{id:r,key:o,resourceId:t.resourceId,animations:t.animations,valid:d,submitted:i?.submitted===!0,fields:a,fieldList:c,values:u,submitActions:{submitForm:{formKey:o,actions:T(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:T(t.cancelActions??{})}}}},Ze=[],Ki="line",Vr="interaction",gn=({sectionId:e,lineId:t,rollbackPolicy:n,returnable:r})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free",...typeof r=="boolean"?{returnable:r}:{}}),jr=e=>{let{contextVariableDefaultValues:t}=Zt(e??{});return T(t)},ps=()=>({...T(_t)}),hs=({loadedRuntime:e,runtimeIds:t,defaults:n={},path:r})=>{if(e===void 0)return{runtimeState:T(n),hasLoadedValues:!1};if(!$(e))throw new Error(`Malformed ${r}.`);let o=T(n),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=ms(s,T(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Hu=({loadedGlobalRuntime:e={}})=>hs({loadedRuntime:e,runtimeIds:ir,defaults:Ge,path:"global.runtime"}).runtimeState,Wu=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:n}=hs({loadedRuntime:e,runtimeIds:sr,defaults:ps(),path:"context.runtime"});return n?t:void 0},bn=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Yu=e=>e.runtime?(sr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=T(_t[t]))}),e.runtime):(e.runtime=ps(),e.runtime),Gu=e=>Qo(e.global),Ku=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Gu(e)}})},Ju=e=>Xo[e],Xu=(e,t)=>{let n=Ju(e);if(n==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(n==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(n==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},ms=(e,t)=>{if(Xu(e,t),e==="autoForwardSpeed"&&t<=0)throw new Error("autoForwardSpeed requires a value greater than 0");return e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t},gs=(e,t,n)=>{let r=ms(t,n);if(t in _t){let o=bn(e);if(!o)return r;let i=Yu(o);return i[t]=r,r}return e.global[t]=r,r},ys=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:T(e)},configuration:{},views:[],bgm:wu(),variables:jr(t),rollback:Tt({pointer:e})}),gt=e=>e?(e.currentPointerMode="read",$(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Qu=(e,{queueRender:t=!0}={})=>{let n=e.contexts?.[e.contexts.length-1],r=n?.pointers?.read;if(!n||!r?.sectionId||!r?.lineId)return null;let o=ys({pointer:r,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,Zu(e,{queueRender:t}),o},Zu=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,ht(e),mt(e),e.global.nextLineConfig=yn(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},bs=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},Tt=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[gn({sectionId:e.sectionId,lineId:e.lineId})]:[]}},tt=(e,t={})=>{if(e?.rollback)return bs(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 n=e?.pointers?.read;return e.rollback=Tt({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},Fr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=tt(n);r.isRestoring||(r.currentIndex<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,r.currentIndex+1)),r.timeline.push(gn(t)),r.currentIndex=r.timeline.length-1)},ed=({state:e})=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!Array.isArray(n?.timeline)||typeof n.currentIndex!="number"?null:{checkpointIndex:n.currentIndex,checkpoint:n.timeline[n.currentIndex]??null}},td=({state:e},t={})=>{let{checkpointIndex:n,checkpointIdentity:r,sectionId:o,lineId:i}=t,l=e.contexts?.[e.contexts.length-1]?.rollback;if(!Number.isInteger(n)||!Array.isArray(l?.timeline)||typeof l.currentIndex!="number")return e;let a=l.timeline[n];return(se(a)?jn(a):a)!==r||a?.sectionId!==o||a?.lineId!==i||(a.returnable=!1),e},nd=({state:e},t={})=>{let{slotId:n,saveSlotIdentity:r,checkpointIndex:o,sectionId:i,lineId:s}=t,l=Dt(n),a=e.global.saveSlots?.[l],c=se(a)?jn(a):a;if(!a||c!==r)return e;let u=a.state?.contexts,d=Array.isArray(u)?u.at(-1):null,f=d?.rollback,p=f?.timeline?.[o];return!Number.isInteger(o)||f?.currentIndex!==o||d?.pointers?.read?.sectionId!==i||d?.pointers?.read?.lineId!==s||p?.sectionId!==i||p?.lineId!==s||(p.returnable=!1,f.returnabilityVersion=Dr,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}})),e},rd=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;if(!n||n.isRestoring||!Array.isArray(n.timeline)||typeof n.currentIndex!="number")return null;let r=Ze[Ze.length-1],o=typeof r?.checkpointIndex=="number"?r.checkpointIndex:n.currentIndex;return o<0||o>=n.timeline.length?null:(typeof r?.checkpointIndex!="number"&&o<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,o+1)),n.timeline[o]??null)},od=({state:e},t={})=>{let n=t?.source===Ki?Ki:Vr,o=e.contexts?.[e.contexts.length-1]?.rollback;return!o||o.isRestoring||!Array.isArray(o.timeline)||typeof o.currentIndex!="number"||o.currentIndex<0||o.currentIndex>=o.timeline.length?(Ze.push({checkpointIndex:null,source:n}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Ze.push({checkpointIndex:o.currentIndex,source:n}),e)},id=({state:e})=>(Ze.pop(),e),Se=(e,t,n)=>{let o=Ze[Ze.length-1]?.source??Vr;if(!Lf(t,o))return;let i=rd(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:T(n)}))},Ji=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:l}of r){let a=e.projectData.resources?.variables?.[o],c=a?.scope,u=a?.type;if(Ne(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);en(c,o),tn(u,i,o),Zn(u,i,s,o,{roundTo:l}),c==="context"&&(n.variables[o]=nn(n.variables[o],i,s,{roundTo:l}))}},sd=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:n,payload:r})=>{$f(e,n,r)})},ad=(e,t)=>{let{sectionId:n,lineId:r}=t,s=le({state:e},{sectionId:n})?.lines?.find(l=>l.id===r)?.actions;s&&Object.entries(s).forEach(([l,a])=>{Ns(e,l,a)})},Is=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=tt(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Pt({state:e}),e.global.skipMode&&Me({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=jr(e.projectData),delete n.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=T(hn),e.global.overlayStack=[],ht(e),mt(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let l=i;l<=t;l++)l>i&&Nr(e),ad(e,r.timeline[l]),sd(e,r.timeline[l]);let s=gt(n);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},cd=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=n;es(t);let l=t.story.initialSceneId,a=t.story.scenes[l],c=a.initialSectionId,u=a.sections[c],d={sceneId:l,sectionId:c,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:f}=Zt(t),p={...f,...st(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:Su(s,"accountViewedRegistry"),nextLineConfig:yn(),saveSlots:vu(r),overlayStack:[],variables:p,...Hu({loadedGlobalRuntime:i})},contexts:[ys({pointer:d,projectData:t})]}},ld=({state:e})=>e.global.overlayStack||[],ud=({state:e})=>e.global.pendingEffects,As=({state:e})=>e.global.skipMode,dd=({state:e})=>e.global.autoMode,ws=({state:e})=>e.global.dialogueUIHidden,Es=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(!n)return[];let{sectionId:r,lineId:o}=n.pointers.read,i=le({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(d=>d.id===o),l=i.lines.slice(0,s+1),a=[],c={},u=Ct({variables:{...e.global?.variables??{},...bn(e)?.variables??{}},runtime:Ke(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let d of l){let f=d.actions||{};if(c=Ye([c,f]),!f.dialogue)continue;let p=c.dialogue||{},h=Qt({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:u}),g=Au({sectionId:r,lineId:d.id,content:f.dialogue.append===!0?p.content:f.dialogue.content,dialogueState:p,characterName:h});if(f.dialogue.append===!0&&a.length>0){a[a.length-1]={...a[a.length-1],content:g.content,text:g.text,characterId:g.characterId,character:g.character,characterName:g.characterName};continue}a.push(g)}return a},fd=({state:e})=>e.global.confirmDialog??null,Nt=({state:e},{pointer:t}={})=>{let n=t??Ie({state:e})?.pointer,r=zu({state:e,pointer:n});return qu({state:e,form:r.form,pointer:n})},pd=({state:e},{pointer:t}={})=>!!Nt({state:e},{pointer:t}),Ae=({state:e},{pointer:t}={})=>{let n=Nt({state:e},{pointer:t});if(n)return{source:Fe,formId:n.id,formKey:n.key};let r=xs({state:e,pointer:t});return r?{source:ft,resourceId:r}:null},hd=({state:e,registry:t},n)=>{let{sectionId:r,lineId:o}=n,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===r);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let l=le({state:e},{sectionId:r});if(!l||!l.lines||!Array.isArray(l.lines))return s.lastLineId===o;let a=l.lines.findIndex(u=>u.id===s.lastLineId),c=l.lines.findIndex(u=>u.id===o);return a===-1||c===-1?s.lastLineId===o:c<=a},md=({registry:e},t)=>{let{resourceId:n}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===n)},Mr=({state:e},t)=>hd({state:e,registry:e.global.accountViewedRegistry},t),gd=({state:e},t)=>md({registry:e.global.accountViewedRegistry},t),yd=({state:e})=>e.global.nextLineConfig,xs=({state:e,pointer:t}={})=>{let n=t??Ie({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=le({state:e},{sectionId:r})?.lines||[],l=s.findIndex(c=>c.id===o);if(l<0)return;let a;for(let c of s.slice(0,l+1)){let u=c?.actions;if(u?.cleanAll&&(a=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){a=void 0;continue}let d=u.choice;if(d?.resourceId){a=d.resourceId;continue}d?.animations||(a=void 0)}return a},vs=({state:e})=>!!xs({state:e}),bd=({state:e})=>structuredClone(e),Id=({state:e})=>T(e.projectData.resources?.achievements??{}),Ad=({state:e},t)=>{let n=e.projectData.resources?.achievements?.[t?.resourceId];return n===void 0?void 0:T(n)},Cs=({state:e})=>e.global.saveSlots,wd=({state:e},t)=>{let n=t?.slotId,r=Dt(n);return e.global.saveSlots[r]},Br=({state:e})=>Ke(e),Ed=({state:e},t)=>Pe(e,t?.runtimeId),In=({state:e})=>{let t={...e.global?.variables??{},...bn(e)?.variables??{}};return Ct({variables:t,runtime:Ke(e),variableConfigs:e.projectData.resources?.variables??{}})},Ie=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(n)return{currentPointerMode:"read",pointer:n.pointers?.read}},le=({state:e},t)=>{let{sectionId:n}=t;return pt(e.projectData,n).section},An=({state:e})=>{let t=Ie({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=le({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},Ss=({state:e})=>{let{sectionId:t,lineId:n}=Ie({state:e}).pointer,o=le({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n),l=o.slice(0,i+1).map(c=>{let u=c.actions||{},d={};return Object.keys(u).forEach(f=>{d[f]=u[f]}),d});return Ye(l)},xd=e=>{let t=An({state:e})?.actions?.dialogue;if(t?.clear===!0||!Array.isArray(t?.content))return"";let n=In({state:e});return t.content.map(r=>`${at(r?.text,{variables:n})??""}`).join("")},wn=({state:e})=>Wi({text:xd(e),baseDelay:Pe(e,"autoForwardDelay"),speed:Pe(e,"autoForwardSpeed")}),vd=({state:e})=>{let t=_s({state:e}),r=An({state:e})?.actions??{},o=Ye([t??{},r]);return tr(t??{},o??{})},Cd=({state:e},{sectionId:t})=>{let n=le({state:e},{sectionId:t});if(!n?.lines)return[];let r=[],o={};for(let i of n.lines){let s=i.actions||{},l=Ye([o,s]),a=tr(o,l);r.push({id:i.id,changes:a,presentationState:l}),o=nr(l)}return r},Sd=({state:e},{sectionId:t,includePresentationState:n=!1})=>{let r=Cd({state:e},{sectionId:t});return n?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},_s=({state:e})=>{let{sectionId:t,lineId:n}=Ie({state:e}).pointer,o=le({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===n);if(i<=0)return null;let l=o.slice(0,i).map(a=>{let c=a.actions||{},u={};return Object.keys(c).forEach(d=>{u[d]=c[d]}),u});return nr(Ye(l))},Ur=({state:e},{slotsPerPage:t=6}={})=>{let o=((Br({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let l=o+s,a=e.global.saveSlots&&e.global.saveSlots[Dt(l)]||{};i.push({...a,slotId:l})}return{saveSlots:i}},_d=Cs,Rd=Ur,Od=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!n||!Array.isArray(n.timeline)||typeof n.currentIndex!="number"?!1:n.currentIndex>=0&&n.currentIndex<n.timeline.length-1},kd=({state:e},t={})=>{let n=Ss({state:e}),r=_s({state:e}),o=An({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:T(i)}:o,l=i?.animations&&r===null?{}:r,{sectionId:a}=Ie({state:e}).pointer,{sceneId:c}=pt(e.projectData,a),u=Br({state:e}),d=t?.activePersistentAnimations??[],f=t?.restoredPersistentAnimations??[],p=Nt({state:e}),h=vs({state:e}),g=In({state:e}),{saveSlots:b}=Ur({state:e}),A=Od(e);return _i({presentationState:n,previousPresentationState:l,currentLineActions:s,resources:e.projectData.resources,currentSceneId:c,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:js({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||A,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:Es({state:e}),saveSlots:b,variables:g,runtime:u,activePersistentAnimations:d,restoredPersistentAnimations:f})},Ld=({state:e},t)=>(e.global.confirmDialog=Pu(t),e.global.pendingEffects.push({name:"render"}),e),$d=({state:e})=>(e.global.confirmDialog&&(ht(e),e.global.pendingEffects.push({name:"render"})),e),Td=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Se(e,"pushOverlay",t),e),Dd=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Se(e,"popOverlay",void 0),e),Nd=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),Se(e,"replaceLastOverlay",t),e),Pd=({state:e})=>(e.global.overlayStack=[],ht(e),mt(e),e.global.pendingEffects.push({name:"render"}),Se(e,"clearOverlays",void 0),e),Vd=(e,{activeInteraction:t})=>{e.global.autoMode&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),t&&e.global.skipMode&&e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},En=(e,t,{screenTransition:n}={})=>{e.global.isLineCompleted=!1,ju(e,n),mt(e);let r=Ae({state:e},{pointer:t}),o=r?.source===ft,i=r?.source===Fe;return Vd(e,{activeInteraction:r}),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:r}},xn=(e,t,n)=>{!(t?.source===ft||t?.source===Fe)||n||!e.global.skipMode||e.global.pendingEffects.push({name:"startSkipNextTimer"})},Rs=({state:e})=>(Ae({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:wn({state:e})}}),e.global.pendingEffects.push({name:"render"})),e),Pt=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),jd=({state:e})=>{let t=e.global.autoMode;return Ae({state:e})&&!t||(t?Pt({state:e}):Rs({state:e})),e},Os=({state:e})=>(Ae({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),Me=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Fd=({state:e})=>{let t=As({state:e});return Ae({state:e})&&!t||(t?Me({state:e}):Os({state:e})),e},vn=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Se(e,"showDialogueUI",void 0),e),ks=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Se(e,"hideDialogueUI",void 0),e),Md=({state:e})=>(ws({state:e})?vn({state:e}):ks({state:e}),e),Be=(e,t,n)=>(gs(e,t,n),Ku(e),e.global.pendingEffects.push({name:"render"}),e),Vt=(e,t,n,r)=>{let o=gs(e,t,n);return e.global.pendingEffects.push({name:"render"}),Se(e,r,{value:o}),e},Bd=({state:e},t)=>Be(e,"dialogueTextSpeed",t?.value),Ud=({state:e},t)=>Be(e,"autoForwardDelay",t?.value),zd=({state:e},t)=>Be(e,"autoForwardSpeed",t?.value),qd=({state:e},t)=>Be(e,"skipUnseenText",t?.value),Hd=({state:e},t)=>Be(e,"skipTransitionsAndAnimations",t?.value),Wd=({state:e},t)=>Be(e,"soundVolume",t?.value),Yd=({state:e},t)=>Be(e,"musicVolume",t?.value),Gd=({state:e},t)=>Be(e,"muteAll",t?.value),Kd=({state:e},t)=>Vt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),Jd=({state:e})=>{let t=Pe(e,"saveLoadPagination")+1;return Vt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},Xd=({state:e})=>{let t=Pe(e,"saveLoadPagination")-1;return Vt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},Qd=({state:e},t)=>Vt(e,"menuPage",t?.value,"setMenuPage"),Zd=({state:e},t)=>Vt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),ef=({state:e})=>(e.global.pendingEffects=[],e),tf=({state:e},t)=>(e.global.pendingEffects.push(t),e),nf=({state:e},t)=>{let n=t?.resourceId;return Qi(e,n),e.global.pendingEffects.push({name:"completeAchievement",payload:{resourceId:n}}),e},rf=({state:e},t)=>{let n=t?.resourceId,r=Qi(e,n);if(r.type!=="number")throw new Error(`Achievement resource "${n}" does not support numeric progress`);let o=t?.current;if(!Number.isInteger(o)||o<0)throw new Error(`Achievement progress for "${n}" must be a non-negative integer`);if(!Number.isInteger(r.target)||r.target<1)throw new Error(`Achievement resource "${n}" must have a positive integer target`);let i=Math.min(o,r.target);return e.global.pendingEffects.push({name:"setAchievementProgress",payload:{resourceId:n,current:i,target:r.target,completed:i>=r.target}}),e},Ls=(e,{sectionId:t,resetStoryState:n=!1,screen:r})=>{let o=!!us(r),i=le({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(n&&!Qu(e,{queueRender:!o}))return e;let l=Ae({state:e});n&&e.global.skipMode&&Me({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let u=gt(a),d=u.read;n||et(e,{sectionId:d?.sectionId,lineId:d?.lineId}),a.rollback||tt(a,{compatibilityAnchor:!0}),u.read={sectionId:t,lineId:s.id},n?a.rollback=Tt({pointer:u.read}):Fr(e,{sectionId:t,lineId:s.id})}let{activeInteraction:c}=En(e,a?.pointers?.read,{screenTransition:r});return xn(e,l,c),e},of=({state:e},t)=>Ls(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),$s=e=>(e.global.accountViewedRegistry=bu(e.global.accountViewedRegistry),e.global.accountViewedRegistry),zr=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(n=>({scope:n.scope,path:n.path,op:n.op,value:T(n.value)}))}})},Ts=(e,t)=>{zr(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(n=>({sectionId:n.sectionId,...n.lastLineId===void 0?{}:{lineId:n.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},sf=(e,t,{sectionId:n,lineId:r})=>{if(!n||!r)return!1;let o=$(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===n);if(i){if(i.lastLineId===void 0)return!1;let s=le({state:e},{sectionId:n});if(s?.lines){let l=s.lines.findIndex(c=>c.id===i.lastLineId),a=s.lines.findIndex(c=>c.id===r);if(l===-1||a>l)return i.lastLineId===r?!1:(i.lastLineId=r,!0)}else return i.lastLineId===r?!1:(i.lastLineId=r,!0);return!1}else return o.sections.push({sectionId:n,lastLineId:r}),!0},et=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;sf(e,$s(e),t)&&Ts(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},af=({state:e},t)=>(et(e,t),e.global.pendingEffects.push({name:"render"}),e),cf=({state:e},t)=>{let{resourceId:n}=t;if(e.global.accountViewedRegistry!==void 0){let r=$s(e);r.resources.find(i=>i.resourceId===n)||(r.resources.push({resourceId:n}),Ts(e,{sections:[],resources:[{resourceId:n}]}))}return e.global.pendingEffects.push({name:"render"}),e},Ds=({state:e},t)=>{let n=Eu(t.manual),{auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;n&&r?(e.global.nextLineConfig={manual:n,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let a=e.global.nextLineConfig.auto?.enabled,c=Ae({state:e});return!l&&!c&&a===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!l&&a===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),Se(e,"setNextLineConfig",t),e},lf=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:r}=t,o=t?.savedAt,i=Dt(n),s=T(e.contexts);s?.forEach(c=>{gt(c),bs(c.rollback),Cu(c.rollback)});let l={contexts:s},a={formatVersion:Xi,slotId:ts(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:l};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},uf=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=Dt(n),o=e.global.saveSlots[r];if(o){let i=Nu(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=yn(),e.global.overlayStack=[],e.global.isLineCompleted=!0,ht(e),mt(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},df=({state:e},t)=>{let{projectData:n}=t;es(n),e.projectData=n;let r=n?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=Zt(n??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...st(e.global.variables,r)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...st(s.variables,r)})}),ht(e),mt(e),e.global.pendingEffects.push({name:"render"}),e},ff=({state:e},t)=>{let{sectionId:n,lineId:r}=t;if(!r)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=n||o.pointers.read?.sectionId;if(n&&!le({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=le({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(d=>d.id===r))return console.warn(`Line not found: ${r} in section ${i}`),e;let a=Ae({state:e}),c=gt(o);c.read={sectionId:i,lineId:r};let{activeInteraction:u}=En(e,c.read);return xn(e,a,u),e},pf=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return vn({state:e}),e;let n=Ae({state:e});if(n?.source===ft&&t?.bypassChoice!==!0||n?.source===Fe&&t?._interactionSource!==Fe)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=Ie({state:e})?.pointer,d=u?.sectionId,f=u?.lineId;d&&f&&et(e,{sectionId:d,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&!n&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:wn({state:e})}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&!n&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let r=Ie({state:e})?.pointer,o=r?.sectionId,i=le({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],l=i?.lines||[],c=l.findIndex(u=>u.id===r?.lineId)+1;if(c<l.length){let u=l[c],d=!Pe(e,"skipUnseenText");if(e.global.skipMode&&d&&!Mr({state:e},{sectionId:o,lineId:u.id}))return Me({state:e}),e;if(s&&!s.rollback&&tt(s,{compatibilityAnchor:!0}),s){let p=gt(s),h=p.read?.lineId;h&&o&&et(e,{sectionId:o,lineId:h}),p.read={sectionId:o,lineId:u.id}}Fr(e,{sectionId:o,lineId:u.id}),Nr(e);let{activeInteraction:f}=En(e,{sectionId:o,lineId:u.id});xn(e,n,f)}else e.global.autoMode&&Pt({state:e}),e.global.skipMode&&Me({state:e});return e},hf=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ae({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:wn({state:e})}});let n=Ie({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&et(e,{sectionId:r,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},mf=({state:e},t)=>Ls(e,{sectionId:t?.sectionId,screen:t?.screen}),gf=({state:e},t)=>{let n=t?._conditionalContinuation===!0;if(e.global.dialogueUIHidden&&!n)return vn({state:e}),e;let r=Ae({state:e});if(r?.source===ft&&t?.bypassChoice!==!0||r?.source===Fe&&t?._interactionSource!==Fe||r&&r.source!==ft&&r.source!==Fe)return e;let o=Ie({state:e})?.pointer,i=o?.sectionId,s=le({state:e},{sectionId:i}),l=e.contexts[e.contexts.length-1],a=s?.lines||[],u=a.findIndex(d=>d.id===o?.lineId)+1;if(u<a.length){let d=a[u],f=!Pe(e,"skipUnseenText");if(e.global.skipMode&&f&&!Mr({state:e},{sectionId:i,lineId:d.id})&&(Me({state:e}),!n))return e;if(l&&!l.rollback&&tt(l,{compatibilityAnchor:!0}),l){let h=gt(l),g=h.read?.lineId;g&&i&&et(e,{sectionId:i,lineId:g}),h.read={sectionId:i,lineId:d.id}}Fr(e,{sectionId:i,lineId:d.id}),Nr(e);let{activeInteraction:p}=En(e,{sectionId:i,lineId:d.id});xn(e,r,p)}else e.global.autoMode&&Pt({state:e}),e.global.skipMode&&Me({state:e}),e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},qr=(e,t={})=>{let n=Nt({state:e});return!n||t.formKey&&t.formKey!==n.key||t.formId&&t.formId!==n.id?null:n},yf=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let n=e.projectData.resources?.variables?.[t.variableId],r=n?.scope,o=n?.type;if(Ne(n))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(n?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return en(r,t.variableId),tn(o,"set",t.variableId),{variableConfig:n,scope:r}},bf=(e,t)=>({id:e.id,key:e.key,valid:!0,values:T(t),fields:T(e.fields),fieldList:T(e.fieldList)}),If=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ie({state:e})?.pointer,n=t?.sectionId,r=t?.lineId;n&&r&&et(e,{sectionId:n,lineId:r})},Af=({state:e},t={})=>{let n=qr(e,t),r=t.field;if(!n?.fields?.[r])return e;let o=fs(e,n.key),i=mn(t.value),s=n.fields[r],l=Pr(s,i);return o.values[r]=i,o.touched[r]=!0,l?o.errors[r]=l:delete o.errors[r],e.global.pendingEffects.push({name:"render"}),e},wf=({state:e},t={})=>{let n=qr(e,t);if(!n)return{submitted:!1,valid:!1,reason:"inactive"};let r=fs(e,n.key);r.submitted=!0;let o={},i={};if(Object.entries(n.fields).forEach(([d,f])=>{let p=Object.prototype.hasOwnProperty.call(r.values,d)?r.values[d]:f.value,h=Pr(f,p);r.touched[d]=!0,h&&(i[d]=h),o[d]=ds(f,p)}),r.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:T(i),form:{id:n.id,key:n.key,values:T(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let l=!1,a=[],c=[];Object.entries(n.fields).forEach(([d,f])=>{let{scope:p}=yf(e,f),h=p==="context"?s.variables:e.global.variables,g=o[d];h[f.variableId]=nn(h[f.variableId],"set",g),p==="context"&&(l=!0,c.push({variableId:f.variableId,op:"set",value:g})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${f.variableId}`,op:"set",value:T(h[f.variableId])})}),l&&Se(e,"updateVariable",{id:"submitForm",operations:c}),zr(e,a);let u=bf(n,o);return If(e),delete e.global.formDrafts[n.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},Ef=({state:e},t={})=>{let n=qr(e,t);return n?(delete e.global.formDrafts?.[n.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:n.id,key:n.key,values:T(n.values),fields:T(n.fields),fieldList:T(n.fieldList)}}):{cancelled:!1,reason:"inactive"}},xf=({state:e},t)=>{let{id:n,operations:r=[]}=t;if(!n)throw new Error("updateVariable requires an id field");if(typeof n!="string"||!/^[a-zA-Z0-9]+$/.test(n))throw new Error(`updateVariable id must be alphanumeric, got: "${n}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],l=[];return r.forEach(({variableId:a,op:c,value:u,roundTo:d})=>{let f=e.projectData.resources?.variables?.[a],p=f?.scope,h=f?.type;if(Ne(f))throw new Error(`Cannot update computed variable: ${a}`);if(f?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);en(p,a),tn(h,c,a),Zn(h,c,u,a,{roundTo:d});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let b={variableId:a,op:c,value:u};d!==void 0&&(b.roundTo=d),l.push(b)}g[a]=nn(g[a],c,u,{roundTo:d}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:T(g[a])})}),i&&Se(e,"updateVariable",{id:n,operations:l}),zr(e,s),e.global.pendingEffects.push({name:"render"}),e},vf=e=>(t,n)=>e({state:t},n),Cf=e=>({variables:Ct({variables:{...e.global?.variables??{},...bn(e)?.variables??{}},runtime:Ke(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:Ke(e)}),Sf=e=>{if(!$(e))throw new Error("conditional action payload must be an object");if(!Array.isArray(e.branches))throw new Error("conditional action requires branches array");if(e.branches.length===0)throw new Error("conditional action requires at least one branch")},_f=(e,t,n)=>{if(!$(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!$(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==n-1)throw new Error("conditional else branch must be the last branch")},Rf=(e,t)=>{Sf(t);for(let n=0;n<t.branches.length;n+=1){let r=t.branches[n];if(_f(r,n,t.branches.length),!(Object.prototype.hasOwnProperty.call(r,"when")&&!vt(r.when,Cf(e)))){Object.entries(r.actions).forEach(([i,s])=>{Ns(e,i,s)});return}}},Of={conditional:{replayLine:Rf},updateVariable:{recordSources:[Vr],replayLine:Ji,replayRecorded:Ji,persistInSaveSlot:!0},setNextLineConfig:{replayLine:vf(Ds)}},Cn=e=>Of[e]??null,kf=e=>Cn(e)?.persistInSaveSlot===!0,Lf=(e,t)=>{let n=Cn(e)?.recordSources;return Array.isArray(n)&&n.includes(t)},$f=(e,t,n)=>{Cn(t)?.replayRecorded?.(e,n)},Ns=(e,t,n)=>{Cn(t)?.replayLine?.(e,n)},Tf=e=>e?.returnable!==!1,Ps=(e,t)=>{if(t>=0)return e.currentIndex+t;let n=Math.abs(t);for(let r=e.currentIndex-1;r>=0;r-=1)if(Tf(e.timeline[r])&&(n-=1,n===0))return r;return-1},Vs=({state:e},t)=>{let{offset:n}=t;if(n===void 0||typeof n!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let r=e.contexts[e.contexts.length-1];if(!r)return null;let o=r.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=Ps(o,n);if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},js=({state:e})=>Vs({state:e},{offset:-1})!==null,Df=({state:e},t)=>{let{offset:n=-1}=t;if(n>=0)throw new Error("rollbackByOffset requires a negative offset");let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let o=tt(r,{compatibilityAnchor:!r.rollback}),i=Ps(o,n);return i<0||i>=o.timeline.length?e:Is(e,i)},Nf=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=tt(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===n&&a.lineId===r);if(l===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return l===i.currentIndex?e:Is(e,l)},Fs=e=>{let t=cd(e);return Do(t,{selectPendingEffects:ud,selectSkipMode:As,selectAutoMode:dd,selectIsChoiceVisible:vs,selectIsFormVisible:pd,selectActiveInteraction:Ae,selectActiveForm:Nt,selectDialogueUIHidden:ws,selectDialogueHistory:Es,selectConfirmDialog:fd,selectIsLineAccountViewed:Mr,selectIsResourceAccountViewed:gd,selectNextLineConfig:yd,selectSystemState:bd,selectAchievements:Id,selectAchievement:Ad,selectSaveSlotMap:Cs,selectSaveSlots:_d,selectSaveSlot:wd,selectRuntime:Br,selectRuntimeValue:Ed,selectAllVariables:In,selectCurrentPointer:Ie,selectSection:le,selectCurrentLine:An,selectPresentationState:Ss,selectAutoForwardTimerDelay:wn,selectPresentationChanges:vd,selectSectionLineChanges:Sd,selectSaveSlotPage:Ur,selectCurrentPageSlots:Rd,selectRenderState:kd,selectOverlayStack:ld,selectLineIdByOffset:Vs,selectCanRollback:js,selectRollbackCursor:ed,startAutoMode:Rs,stopAutoMode:Pt,toggleAutoMode:jd,startSkipMode:Os,stopSkipMode:Me,toggleSkipMode:Fd,showDialogueUI:vn,hideDialogueUI:ks,toggleDialogueUI:Md,setDialogueTextSpeed:Bd,setAutoForwardDelay:Ud,setAutoForwardSpeed:zd,setSkipUnseenText:qd,setSkipTransitionsAndAnimations:Hd,setSoundVolume:Wd,setMusicVolume:Yd,setMuteAll:Gd,setSaveLoadPagination:Kd,incrementSaveLoadPagination:Jd,decrementSaveLoadPagination:Xd,setMenuPage:Qd,setMenuEntryPoint:Zd,showConfirmDialog:Ld,hideConfirmDialog:$d,resetStoryAtSection:of,clearPendingEffects:ef,appendPendingEffect:tf,completeAchievement:nf,setAchievementProgress:rf,beginRollbackActionBatch:od,endRollbackActionBatch:id,markRollbackCheckpointTransient:td,markSavedRollbackCheckpointTransient:nd,addViewedLine:af,addViewedResource:cf,setNextLineConfig:Ds,saveSlot:lf,loadSlot:uf,updateProjectData:df,sectionTransition:mf,jumpToLine:ff,nextLine:pf,markLineCompleted:hf,rollbackToLine:Nf,rollbackByOffset:Df,pushOverlay:Td,popOverlay:Dd,replaceLastOverlay:Nd,clearOverlays:Pd,updateFormField:Af,submitForm:wf,cancelForm:Ef,updateVariable:xf,nextLineFromSystem:gf},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var Pf="route-engine",Vf="projectPersistence";var Bs=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),ee=e=>Object.prototype.toString.call(e)==="[object Object]",Ms="variables.",jf=(e={})=>{let t=ee(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!ee(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lineId=="string"?{lineId:n.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!ee(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},Ff=(e={})=>{let t=ee(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!ee(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lastLineId=="string"?{lastLineId:n.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!ee(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},Mf=(e,t)=>{let n=Ff(e),r=jf(t),o=n.sections.map(s=>({...s})),i=n.resources.map(s=>({...s}));return r.sections.forEach(s=>{let l=o.find(a=>a.sectionId===s.sectionId);if(!l){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(l.lastLineId!==void 0){if(s.lineId===void 0){delete l.lastLineId;return}l.lastLineId=s.lineId}}),r.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},Us=(e={})=>{let t=ee(e)?e:{};return{saveSlots:ee(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:ee(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:ee(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:ee(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:ee(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Bf=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,n)=>{if(!ee(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${n}] entry.`);let r=t.path?.startsWith(Ms)?t.path.slice(Ms.length):null;if(r!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(r.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${n}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:r}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${n}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${n}].`)})},Uf=(e,t)=>{let n={};return Bf(t).forEach(r=>{if(r.path==="viewedRegistry"){n.accountViewedRegistry=Mf(n.accountViewedRegistry??e.accountViewedRegistry,r.value);return}let o=r.scope==="device"?"globalDeviceVariables":"globalAccountVariables";n[o]={...e[o],...n[o],[r.variableId]:r.value}}),n},Hr=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},zf=e=>{let t=Hr(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},qf=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},Hf=({indexedDB:e,databaseName:t,objectStoreName:n})=>new Promise((r,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(n)||s.createObjectStore(n,{keyPath:"namespace"})},i.onsuccess=()=>{r(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),Wf=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let a=r.transaction(t,"readonly").objectStore(t).get(n);a.onsuccess=()=>{o(a.result??null)},a.onerror=()=>{i(a.error??new Error(`Failed to read persisted namespace "${n}" from IndexedDB.`))}})},jt=async({databasePromise:e,objectStoreName:t,namespace:n,patch:r})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),a=l.objectStore(t),c=a.get(n),u=!1,d=p=>{u||(u=!0,s(p))},f=()=>{u||(u=!0,i())};c.onerror=()=>{d(c.error??new Error(`Failed to read persisted namespace "${n}" before updating IndexedDB.`))},c.onsuccess=()=>{let p=Us(c.result),h=typeof r=="function"?r(p):r,g={namespace:n,version:1,...Bs(),...p,...h},b=a.put(g);b.onerror=()=>{d(b.error??new Error(`Failed to persist namespace "${n}" to IndexedDB.`))}},l.oncomplete=()=>{f()},l.onerror=()=>{d(l.error??new Error(`IndexedDB transaction failed while updating namespace "${n}".`))},l.onabort=()=>{d(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${n}".`))}})},Yf=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let s=r.transaction(t,"readwrite"),a=s.objectStore(t).delete(n),c=!1,u=f=>{c||(c=!0,i(f))},d=()=>{c||(c=!0,o())};a.onerror=()=>{u(a.error??new Error(`Failed to clear persisted namespace "${n}" from IndexedDB.`))},s.oncomplete=()=>{d()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${n}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${n}".`))}})},Wr=(e={})=>{let{indexedDB:t,databaseName:n=Pf,objectStoreName:r=Vf,namespace:o}=e,i=qf(t),s=zf(o),l=Hf({indexedDB:i,databaseName:n,objectStoreName:r});return{namespace:s,load:async()=>{let a=await Wf({databasePromise:l,objectStoreName:r,namespace:s});return{...Bs(),...Us(a)}},clear:async()=>Yf({databasePromise:l,objectStoreName:r,namespace:s}),saveSlots:async a=>jt({databasePromise:l,objectStoreName:r,namespace:s,patch:{saveSlots:ee(a)?a:{}}}),saveGlobalDeviceVariables:async a=>jt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:ee(a)?a:{}}}),saveGlobalAccountVariables:async a=>jt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalAccountVariables:ee(a)?a:{}}}),saveGlobalRuntime:async a=>jt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalRuntime:ee(a)?a:{}}}),applyScopedDataUpdates:async a=>jt({databasePromise:l,objectStoreName:r,namespace:s,patch:c=>Uf(c,a)})}},Gf=Wr;var Kf=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Jf=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),zs="conditional",Kr=Symbol("conditionalAutoContinue"),Xf=new Set(["sectionTransition","resetStoryAtSection"]),Qf=new Set(["nextLine","nextLineFromSystem","resetStoryAtSection","sectionTransition"]),Zf=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),Yr="form",ep=new Set(["submitForm","cancelForm"]),Ft=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Sn=e=>e?.type===Kr,Gr=(e,t)=>e?.sectionId===t?.sectionId&&e?.lineId===t?.lineId;function Jr(e){let t,n=0,r=null,o=0,i=!1,s=0,l=[],a=null,c=new Map,u=new Map,d=new Map,{handlePendingEffects:f}=e,p=(y=new Map,I=Date.now())=>new Map(Array.from(y.entries()).filter(([,x])=>I<x.expiresAt).map(([x,_])=>[x,{animation:structuredClone(_.animation),startedAt:_.startedAt,expiresAt:_.expiresAt}])),h=(y=new Map)=>Array.from(y.values()).map(I=>structuredClone(I.animation)),g=(y=Date.now())=>{c=new Map(Array.from(c.entries()).filter(([,I])=>y<I.expiresAt))},b=()=>{if(!(o>0||i)){i=!0;try{for(;t.selectPendingEffects().length>0;){let y=[...t.selectPendingEffects()];t.clearPendingEffects();try{f(y)}catch(I){throw t.clearPendingEffects(),y.forEach(x=>{t.appendPendingEffect(x)}),I}}}finally{i=!1}}},A=y=>{o+=1;try{return y()}finally{o-=1,b()}},w=({initialState:y,namespace:I})=>{t=Fs(y),n=0,r=Hr(I),o=0,i=!1,s=0,l=[],a=null,c=new Map,u=new Map,d=new Map,t.appendPendingEffect({name:"handleLineActions"}),b()},C=()=>r,R=()=>t.selectPresentationState(),V=()=>t.selectPresentationChanges(),j=y=>t.selectSectionLineChanges(y),E=(y={})=>{n+=1;let I=Date.now();g(I);let x=u.size>0,_=p(c,I),D=x?p(u,I):new Map,q={...t.selectRenderState({activePersistentAnimations:h(_),restoredPersistentAnimations:h(D)}),id:`render-${n}`};return d.set(q.id,{builtAt:I,persistentAnimationSessions:new Map([...D.entries(),..._.entries()]),usedRestoredPersistentAnimationSessions:x}),q},B=(y={})=>E(y),U=(y={})=>E(y),J=y=>{let I=typeof y?.id=="string"&&y.id.length>0?y.id:null,x=I?d.get(I):null;I&&d.delete(I);let _=new Map;di(y?.animations).forEach(D=>{let H=ln(D);if(!H)return;let q=x?.persistentAnimationSessions?.get(H)??c.get(H),rt=Math.max(0,pi(D)),yt=q?.startedAt??x?.builtAt??Date.now();_.set(H,{animation:structuredClone(D),startedAt:yt,expiresAt:yt+rt})}),c=_,x?.usedRestoredPersistentAnimationSessions&&(u=new Map)},M=()=>t.selectSystemState(),Y=()=>t.selectAchievements(),G=y=>t.selectAchievement(y),X=()=>t.selectSaveSlotMap(),ve=y=>t.selectSaveSlot(y),te=y=>t.selectSaveSlotPage(y),ne=()=>t.selectSkipMode(),ue=()=>t.selectAutoMode(),de=()=>t.selectRuntime(),Q=()=>t.selectIsChoiceVisible(),re=()=>t.selectIsFormVisible(),fe=()=>t.selectActiveInteraction(),S=()=>t.selectPendingEffects().some(y=>y?.name==="handleLineActions"||y?.name==="render"),O=(y,I,x={})=>!Ft(I)||y!=="nextLine"?I:x.bypassChoice===!0?{...I,bypassChoice:!0}:x.interactionSource===Yr?{...I,_interactionSource:Yr}:I,F=(y={})=>({type:Kr,payload:O("nextLine",{_conditionalContinuation:!0},y)}),oe=(y,I)=>Sn(y)?{type:Kr,payload:{...y.payload,...I.payload}}:I,ie=y=>{y.savedCheckpointOccurrences.forEach(I=>{t.markSavedRollbackCheckpointTransient(I)}),y.savedCheckpointOccurrences=[]},z=(y,I)=>{let x=a;return a=null,!x||!Gr(x.pointer,y)||x.checkpointIndex!==I?.checkpointIndex||x.checkpointIdentity!==I?.checkpoint?[]:x.savedCheckpointOccurrences},Le=y=>{y.markCurrentCheckpointTransient&&(t.markRollbackCheckpointTransient({checkpointIndex:y.rollbackCursor?.checkpointIndex,checkpointIdentity:y.rollbackCursor?.checkpoint,sectionId:y.pointer?.sectionId,lineId:y.pointer?.lineId}),ie(y))},nt=(y,I,x)=>Qf.has(y)?y==="resetStoryAtSection"?x?.checkpoint!==I?.checkpoint:x?.checkpoint!==I?.checkpoint&&x?.checkpointIndex>I?.checkpointIndex:!1,Ws=y=>{let I=l.at(-1);if(!I?.markCurrentCheckpointTransient)return;let x=t.selectSaveSlot({slotId:y?.slotId});x&&I.savedCheckpointOccurrences.push({slotId:y.slotId,saveSlotIdentity:x,checkpointIndex:I.rollbackCursor?.checkpointIndex,sectionId:I.pointer?.sectionId,lineId:I.pointer?.lineId})},Ys=(y,I,x)=>{let _=l.at(-1);if(!_)return;let D=t.selectCurrentPointer()?.pointer,H=nt(y,I,x);if(Gr(_.pointer,D)){let q=x?.checkpoint!==I?.checkpoint||x?.checkpointIndex!==I?.checkpointIndex;(H||q&&Zf.has(y))&&(Le(_),_.pointer=D,_.rollbackCursor=x,_.markCurrentCheckpointTransient=H,_.savedCheckpointOccurrences=[]);return}Le(_),_.pointer=D,_.rollbackCursor=t.selectRollbackCursor?.()??null,_.markCurrentCheckpointTransient=H,_.savedCheckpointOccurrences=[]},Mt=(y,I)=>{if(!t[y])return;Xf.has(y)&&(s+=1),Kf.has(y)&&(Jf.has(y)?u=p(c):u=new Map,c=new Map);let x=t.selectRollbackCursor?.()??null,_=t[y](I),D=t.selectRollbackCursor?.()??null;return y==="saveSlot"&&Ws(I),Ys(y,x,D),b(),_},Gs=(y,I,x)=>{let _=t.selectCurrentPointer()?.pointer;I!==_||x!==s||(t.appendPendingEffect({name:"clearAutoNextTimer"}),t.appendPendingEffect({name:"clearNextLineConfigTimer"}),Mt("nextLineFromSystem",y.payload))},Qr=(y,I={})=>A(()=>{let x,_=t.selectCurrentPointer()?.pointer??null,D=t.selectRollbackCursor?.()??null,H=s,q={pointer:_,rollbackCursor:D,markCurrentCheckpointTransient:I.rollbackSource==="line",savedCheckpointOccurrences:I.savedCheckpointOccurrences?.slice()??[]};l.push(q);try{t.beginRollbackActionBatch({source:I.rollbackSource});try{x=y()}finally{t.endRollbackActionBatch({})}Sn(x)&&Gs(x,_,H)}finally{l.pop(),(!Gr(_,q.pointer)||D?.checkpoint!==q.rollbackCursor?.checkpoint)&&q.markCurrentCheckpointTransient&&q.savedCheckpointOccurrences.length>0&&(a={pointer:q.pointer,checkpointIndex:q.rollbackCursor?.checkpointIndex,checkpointIdentity:q.rollbackCursor?.checkpoint,savedCheckpointOccurrences:q.savedCheckpointOccurrences})}}),Zr=(y,I,x,_={})=>{if(y===zs)return Qr(()=>{let D=Rn(x),H=rr({[y]:I},D);return eo(H[y],x,_)},_);Mt(y,I)},Ks=(y,I)=>{Zr(y,I)},Rn=y=>{if(!y)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(y,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:I,...x}=y,_=t.selectAllVariables?t.selectAllVariables():void 0;return{...x,_event:I,variables:_,runtime:t.selectRuntime?t.selectRuntime():{}}},Js=y=>{if(!Ft(y))throw new Error("conditional action payload must be an object");if(!Array.isArray(y.branches))throw new Error("conditional action requires branches array");if(y.branches.length===0)throw new Error("conditional action requires at least one branch")},Xs=(y,I,x)=>{if(!Ft(y))throw new Error(`conditional branch at index ${I} must be an object`);if(!Ft(y.actions))throw new Error(`conditional branch at index ${I} requires actions object`);if(!Object.prototype.hasOwnProperty.call(y,"when")&&I!==x-1)throw new Error("conditional else branch must be the last branch")},eo=(y,I,x)=>{Js(y);let _=F(x);for(let D=0;D<y.branches.length;D+=1){let H=y.branches[D];Xs(H,D,y.branches.length);let q=Rn(I);if(Object.prototype.hasOwnProperty.call(H,"when")&&!vt(H.when,q))continue;let yt=On(H.actions,I,x);return Sn(yt)?oe(_,yt):_}return _},Qs=(y,I)=>({...y??{},_form:I}),Zs=(y,I,x,_)=>{let D=Mt(y,I),H=D?.submitted===!0&&D.valid===!0,q=D?.cancelled===!0;if(!(!H&&!q)&&Ft(I.actions))return On(I.actions,Qs(x,D.form),{..._,interactionSource:Yr})},ea=(y,I,x,_)=>{let D=Rn(x),q=rr({[y]:I},D)[y];if(y===zs)return eo(q,x,_);let rt=O(y,q,_);if(ep.has(y))return Zs(y,rt,x,_);Mt(y,rt)},On=(y,I,x)=>{let _;return Object.entries(y).forEach(([D,H])=>{let q=ea(D,H,I,x);Sn(q)&&(_=oe(_,q))}),_},to=(y,I,x={})=>Qr(()=>On(y,I,x),x),ta=y=>{let I=t.selectCurrentPointer()?.pointer;if(y!==I||t.selectActiveInteraction())return;let x=t.selectNextLineConfig();x?.auto?.enabled&&x.auto.trigger==="fromStart"&&t.appendPendingEffect({name:"nextLineConfigTimer",payload:{delay:x.auto.delay}})};return{init:w,handleAction:Zr,handleInternalAction:Ks,handleActions:to,selectRenderState:B,prepareRenderState:U,commitRenderState:J,selectPresentationState:R,selectPresentationChanges:V,selectSectionLineChanges:j,selectSystemState:M,selectAchievements:Y,selectAchievement:G,selectSaveSlotMap:X,selectSaveSlot:ve,selectSaveSlotPage:te,selectSaveSlots:X,selectRuntime:de,selectIsChoiceVisible:Q,selectIsFormVisible:re,selectActiveInteraction:fe,selectHasPendingRenderWork:S,handleLineActions:()=>A(()=>{let y=t.selectCurrentPointer()?.pointer,I=t.selectRollbackCursor?.()??null,x=z(y,I),_=t.selectCurrentLine(),D=!1;return _?.actions&&(to(_.actions,void 0,{rollbackSource:"line",savedCheckpointOccurrences:x}),D=!0),ta(y),D}),getNamespace:C}}var Xr=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},tp=80,Hs=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{if(e.selectHasPendingRenderWork?.())return;let o=e.prepareRenderState?.(r)??e.selectRenderState(r);n?.(o),t.render(o),e.commitRenderState?.(o)},np=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&Hs({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},rp=({engine:e,ticker:t,autoTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(t.remove(i),n.setCallback(null),n.setElapsed(0),_n(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},op=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},ip=({engine:e,ticker:t,skipTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r?.delay??tp;n.getElapsed()>=l&&(n.setElapsed(0),_n(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},sp=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},ap=({engine:e,ticker:t,nextLineConfigTimerState:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(n.setElapsed(0),_n(e,"nextLineFromSystem",{}),t.remove(i),n.getCallback()===i&&n.setCallback(null))};n.setCallback(i),t.add(i)},cp=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},lp=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveSlots(t?.saveSlots))},up=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalDeviceVariables(t?.globalDeviceVariables))},dp=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalAccountVariables(t?.globalAccountVariables))},fp=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalRuntime(t?.globalRuntime))},pp=({enqueuePersistenceWrite:e},t)=>{e(n=>{if(typeof n.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return n.applyScopedDataUpdates(t?.updates)})},qs={render:Hs,saveSlots:lp,saveGlobalDeviceVariables:up,saveGlobalAccountVariables:dp,saveGlobalRuntime:fp,applyScopedDataUpdates:pp,handleLineActions:np,startAutoNextTimer:rp,clearAutoNextTimer:op,startSkipNextTimer:ip,clearSkipNextTimer:sp,nextLineConfigTimer:ap,clearNextLineConfigTimer:cp},hp=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),_n=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},mp=(e=[])=>{let t=new Set,n=[];for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!hp.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},gp=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let a=Xr(),c=Xr(),u=Xr(),d=s??null,f=Promise.resolve(),p=null,h=null,g=!1,b=0,A=S=>{if(o){o(S);return}console.error("RouteEngine persistence write failed.",S)},w=()=>{if(d)return d;let S=e();return d=Wr({indexedDB:i,namespace:l??S?.getNamespace?.()}),d},C=S=>{f=f.catch(()=>{}).then(()=>{let O=w();return S(O)}).catch(O=>{A(O)})},R=S=>{let O=typeof S?.id=="string"&&S.id.length>0?S.id:null;b+=1,p=O,g=!1},V=()=>b,j=(S={})=>{if(S?.aborted===!0)return!1;let O=typeof S?.id=="string"&&S.id.length>0?S.id:null;return O?O!==p||O===h?!1:(h=O,!0):p!==null||g?!1:(g=!0,!0)},E=(S,O={})=>{if(S!=="renderComplete"||!j(O))return!1;let F=e();return _n(F,"markLineCompleted",{}),!0},B=new Set(["updateFormField","submitForm","cancelForm"]),U=new Set(["updateVariable"]),J=S=>typeof S?.selectActiveInteraction=="function"?S.selectActiveInteraction():typeof S?.selectIsChoiceVisible=="function"&&S.selectIsChoiceVisible()?{source:"choice"}:null,M=S=>S?._formKey??S?.formKey,Y=(S,O)=>M(S)===O?.formKey,G=(S,O)=>!S||typeof S!="object"||Array.isArray(S)?!1:S._interactionSource===O?.source,X=(S,O)=>G(S,O)?O.source==="form"?Y(S,O):!0:!1,ve=(S,O)=>!S||typeof S!="object"||Array.isArray(S)||O?.source!=="form"?!1:Y(S,O),te=(S={})=>Object.keys(S).some(O=>B.has(O)),ne=(S={},O)=>Object.entries(S).some(([F,oe])=>B.has(F)&&ve(oe,O)),ue=(S={})=>Object.keys(S).length>0&&Object.keys(S).every(O=>U.has(O)),de=(S={},O)=>{let F=S?.actions;return O?.source==="form"?!F||typeof F!="object"||Array.isArray(F)?!1:ne(F,O)?!0:te(F)?!1:ue(F):X(S,O)?!0:!F||typeof F!="object"||Array.isArray(F)?!1:Object.values(F).some(oe=>X(oe,O))},Q=(S,O={})=>{if(!O?.actions)return!1;let F=J(S);return!F||F.source==="choice"?!1:!de(O,F)},re=({preprocessPayload:S,onEvent:O}={})=>async(F,oe={})=>{let ie=e();if(Q(ie,oe))return O?.(F,oe);let z=await S?.(F,oe)??oe;if(Q(ie,z))return O?.(F,z);if(E(F,z),z?.actions){let Le=z?._event?{_event:z._event}:z?.event?{_event:z.event}:void 0,nt;z?.bypassChoice===!0?nt={bypassChoice:!0}:z?._interactionSource&&(nt={interactionSource:z._interactionSource}),nt?ie.handleActions(z.actions,Le,nt):ie.handleActions(z.actions,Le)}return O?.(F,z)},fe=S=>{let O=e(),F=mp(S),oe=F.some(z=>z.name==="handleLineActions");F.forEach(z=>{if(!qs[z.name]&&!r)throw new Error(`Unhandled pending effect "${z.name}".`)});let ie={engine:O,routeGraphics:t,ticker:n,autoTimer:a,skipTimer:c,nextLineConfigTimerState:u,trackRenderDispatch:R,getRenderDispatchCount:V,enqueuePersistenceWrite:C};for(let z of F){if(oe&&z.name==="render")continue;let Le=qs[z.name];if(Le){Le(ie,z.payload);continue}r(z,ie)}};return fe.handleRouteGraphicsEvent=E,fe.createRouteGraphicsEventHandler=re,fe},yp=gp;var bp=(e,t={})=>{let{resources:n={}}=t;return Rr(e,n)};var Jh=Jr;export{ar as DEFAULT_VISUAL_LAYER,ct as RENDER_LAYER,_e as VISUAL_LAYER,yp as createEffectsHandler,Gf as createIndexedDbPersistence,Jh as default,er as formatDate,uc as resolveComputedVariables,bp as resolveLayoutReferences};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "route-engine-js",
3
- "version": "1.31.0",
3
+ "version": "1.31.2",
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",
@@ -59,7 +59,7 @@
59
59
  "ajv": "^8.18.0",
60
60
  "husky": "^9.1.7",
61
61
  "prettier": "^3.7.4",
62
- "route-graphics": "1.25.1",
62
+ "route-graphics": "1.30.0",
63
63
  "vitest": "4.0.16"
64
64
  }
65
65
  }