route-engine-js 1.32.1 → 1.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- var Wa=Object.defineProperty;var Ka=(e,t)=>{for(var r in t)Wa(e,r,{get:t[r],enumerable:!0})};var To=Symbol.for("immer-nothing"),Oo=Symbol.for("immer-draftable"),pe=Symbol.for("immer-state");function Ie(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var lt=Object.getPrototypeOf;function se(e){return!!e&&!!e[pe]}function We(e){return e?No(e)||Array.isArray(e)||!!e[Oo]||!!e.constructor?.[Oo]||Zt(e)||er(e):!1}var Ja=Object.prototype.constructor.toString();function No(e){if(!e||typeof e!="object")return!1;let t=lt(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===Ja}function Hr(e){return se(e)||Ie(15,e),e[pe].base_}function Kt(e,t){Qt(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function Qt(e){let t=e[pe];return t?t.type_:Array.isArray(e)?1:Zt(e)?2:er(e)?3:0}function Ur(e,t){return Qt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Po(e,t,r){let n=Qt(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function Xa(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Zt(e){return e instanceof Map}function er(e){return e instanceof Set}function He(e){return e.copy_||e.base_}function Br(e,t){if(Zt(e))return new Map(e);if(er(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=No(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[pe];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],l=n[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(n[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(lt(e),n)}else{let n=lt(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function Wr(e,t=!1){return tr(e)||se(e)||!We(e)||(Qt(e)>1&&(e.set=e.add=e.clear=e.delete=Qa),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>Wr(n,!0))),e}function Qa(){Ie(2)}function tr(e){return Object.isFrozen(e)}var Za={};function Ke(e){let t=Za[e];return t||Ie(0,e),t}var xt;function Do(){return xt}function ec(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Ro(e,t){t&&(Ke("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Gr(e){zr(e),e.drafts_.forEach(tc),e.drafts_=null}function zr(e){e===xt&&(xt=e.parent_)}function $o(e){return xt=ec(xt,e)}function tc(e){let t=e[pe];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function ko(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[pe].modified_&&(Gr(t),Ie(4)),We(e)&&(e=Jt(t,e),t.parent_||Xt(t,e)),t.patches_&&Ke("Patches").generateReplacementPatches_(r[pe].base_,e,t.patches_,t.inversePatches_)):e=Jt(t,r,[]),Gr(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==To?e:void 0}function Jt(e,t,r){if(tr(t))return t;let n=t[pe];if(!n)return Kt(t,(o,i)=>Lo(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return Xt(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let o=n.copy_,i=o,s=!1;n.type_===3&&(i=new Set(o),o.clear(),s=!0),Kt(i,(l,a)=>Lo(e,n,o,l,a,r,s)),Xt(e,o,!1),r&&e.patches_&&Ke("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function Lo(e,t,r,n,o,i,s){if(se(o)){let l=i&&t&&t.type_!==3&&!Ur(t.assigned_,n)?i.concat(n):void 0,a=Jt(e,o,l);if(Po(r,n,a),se(a))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(We(o)&&!tr(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Jt(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&Xt(e,o)}}function Xt(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Wr(t,r)}function rc(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:Do(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=Kr;r&&(o=[n],i=vt);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return n.draft_=l,n.revoke_=s,l}var Kr={get(e,t){if(t===pe)return e;let r=He(e);if(!Ur(r,t))return nc(e,r,t);let n=r[t];return e.finalized_||!We(n)?n:n===Mr(e.base_,t)?(Fr(e),e.copy_[t]=Yr(n,e)):n},has(e,t){return t in He(e)},ownKeys(e){return Reflect.ownKeys(He(e))},set(e,t,r){let n=Vo(He(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=Mr(He(e),t),i=o?.[pe];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(Xa(r,o)&&(r!==void 0||Ur(e.base_,t)))return!0;Fr(e),qr(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return Mr(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Fr(e),qr(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=He(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){Ie(11)},getPrototypeOf(e){return lt(e.base_)},setPrototypeOf(){Ie(12)}},vt={};Kt(Kr,(e,t)=>{vt[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});vt.deleteProperty=function(e,t){return vt.set.call(this,e,t,void 0)};vt.set=function(e,t,r){return Kr.set.call(this,e[0],t,r,e[0])};function Mr(e,t){let r=e[pe];return(r?He(r):e)[t]}function nc(e,t,r){let n=Vo(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function Vo(e,t){if(!(t in e))return;let r=lt(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=lt(r)}}function qr(e){e.modified_||(e.modified_=!0,e.parent_&&qr(e.parent_))}function Fr(e){e.copy_||(e.copy_=Br(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var oc=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,n)=>{if(typeof t=="function"&&typeof r!="function"){let i=r;r=t;let s=this;return function(a=i,...c){return s.produce(a,u=>r.call(this,u,...c))}}typeof r!="function"&&Ie(6),n!==void 0&&typeof n!="function"&&Ie(7);let o;if(We(t)){let i=$o(this),s=Yr(t,void 0),l=!0;try{o=r(s),l=!1}finally{l?Gr(i):zr(i)}return Ro(i,n),ko(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===To&&(o=void 0),this.autoFreeze_&&Wr(o,!0),n){let i=[],s=[];Ke("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else Ie(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,a=>t(a,...l));let n,o;return[this.produce(t,r,(s,l)=>{n=s,o=l}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){We(e)||Ie(8),se(e)&&(e=Je(e));let t=$o(this),r=Yr(e,void 0);return r[pe].isManual_=!0,zr(t),r}finishDraft(e,t){let r=e&&e[pe];(!r||!r.isManual_)&&Ie(9);let{scope_:n}=r;return Ro(n,t),ko(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let o=t[r];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}r>-1&&(t=t.slice(r+1));let n=Ke("Patches").applyPatches_;return se(e)?n(e,t):this.produce(e,o=>n(o,t))}};function Yr(e,t){let r=Zt(e)?Ke("MapSet").proxyMap_(e,t):er(e)?Ke("MapSet").proxySet_(e,t):rc(e,t);return(t?t.scope_:Do()).drafts_.push(r),r}function Je(e){return se(e)||Ie(10,e),jo(e)}function jo(e){if(!We(e)||tr(e))return e;let t=e[pe],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=Br(e,t.scope_.immer_.useStrictShallowCopy_)}else r=Br(e,!0);return Kt(r,(n,o)=>{Po(r,n,jo(o))}),t&&(t.finalized_=!1),r}var ye=new oc,Jr=ye.produce,Th=ye.produceWithPatches.bind(ye),Nh=ye.setAutoFreeze.bind(ye),Ph=ye.setUseStrictShallowCopy.bind(ye),Dh=ye.applyPatches.bind(ye),Vh=ye.createDraft.bind(ye),jh=ye.finishDraft.bind(ye);var y={LITERAL:0,VARIABLE:1,INTERPOLATION:2,FUNCTION:3,BINARY:4,UNARY:5,CONDITIONAL:6,LOOP:7,OBJECT:8,ARRAY:9,PARTIAL:10,PATH_REFERENCE:11},L={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},ut={NOT:0};var C=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},ue=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Xr=e=>{if(!e||e.trim()==="")throw new C("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new C(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${r}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let r of t)if(e.trim().endsWith(r))throw new C(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Mo=e=>{if(e.trim().endsWith(" in"))throw new C(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new C(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new C(`Missing iterable expression after 'in' (got: '$for ${e}')`);let n=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of n){if(!o)throw new C(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new C(`Invalid loop syntax (got: '$for ${e}')`)}};var Fo=(e,t,r=!1)=>{if(t===null)return new ue(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new ue(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new ue(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new ue(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},Uo=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new ue(`Unknown function '${e}' (${r})`)};var ic=(e,t,r={})=>{let n={},o={};r&&typeof r=="object"&&(r.functions!==void 0||r.partials!==void 0?(n=r.functions||{},o=r.partials||{}):typeof r=="object"&&(n=r));let s=V(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},V=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return J(e.var,r,n);if(e.type===y.LITERAL)return e.value;if(e.type===y.VARIABLE)return J(e.path,r,n);if(e.type===y.INTERPOLATION)return ac(e.parts,t,r,n);switch(e.type){case y.FUNCTION:return Go(e,t,r,n);case y.BINARY:return zo(e,t,r,n);case y.UNARY:return qo(e,t,r,n);case y.CONDITIONAL:return lc(e,t,r,n);case y.LOOP:return hc(e,t,r,n);case y.OBJECT:return gc(e,t,r,n);case y.ARRAY:return yc(e,t,r,n);case y.PARTIAL:return bc(e,t,r,n);case y.PATH_REFERENCE:return Ic(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Bo=new Map,sc=e=>{let t=[],r="",n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")r&&(t.push({type:"property",value:r}),r=""),n=!0;else if(i==="]"){if(n&&r){let s=r.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let l=s.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},J=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=Bo.get(e);if(!n){let i=[],s="",l=0;for(let a=0;a<e.length;a++){let c=e[a];c==="["?(l++,s+=c):c==="]"?(l--,s+=c):c==="."&&l===0?s&&(i.push(s),s=""):s+=c}s&&i.push(s),n=[];for(let a of i){let c=sc(a.trim());n.push(...c)}Bo.set(e,n)}let o=t;for(let i=0;i<n.length;i++){let s=n[i];if(s.type==="property"&&s.value in r){o=r[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},ac=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=V(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},Go=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Uo(e.name,o);let s=e.args.map(l=>V(l,t,r,n));return i(...s)},Pe=(e,t,r,n)=>{if(e.var&&!e.type)return J(e.var,r,n);switch(e.type){case y.VARIABLE:return J(e.path,r,n);case y.LITERAL:return e.value;case y.BINARY:return zo(e,t,r,n);case y.UNARY:return qo(e,t,r,n);case y.FUNCTION:return Go(e,t,r,n);default:return V(e,t,r,n)}},zo=(e,t,r,n)=>{if(e.op===L.AND||e.op===L.OR){let s=Pe(e.left,t,r,n),l=Pe(e.right,t,r,n);switch(e.op){case L.AND:return s&&l;case L.OR:return s||l}}let o=V(e.left,t,r,n),i=V(e.right,t,r,n);switch(e.op){case L.EQ:return o==i;case L.NEQ:return o!=i;case L.GT:return o>i;case L.LT:return o<i;case L.GTE:return o>=i;case L.LTE:return o<=i;case L.IN:return Array.isArray(i)?i.includes(o):!1;case L.ADD:if(typeof o!="number"||typeof i!="number")throw new ue(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case L.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new ue(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},qo=(e,t,r,n)=>{let o=e.op===ut.NOT?Pe(e.operand,t,r,n):V(e.operand,t,r,n);if(e.op===ut.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},cc=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===y.VARIABLE)if(J(o.path,r,n)){let s=e.bodies[0];if(s.type===y.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?V(a.parsedKey,t,r,n):a.key,u=a.value;if(u.type===y.LITERAL)l[c]=u.value;else if(u.type===y.VARIABLE)l[c]=J(u.path,r,n);else if(u.type===y.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===y.VARIABLE){let p=J(f.path,r,n);d.push(p!=null?String(p):"")}else{let p=V(f,t,r,n);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=V(u,t,r,n)}return l}}else{let s=e.bodies[1];if(s.type===y.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?V(a.parsedKey,t,r,n):a.key,u=a.value;if(u.type===y.LITERAL)l[c]=u.value;else if(u.type===y.VARIABLE)l[c]=J(u.path,r,n);else if(u.type===y.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===y.VARIABLE){let p=J(f.path,r,n);d.push(p!=null?String(p):"")}else{let p=V(f,t,r,n);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=V(u,t,r,n)}return l}}}return null},lc=(e,t,r,n)=>{let o=cc(e,t,r,n);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||Pe(s,t,r,n))return V(e.bodies[i],t,r,n)}return Yo},uc=(e,t)=>{let r=e.body,n=e.itemVar;if(r.type===y.CONDITIONAL&&r.conditions.length===1&&r.conditions[0].type===y.VARIABLE){let o=r.conditions[0].path,i=r.bodies[0];if(o.startsWith(n+".")){let s=o.substring(n.length+1);if(i.type===y.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===y.LITERAL)u[f]=p.value;else if(p.type===y.VARIABLE){let h=p.path;if(h===n)u[f]=c;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);u[f]=c[g]}else return null}else if(p.type===y.INTERPOLATION){let h=[],g=!0;for(let I of p.parts)if(typeof I=="string")h.push(I);else if(I.type===y.VARIABLE){let b=I.path;if(b===n)h.push(c!=null?String(c):"");else if(b.startsWith(n+".")){let w=b.substring(n.length+1),S=c[w];h.push(S!=null?String(S):"")}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},dc=(e,t)=>{let r=e.body,n=e.itemVar,o=uc(e,t);if(o!==null)return o;if(r.type===y.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let l of r.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of r.properties){let a=l.key,c=l.value;if(c.type===y.LITERAL)i.push({key:a,type:"literal",value:c.value});else if(c.type===y.VARIABLE){let u=c.path;if(u===n)i.push({key:a,type:"item"});else if(u.startsWith(n+".")){let d=u.substring(n.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:a,type:"prop",prop:d});else{s=!1;break}}else{s=!1;break}}else if(c.type===y.INTERPOLATION&&c.parts.length===1){let u=c.parts[0];if(u.type===y.VARIABLE){let d=u.path;if(d===n)i.push({key:a,type:"item_string"});else if(d.startsWith(n+".")){let f=d.substring(n.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:a,type:"prop_string",prop:f});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let l=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let a=0;a<t.length;a++){let c=t[a];l[a]={id:c.id,title:c.title!=null?String(c.title):"",completed:c.completed}}else for(let a=0;a<t.length;a++){let c=t[a],u={};for(let d of i)if(d.type==="literal")u[d.key]=d.value;else if(d.type==="item")u[d.key]=c;else if(d.type==="prop")u[d.key]=c[d.prop];else if(d.type==="item_string")u[d.key]=c!=null?String(c):"";else if(d.type==="prop_string"){let f=c[d.prop];u[d.key]=f!=null?String(f):""}l[a]=u}return l}}return null},fc=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===y.OBJECT&&s.fast!==!1){let l=e.itemVar,a=e.indexVar;for(let c=0;c<o.length;c++){let u=o[c],d={},f={...n,[l]:u,...a&&{[a]:c}};f.__paths__||(f.__paths__=n.__paths__||{});let p=e.iterable.path||"";if(n&&n.__paths__&&p){let h=p.split("."),g=h[0];g in n.__paths__&&(p=n.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}f.__paths__={...f.__paths__,[l]:`${p}[${c}]`,...a&&{[a]:c}};for(let h of s.properties){let g=h.parsedKey?V(h.parsedKey,t,r,f):h.key,I=h.value;if(I.type===y.LITERAL)d[g]=I.value;else if(I.type===y.VARIABLE){let b=I.path;if(b===l)d[g]=u;else if(b===a)d[g]=c;else if(b.startsWith(l+".")){let w=b.substring(l.length+1);!w.includes(".")&&!w.includes("[")?d[g]=u[w]:d[g]=J(b,r,{...n,[l]:u,...a&&{[a]:c}})}else d[g]=J(b,r,{...n,[l]:u,...a&&{[a]:c}})}else if(I.type===y.INTERPOLATION){let b=[];for(let w of I.parts)if(typeof w=="string")b.push(w);else if(w.type===y.VARIABLE){let S=w.path,O;if(S===l)O=u;else if(S===a)O=c;else if(S.startsWith(l+".")){let $=S.substring(l.length+1);!$.includes(".")&&!$.includes("[")?O=u[$]:O=J(S,r,{...n,[l]:u,...a&&{[a]:c}})}else O=J(S,r,{...n,[l]:u,...a&&{[a]:c}});b.push(O!=null?String(O):"")}else{let S={...n,[l]:u,...a&&{[a]:c}},O=V(w,t,r,S);b.push(O!=null?String(O):"")}d[g]=b.join("")}else{let b={...n,[l]:u,...a&&{[a]:c}};d[g]=V(I,t,r,b)}}i.push(d)}return i}return null},pc=(e,t,r)=>{let n=e.body;if(n.type===y.OBJECT&&n.properties.length===1&&n.properties[0].key==="$if item.visible"){let i=n.properties[0].value;if(i.type===y.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===y.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===y.OBJECT&&s.properties.length===2){let l=s.properties[0],a=s.properties[1];if(l.key==="id"&&l.value.type===y.VARIABLE&&l.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===y.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},hc=(e,t,r,n)=>{let o=V(e.iterable,t,r,n);if(!Array.isArray(o)){let c,u=!1;if(e.iterable.type===y.FUNCTION){u=!0;let f=e.iterable.args.map(p=>p.type===y.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===y.VARIABLE?p.path:p.type===y.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 Fo(d,o,u)}if(!e.indexVar){let c=pc(e,o,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=dc(e,o);if(c!==null)return c}let i=fc(e,t,r,n,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(n&&n.__paths__&&l){let c=l.split("."),u=c[0];u in n.__paths__&&(l=n.__paths__[u],c.length>1&&(l+="."+c.slice(1).join(".")))}let a=!1;e.body.type===y.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(c=>c.type===y.OBJECT&&c.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let c=0;c<o.length;c++){let u=e.indexVar?{...n,[e.itemVar]:o[c],[e.indexVar]:c}:{...n,[e.itemVar]:o[c]};u.__paths__||(u.__paths__=n.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${c}]`},e.indexVar&&(u.__paths__[e.indexVar]=c);let d=V(e.body,t,r,u);if(Array.isArray(d)&&d.length===1&&!a){let f=d[0];s.push(f===void 0?{}:f)}else s.push(d===void 0?{}:d)}return s},mc=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?V(o.parsedKey,t,r,n):o.key,s=o.value;if(s.type===y.OBJECT&&s.properties.length<=10&&!s.whenCondition){let l={},a={},c=!0;for(let u of s.properties){let d=u.parsedKey?V(u.parsedKey,t,r,n):u.key,f=u.value;if(f.type===y.LITERAL)a[d]=f.value;else if(f.type===y.VARIABLE)a[d]=J(f.path,r,n);else if(f.type===y.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===y.VARIABLE){let g=J(h.path,r,n);p.push(g!=null?String(g):"")}else{c=!1;break}if(!c)break;a[d]=p.join("")}else if(f.type===y.OBJECT&&f.properties.length<=5){let p={};for(let h of f.properties){let g=h.key,I=h.value;if(I.type===y.LITERAL)p[g]=I.value;else if(I.type===y.VARIABLE)p[g]=J(I.path,r,n);else if(I.type===y.INTERPOLATION){let b=[];for(let w of I.parts)if(typeof w=="string")b.push(w);else if(w.type===y.VARIABLE){let S=J(w.path,r,n);b.push(S!=null?String(S):"")}else{c=!1;break}if(!c)break;p[g]=b.join("")}else{c=!1;break}}if(!c)break;a[d]=p}else{c=!1;break}}if(c)return l[i]=a,l}}return null},gc=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!Pe(e.whenCondition,o,r,n))return;let i=mc(e,t,r,n);if(i!==null)return i;if(e.fast){let c={};for(let u of e.properties){let d=u.parsedKey?V(u.parsedKey,t,r,n):u.key,f=u.value;if(f.type===y.LITERAL)c[d]=f.value;else if(f.type===y.VARIABLE)c[d]=J(f.path,r,n);else if(f.type===y.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===y.VARIABLE){let g=J(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=V(h,t,r,n);p.push(g!=null?String(g):"")}c[d]=p.join("")}else c[d]=V(f,t,r,n)}return c}let s={},l=null,a=!1;for(let c of e.properties)if(!c.key.startsWith("$if ")&&!c.key.match(/^\$if\s+\w+.*:?$/)&&!c.key.startsWith("$elif")&&!c.key.startsWith("$else")&&!c.key.startsWith("$for ")){a=!0;break}for(let c of e.properties)if(c.key.startsWith("$if ")||c.key.match(/^\$if\s+\w+.*:?$/)){let u=V(c.value,t,r,n);if(!a&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(c.key.startsWith("$for ")){if(e.properties.length===1)return V(c.value,t,r,n)}else{let u=c.value;if(u&&u.type===y.OBJECT&&u.properties){let d=u.properties.find(f=>f.key.startsWith("$for "));if(d){let f=V(d.value,t,r,n);f!==void 0&&(s[c.key]=f)}else{let f=V(c.value,t,r,n);f!==void 0&&(s[c.key]=f)}}else{let d=c.parsedKey?V(c.parsedKey,t,r,n):c.key,f=V(c.value,t,r,n);f!==void 0&&(s[d]=f)}}return s},Yo={},yc=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===y.LOOP){let s=V(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=V(i,t,r,n);s!==Yo&&s!==void 0&&o.push(s)}return o},bc=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},a=t.functions||t;if(s&&!Pe(s,a,r,n))return;if(!l[o])throw new ue(`Partial '${o}' is not defined`);let c=n._partialStack||[];if(c.includes(o))throw new ue(`Circular partial reference detected: ${o}`);let u=l[o],d=r,f={...n,_partialStack:[...c,o]};if(n){d={...r};for(let p of Object.keys(n))p.startsWith("_")||(d[p]=n[p])}if(i){let p=V(i,t,r,n);d={...d,...p}}return V(u,t,d,f)},Ic=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],l=i.slice(1);if(!n||!(s in n))throw new ue(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(n.__paths__||(n.__paths__={}),!(s in n.__paths__))throw new ue(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=n.__paths__[s];if(typeof a=="number"){if(l.length>0)throw new ue(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return l.length>0&&(a+="."+l.join(".")),a};var Qr=ic;var Ac=/\$\{([^}]*)\}/g,wc=/#\{([^}]*)\}/g,Wo=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=Ec(o,t);return{isFunction:!0,type:y.FUNCTION,name:n,args:i}},Ec=(e,t={})=>e.trim()?xc(e).map(n=>vc(n.trim(),t)):[],xc=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],a=s>0?e[s-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,r+=l):o&&l===i&&a!=="\\"?(o=!1,i="",r+=l):!o&&l==="("?(n++,r+=l):!o&&l===")"?(n--,r+=l):!o&&l===","&&n===0?(t.push(r),r=""):r+=l}return r&&t.push(r),t},vc=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:y.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:y.LITERAL,value:parseFloat(e)};if(e==="true")return{type:y.LITERAL,value:!0};if(e==="false")return{type:y.LITERAL,value:!1};if(e==="null")return{type:y.LITERAL,value:null};let r=Wo(e,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};let n=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:l,type:a}of o){let c=0;for(;c<n.length;){let u=Xe(n.substring(c),l);if(u===-1)break;let d=c+u;d>i&&(i=d,s={op:l,type:a}),c=d+l.length}}if(i!==-1)try{return Q(n,t)}catch{return{type:y.VARIABLE,path:n}}return{type:y.VARIABLE,path:n}},Ko=/^\w+\(.*\)$/,Cc=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Sc=e=>{if(!(!e||e.trim()===""||Ko.test(e))&&Cc.test(e))throw e.includes("?")&&e.includes(":")?new C(`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 C(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new C(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Ho=e=>{let t=e.trim();if(Ko.test(t))throw new C(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new C(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new C(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new C(`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 C(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:y.PATH_REFERENCE,path:t}},Ct=(e,t={})=>{let r=e.trim();Sc(r);let n=Wo(r,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};if(r.includes("[")&&!/[\s+\-*/%|&?:]/.test(r)){let o=0;for(let i of r)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:y.VARIABLE,path:r}},Zr=(e,t={})=>{let r=e,n=[];(e.includes("\\${")||e.includes("\\#{"))&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),r=r.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${n.length}__`;return n.push(u),d}),r=r.replace(/\\(#\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${n.length}__`;return n.push(u),d}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(Ac)],i=[...r.matchAll(wc)],s=[...o.map(c=>({match:c,type:"variable"})),...i.map(c=>({match:c,type:"pathref"}))].sort((c,u)=>c.match.index-u.match.index);if(s.length===0){let c=r;for(let u=0;u<n.length;u++)c=c.replace(`__ESCAPED_${u}__`,n[u]);return{type:y.LITERAL,value:c}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:c,type:u}=s[0];try{return u==="variable"?Ct(c[1],t):Ho(c[1])}catch(d){if(d.message==="Invalid array index syntax")return{type:y.LITERAL,value:r};throw d}}let l=[],a=0;for(let{match:c,type:u}of s){let[d,f]=c,p=c.index;if(p>a){let h=r.substring(a,p);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&l.push(h)}try{let h;u==="variable"?h=Ct(f.trim(),t):h=Ho(f.trim()),l.push(h)}catch(h){if(h.message==="Invalid array index syntax")l.push(d);else throw h}a=p+d.length}if(a<r.length){let c=r.substring(a);for(let u=0;u<n.length;u++)c=c.replace(`__ESCAPED_${u}__`,n[u]);c&&l.push(c)}return{type:y.INTERPOLATION,parts:l}};var rn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Qo=e=>Object.keys(e),ae=e=>e.join("."),De=(e,t,r)=>{let n=Qo(e).filter(o=>!t.has(o));if(n.length>0)throw new C(`Unexpected key '${n[0]}' in condition JSON at '${ae(r)}'`)},Ve=(e,t)=>typeof e=="string"?Zr(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Oc(e,t):Rc(e,t):{type:y.LITERAL,value:e},_c=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new C("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new C("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new C("Empty $each body not allowed");if(r.$partial!==void 0)throw new C("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${n}`]:r}},Oc=(e,t)=>{let r=[],n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let a=_c(i),c=Object.keys(a);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let u=Xo(c[0],a[c[0]],t,!0);r.push(u),n=!0;continue}}catch(a){throw a instanceof C?a:new C(a.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let a=Xo(l[0],i[l[0]],t);r.push(a),n=!0;continue}}let s=Ve(i,t);r.push(s),(s.type===y.FUNCTION||s.type===y.CONDITIONAL||s.type===y.LOOP||s.type===y.PARTIAL||s.type===y.OBJECT&&!s.fast||s.type===y.ARRAY&&!s.fast)&&(n=!0)}return{type:y.ARRAY,items:r,fast:!n}},Rc=(e,t)=>{let r=[],n=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new C("$partial value must be a string");if(e.$partial.trim()==="")throw new C("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],c=[];for(let[b]of i)for(let w of a)if(b===w||b.startsWith(w+" ")||b.startsWith(w+"#")){c.push(w);break}if(c.length>0)throw new C(`Cannot use $partial with ${c.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:d,...f}=e,p={},h=!1;for(let[b,w]of Object.entries(f)){let S=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(S=b.slice(1)),p[S]=w,h=!0}let g=null;if(h&&(g=Ve(p,t),g.type===y.OBJECT)){let b=!1;for(let w of g.properties)if(w.value.type===y.VARIABLE||w.value.type===y.INTERPOLATION||w.value.type===y.FUNCTION||w.value.type===y.CONDITIONAL||w.value.type===y.OBJECT&&!w.value.fast||w.value.type===y.ARRAY&&!w.value.fast){b=!0;break}b&&(g.fast=!1)}let I={type:y.PARTIAL,name:u,data:g};return d!==void 0&&(I.whenCondition=Jo(d,t)),I}for(let[a,c]of i)if(a==="$when"){if(o!==null)throw new C("Multiple '$when' directives on the same object are not allowed");if(c==null)throw new C("Missing condition expression after '$when'");o=Jo(c,t),n=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new C("'$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 C("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let u=$c(i,s,t);r.push({key:a,value:u.node}),n=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let u=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",d=u?`:${u}`:"";throw new C(`$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 C(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new C("Missing condition expression after '$if'");{let u=Ve(c,t);(u.type===y.FUNCTION||u.type===y.CONDITIONAL||u.type===y.PARTIAL||u.type===y.OBJECT&&!u.fast||u.type===y.ARRAY&&!u.fast)&&(n=!0);let d=Zr(a,t),f={key:a,value:u};(d.type!==y.LITERAL||d.value!==a)&&(f.parsedKey=d),r.push(f),s++}}}let l={type:y.OBJECT,properties:r,fast:!n};return o&&(l.whenCondition=o),l},$c=(e,t,r={})=>{let n=[],o=[],i=t,[s,l]=e[i],a=null,c;if(s.startsWith("$if#")){let d=s.match(/^\$if#(\w+)\s+(.+)$/);if(d)a=d[1],c=d[2];else throw new C(`Invalid conditional syntax: ${s}`)}else c=s.substring(4),c.endsWith(":")&&(c=c.slice(0,-1).trim());Xr(c);let u=Q(c,r);for(n.push(u),o.push(Ve(l,r)),i++;i<e.length;){let[d,f]=e[i],p=!1,h;if(a?d.startsWith(`$elif#${a} `)?(h=d.substring(`$elif#${a} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(d===`$else#${a}`||d===`$else#${a}:`)&&(p=!0,h=null):d.startsWith("$elif ")?(h=d.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(d==="$else"||d==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{Xr(h);let g=Q(h,r);n.push(g)}if(o.push(Ve(f,r)),i++,h===null)break}else break}return{node:{type:y.CONDITIONAL,conditions:n,bodies:o,id:a},nextIndex:i}},en={eq:L.EQ,neq:L.NEQ,gt:L.GT,gte:L.GTE,lt:L.LT,lte:L.LTE,in:L.IN,add:L.ADD,sub:L.SUBTRACT},tn={all:L.AND,any:L.OR},kc=new Set(["var","literal","call","not",...Object.keys(en),...Object.keys(tn)]),Lc=(e,t,r)=>{if(!Array.isArray(e))throw new C(`Condition JSON operator '${t}' at '${ae(r)}' requires an array`);if(e.length!==2)throw new C(`Condition JSON operator '${t}' at '${ae(r)}' requires exactly 2 operands`);return e},Tc=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new C(`Condition JSON operator '${t}' at '${ae(o)}' requires an array`);if(e.length===0)throw new C(`Condition JSON operator '${t}' at '${ae(o)}' requires at least 1 condition`);return e.map((s,l)=>he(s,n,[...o,l])).reduce((s,l)=>({type:y.BINARY,op:r,left:s,right:l}))},Nc=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],De(e,new Set(["call","args"]),r);else if(rn(e.call))n=e.call.name,o=e.call.args??[],De(e,new Set(["call"]),r),De(e.call,new Set(["name","args"]),[...r,"call"]);else throw new C(`Condition JSON call at '${ae(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new C(`Condition JSON call at '${ae(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new C(`Invalid condition JSON function name '${n}' at '${ae(r)}'`);if(!Array.isArray(o))throw new C(`Condition JSON call '${n}' at '${ae(r)}' requires args to be an array`);return{type:y.FUNCTION,name:n,args:o.map((i,s)=>he(i,t,[...r,"args",s]))}},he=(e,t={},r=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:y.LITERAL,value:e};if(Array.isArray(e))throw new C(`Condition JSON array at '${ae(r)}' must be wrapped in an operator or { literal: [...] }`);if(!rn(e))throw new C(`Invalid condition JSON value at '${ae(r)}'`);let n=Qo(e);if(n.length===0)throw new C(`Condition JSON object at '${ae(r)}' must contain an operator`);let o=n.filter(s=>kc.has(s));if(o.length===0)throw new C(`Unknown condition JSON operator '${n[0]}' at '${ae(r)}'`);if(o.length>1)throw new C(`Condition JSON at '${ae(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(De(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new C(`Condition JSON var at '${ae(r)}' requires a non-empty path`);return{type:y.VARIABLE,path:e.var}}if(i==="literal")return De(e,new Set(["literal"]),r),{type:y.LITERAL,value:e.literal};if(i==="call")return Nc(e,t,r);if(i==="not")return De(e,new Set(["not"]),r),{type:y.UNARY,op:ut.NOT,operand:he(e.not,t,[...r,"not"])};if(i in tn)return De(e,new Set([i]),r),Tc(e[i],i,tn[i],t,[...r,i]);if(i in en){De(e,new Set([i]),r);let s=Lc(e[i],i,[...r,i]);return{type:y.BINARY,op:en[i],left:he(s[0],t,[...r,i,0]),right:he(s[1],t,[...r,i,1])}}throw new C(`Unknown condition JSON operator '${i}' at '${ae(r)}'`)},Jo=(e,t={})=>{if(e==null)throw new C("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new C("Empty condition expression after '$when'");return Q(e,t)}return rn(e)||Array.isArray(e)?he(e,t):{type:y.LITERAL,value:e}},Q=(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 Q(c,t)}let r=Xe(e,"||");if(r!==-1)return{type:y.BINARY,op:L.OR,left:Q(e.substring(0,r).trim(),t),right:Q(e.substring(r+2).trim(),t)};let n=Xe(e,"&&");if(n!==-1)return{type:y.BINARY,op:L.AND,left:Q(e.substring(0,n).trim(),t),right:Q(e.substring(n+2).trim(),t)};let o=[{op:">=",type:L.GTE},{op:"<=",type:L.LTE},{op:"==",type:L.EQ},{op:"!=",type:L.NEQ},{op:">",type:L.GT},{op:"<",type:L.LT},{op:" in ",type:L.IN}];for(let{op:c,type:u}of o){let d=Xe(e,c);if(d!==-1)return{type:y.BINARY,op:u,left:Q(e.substring(0,d).trim(),t),right:Q(e.substring(d+c.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:L.ADD},{op:" - ",type:L.SUBTRACT}];for(let{op:c,type:u}of l){let d=0;for(;d<e.length;){let f=Xe(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:y.BINARY,op:s.type,left:Q(e.substring(0,i).trim(),t),right:Q(e.substring(i+s.op.length).trim(),t)};let a=[" * "," / "," % "];for(let c of a)if(Xe(e,c)!==-1)throw new C(`Arithmetic operations are not allowed in conditionals: "${c}"`);return e.startsWith("!")?{type:y.UNARY,op:ut.NOT,operand:Q(e.substring(1).trim(),t)}:Zo(e,t)},Xe=(e,t)=>{let r=0,n=0;for(;n<=e.length-t.length;){if(e[n]==="(")r++;else if(e[n]===")")r--;else if(r===0&&e.substring(n,n+t.length)===t)return n;n++}return-1},Pc=e=>{if(e=e.trim(),e==="true")return{type:y.LITERAL,value:!0};if(e==="false")return{type:y.LITERAL,value:!1};if(e==="null")return{type:y.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:y.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:y.LITERAL,value:""};if(e==="{}")return{type:y.LITERAL,value:{}};if(e==="[]")return{type:y.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:y.LITERAL,value:t}:{type:y.VARIABLE,path:e}},Zo=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return Ct(r,t);let o=Pc(r);if(o.type===y.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:y.VARIABLE,path:r};try{return Ct(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Dc=(e,t=!1)=>{let r=t?"$each":"$for";try{Mo(e)}catch(n){if(n instanceof C&&t){let o=n.message.replace(/\$for/g,"$each");throw new C(o.replace("Parse Error: ",""))}throw n}},Xo=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let I=n?"$each":"$for";throw new C(`Invalid loop syntax (got: '${e.replace("$for",I)}')`)}let s=i[1],l=i[2].trim();Dc(l,n);let a=l.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let I=n?"$each":"$for";throw new C(`Invalid loop syntax - missing 'in' keyword (got: '${I} ${l}')`)}let c=a[1].trim(),u=a[2].trim(),d,f=null;if(c.includes(",")){let I=c.split(",").map(b=>b.trim());if(I.length!==2)throw new C(`Invalid loop variables: ${c}. Expected format: "item" or "item, index"`);d=I[0],f=I[1]}else d=c;let p=["this","undefined","null","true","false"];if(p.includes(d))throw new C(`Reserved variable name: ${d}`);if(f&&p.includes(f))throw new C(`Reserved variable name: ${f}`);let h=Zo(u,r),g=Ve(t,r);return{type:y.LOOP,itemVar:d,indexVar:f,iterable:h,body:g,flatten:s!=="nested"}};var Vc=(e,t={})=>{let{functions:r={}}=t;return Ve(e,r)},rr=Vc;var St={};Ka(St,{now:()=>jc});var jc=()=>Date.now();var Mc=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...St,...n},s=rr(e,{functions:i}),l={};for(let[a,c]of Object.entries(o))l[a]=rr(c,{functions:i});return Qr(s,t,{functions:i,partials:l})},Qe=Mc;var Fc=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Uc=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Bc=(e,t)=>{if(Fc(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new C("Empty condition expression");return Q(e,t)}return he(e,t)},Gc=(e,t={},r={})=>{let n=Uc(r),o={...St,...n},i=Bc(e,o);return!!Pe(i,{functions:o,partials:{}},t,{})},nn=Gc;var gn=Symbol("runStoreTransaction"),un="__routeEngineConditionComparison",nr=(e,t)=>typeof e=="number"&&typeof t=="number"&&Number.isFinite(e)&&Number.isFinite(t)||typeof e=="string"&&typeof t=="string",je=Object.freeze({eq:(e,t)=>e===t,neq:(e,t)=>e!==t,gt:(e,t)=>nr(e,t)&&e>t,gte:(e,t)=>nr(e,t)&&e>=t,lt:(e,t)=>nr(e,t)&&e<t,lte:(e,t)=>nr(e,t)&&e<=t}),si=Object.freeze(Object.fromEntries(Object.keys(je).map(e=>[e,`${un}${e}`]))),zc=Object.freeze(Object.fromEntries(Object.entries(si).map(([e,t])=>[t,je[e]]))),ei=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),qc=e=>{if(typeof e?.call=="string")return e.call;if(e?.call!==null&&typeof e?.call=="object"&&!Array.isArray(e.call))return e.call.name},or=e=>{if(Array.isArray(e))return e.map(or);if(e===null||typeof e!="object"||ei(e,"literal")||ei(e,"var"))return e;if(qc(e)?.startsWith(un))throw new Error(`Condition function names beginning with "${un}" are reserved`);let r=Object.entries(e);if(r.length===1){let[[n,o]]=r,i=si[n];if(i)return{call:i,args:o.map(or)}}return Object.fromEntries(r.map(([n,o])=>[n,or(o)]))},Ot=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return he(e),nn(or(e),t,{functions:zc})},Yc=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],ai=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:l=c=>c}=r;for(let[c,u]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...d)=>u(s(n),...d):i[c]=(...d)=>{let f;return n=Jr(n,h=>{let g=u(l(h),...d);f=g!==void 0&&!se(g)?g:void 0}),f});let a=c=>{if(typeof c!="function")throw new Error("Store transaction requires a callback");let u=n;try{return c()}catch(d){throw n=u,d}};return{...o,...i,[gn]:a}},cr=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return Jr(n,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var Hc=(e,t)=>{if(e.default!==void 0)return e.default;let r=["number","boolean","string","object"];if(!r.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${r.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},N=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),dn=(e,t,r)=>{Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0})},be=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Wc=new Set(["pageSize","groups"]),Kc=new Set(["id","variants"]),Jc=new Set(["id","imageId"]),on=(e,t,r)=>{Object.keys(e).forEach(n=>{if(!t.has(n))throw new Error(`${r} contains unsupported property "${n}"`)})},sn=(e,t)=>{if(typeof e!="string"||e.length===0)throw new Error(`${t} must be a non-empty string`)},Rt=(e={})=>{let t=e?.resources?.imageGallery;if(t===void 0)return;if(!be(t))throw new Error("resources.imageGallery must be an object");if(on(t,Wc,"resources.imageGallery"),!Number.isInteger(t.pageSize)||t.pageSize<1)throw new Error("resources.imageGallery.pageSize must be an integer greater than or equal to 1");if(!Array.isArray(t.groups))throw new Error("resources.imageGallery.groups must be an array");let r=new Set;for(let[n,o]of t.groups.entries()){let i=`resources.imageGallery.groups[${n}]`;if(!be(o))throw new Error(`${i} must be an object`);if(on(o,Kc,i),sn(o.id,`${i}.id`),r.has(o.id))throw new Error(`Duplicate image gallery group id "${o.id}"`);if(r.add(o.id),!Array.isArray(o.variants)||o.variants.length===0)throw new Error(`${i}.variants must be a non-empty array`);let s=new Set;for(let[l,a]of o.variants.entries()){let c=`${i}.variants[${l}]`;if(!be(a))throw new Error(`${c} must be an object`);if(on(a,Jc,c),sn(a.id,`${c}.id`),sn(a.imageId,`${c}.imageId`),s.has(a.id))throw new Error(`Duplicate image gallery variant id "${a.id}" in group "${o.id}"`);if(s.add(a.id),!N(e?.resources?.images,a.imageId))throw new Error(`Image gallery variant "${o.id}.${a.id}" references unknown image "${a.imageId}"`)}}},ci=e=>{let t=se(e)?Je(e):e;return structuredClone(t)},Xc=({characterId:e,resourceCharacter:t,variables:r={}}={})=>{if(!N(t,"nameVariableId"))return;let n=t.nameVariableId,o=r?.[n];if(typeof o!="string")throw new Error(`Character "${e}" nameVariableId "${n}" must resolve to a string variable`);return o},lr=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0;if(t?.name!==void 0)return t.name;if(r!==void 0)return r;let s=Xc({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},Ce=e=>N(e,"computed"),dt=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Ce(t[r]))),we=(e,t)=>new Error(`${t} has invalid path: ${JSON.stringify(e)}`),Qc=(e,t,r)=>{if(e[0]==='"')try{return JSON.parse(e)}catch{throw we(t,r)}let o="";for(let i=1;i<e.length-1;i+=1){let s=e[i];if(s!=="\\"){if(s.charCodeAt(0)<32)throw we(t,r);o+=s;continue}if(i+=1,i>=e.length-1)throw we(t,r);let l=e[i];if(l==="u"){let c=e.slice(i+1,i+5);if(c.length!==4||!/^[0-9a-fA-F]{4}$/.test(c))throw we(t,r);o+=String.fromCharCode(Number.parseInt(c,16)),i+=4;continue}let a={"\\":"\\",'"':'"',"'":"'","/":"/",n:`
2
- `,r:"\r",t:" ",b:"\b",f:"\f"};if(!N(a,l))throw we(t,r);o+=a[l]}return o},li=(e,t="Computed expression var")=>{if(typeof e!="string"||e.length===0||e.trim()!==e)throw we(e,t);let r=[],n=0,o=()=>{let s=n;for(;n<e.length&&e[n]!=="."&&e[n]!=="["&&e[n]!=="]";)n+=1;let l=e.slice(s,n);if(l.length===0||l.trim()!==l||/\s/.test(l))throw we(e,t);r.push(l)},i=()=>{for(n+=1;n<e.length&&/\s/.test(e[n]);)n+=1;let s=e[n];if(/\d/.test(s??"")){let u=n;for(;n<e.length&&/\d/.test(e[n]);)n+=1;let d=e.slice(u,n);for(;n<e.length&&/\s/.test(e[n]);)n+=1;if(e[n]!=="]"||d.length>1&&d.startsWith("0"))throw we(e,t);n+=1,r.push(d);return}if(s!=='"'&&s!=="'")throw we(e,t);let l=s,a=n;n+=1;let c=!1;for(;n<e.length;){let u=e[n];if(c)c=!1;else if(u==="\\")c=!0;else if(u===l){let d=e.slice(a,n+1);for(n+=1;n<e.length&&/\s/.test(e[n]);)n+=1;if(e[n]!=="]")throw we(e,t);n+=1,r.push(Qc(d,e,t));return}n+=1}if(c||n>=e.length)throw we(e,t)};for(o();n<e.length;){if(e[n]==="."){n+=1,o();continue}if(e[n]==="["){i();continue}throw we(e,t)}return r},an=(e,t)=>{let r=e;for(let n of t){if(r==null||!N(r,n))return;r=r[n]}return r},ui=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=li(e),[n,o,...i]=r;if(n==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return an(s,i)}return n==="runtime"?an(t.runtime,r.slice(1)):an(t,r)},di=(e,t,r)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(r!==void 0&&t.length!==r)throw new Error(`Computed expression operator "${e}" requires ${r} operand(s)`)},fn=(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`)},Zc=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},ve=(e,t,r,n)=>(di(e,t,n),t.map(o=>ar(o,r))),Ae=(e,t,r,n)=>{let o=ve(e,t,r,n);return o.forEach(i=>Zc(e,i)),o},el=(e,t,r)=>{switch(e){case"var":return ui(t,r);case"add":{let[n,o]=Ae(e,t,r,2);return n+o}case"sub":{let[n,o]=Ae(e,t,r,2);return n-o}case"mul":{let[n,o]=Ae(e,t,r,2);return n*o}case"div":{let[n,o]=Ae(e,t,r,2);return n/o}case"mod":{let[n,o]=Ae(e,t,r,2);return n%o}case"neg":{let[n]=Ae(e,t,r,1);return-n}case"round":{let[n]=Ae(e,t,r,1);return Math.round(n)}case"floor":{let[n]=Ae(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=Ae(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=Ae(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=Ae(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=Ae(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=ve(e,t,r,2);return je.eq(n,o)}case"neq":{let[n,o]=ve(e,t,r,2);return je.neq(n,o)}case"gt":{let[n,o]=ve(e,t,r,2);return je.gt(n,o)}case"gte":{let[n,o]=ve(e,t,r,2);return je.gte(n,o)}case"lt":{let[n,o]=ve(e,t,r,2);return je.lt(n,o)}case"lte":{let[n,o]=ve(e,t,r,2);return je.lte(n,o)}case"in":{let[n,o]=ve(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return fn(e,t),t.every(n=>!!ar(n,r));case"or":case"any":return fn(e,t),t.some(n=>!!ar(n,r));case"not":{let[n]=ve(e,t,r,1);return!n}case"length":{let[n]=ve(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:be(n)?Object.keys(n).length:0}case"includes":{let[n,o]=ve(e,t,r,2);return typeof n=="string"?typeof o=="string"&&n.includes(o):Array.isArray(n)?n.includes(o):!1}case"literal":return ci(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},ar=(e,t={})=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let r=Object.entries(e);if(r.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[n,o]]=r;return el(n,o,t)},pn=(e,t)=>{if(e===null||typeof e!="object"||N(e,"literal"))return e;if(N(e,"var"))return{literal:ui(e.var,t)};if(N(e,"call"))throw new Error("Function calls are not supported in computed-variable conditions");return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Array.isArray(n)?n.map(o=>pn(o,t)):pn(n,t)]))},tl=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return he(e),Ot(pn(e,t))},fi=(e,t)=>{if(!be(e))throw new Error(`${t} must be an object`);let r=N(e,"expr"),n=N(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},cn=(e,t,r)=>(fi(e,t),N(e,"value")?ci(e.value):ar(e.expr,r)),rl=(e,t={},r="unknown")=>{if(!be(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=N(e,"expr"),o=N(e,"value");if(N(e,"branches")){if(n||o)throw new Error(`Computed variable "${r}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${r}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${r}" branches must not be empty`);if(!be(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let l=e.branches[s];if(!be(l))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!N(l,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(tl(l.when,t))return cn(l,`Computed variable "${r}" branch ${s}`,t)}return cn(e.default,`Computed variable "${r}" default`,t)}if(n===o)throw new Error(`Computed variable "${r}" must contain exactly one of expr, value, or branches`);return cn(e,`Computed variable "${r}"`,t)},pi=(e,t,r)=>{switch(t){case"number":if(typeof r!="number"||!Number.isFinite(r))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(r)?"array":typeof r}`);return;case"boolean":if(typeof r!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(r)?"array":typeof r}`);return;case"string":if(typeof r!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(r)?"array":typeof r}`);return;case"object":if(r===null||typeof r!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof r}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},nl=Object.freeze({add:2,sub:2,mul:2,div:2,mod:2,neg:1,round:1,floor:1,ceil:1,min:2,max:2,clamp:3,eq:2,neq:2,gt:2,gte:2,lt:2,lte:2,in:2,not:1,length:1,includes:2}),ol=new Set(["and","or","all","any"]),il=new Set(["add","sub","mul","div","mod","neg","round","floor","ceil","min","max","clamp","length"]),sl=new Set(["add","sub","mul","div","mod","neg","round","floor","ceil","min","max","clamp"]),al=new Set(["eq","neq","gt","gte","lt","lte","in","and","or","all","any","not","includes"]),cl=new Set(["all","any","eq","neq","gt","gte","lt","lte","in","add","sub"]),hi=new WeakMap,ti=e=>e===null?"null":Array.isArray(e)?"object":typeof e,ir=(e,t,r)=>{for(let n of Object.keys(e))if(!t.has(n))throw new Error(`${r} contains unsupported property "${n}"`)},ll=(e,t,r,n)=>{if(r!==void 0&&r!==t)throw new Error(`Computed variable "${e}" ${n} expected type ${t}, got ${r}`)},mi=(e,{variableId:t,variableConfigs:r,dependencies:n,path:o})=>{let i=`Computed variable "${t}" ${o} var`,[s,l,...a]=li(e,i);if(s!=="variables"&&s!=="runtime")throw new Error(`${i} must reference variables.* or runtime.*, got ${JSON.stringify(e)}`);if(!l)throw new Error(`${i} must reference a concrete ${s} member, got ${JSON.stringify(e)}`);if(s==="runtime")return;if(!N(r,l))throw new Error(`Computed variable "${t}" ${o} references unknown variable "${l}"`);let c=r[l];return Ce(c)&&n.add(l),a.length===0?c?.type:void 0},gi=(e,{variableId:t,variableConfigs:r,dependencies:n,path:o})=>{if(e===null||typeof e!="object"){if(typeof e=="number"&&!Number.isFinite(e))throw new Error(`Computed variable "${t}" ${o} must use finite numeric literals`);return ti(e)}if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let i=Object.entries(e);if(i.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[s,l]]=i;if(s==="var"){if(typeof l!="string"||l.trim()==="")throw new Error("Computed expression var requires a non-empty string path");return mi(l,{variableId:t,variableConfigs:r,dependencies:n,path:o})}if(s==="literal"){if(typeof l=="number"&&!Number.isFinite(l))throw new Error(`Computed variable "${t}" ${o} must use finite numeric literals`);return ti(l)}let a=nl[s];if(a===void 0&&!ol.has(s))throw new Error(`Unknown computed expression operator: ${s}`);a===void 0?fn(s,l):di(s,l,a);let c=l.map((u,d)=>gi(u,{variableId:t,variableConfigs:r,dependencies:n,path:`${o}.${s}[${d}]`}));if(sl.has(s)&&c.forEach(u=>{if(u!==void 0&&u!=="number")throw new Error(`Computed expression operator "${s}" requires numeric operands`)}),il.has(s))return"number";if(al.has(s))return"boolean"},ul=(e,{variableId:t,variableConfigs:r,dependencies:n,path:o})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");try{he(e)}catch(s){throw new Error(`Computed variable "${t}" ${o} is invalid: ${s.message}`,{cause:s})}let i=(s,l)=>{if(s===null||typeof s!="object"||N(s,"literal"))return;if(N(s,"var")){mi(s.var,{variableId:t,variableConfigs:r,dependencies:n,path:l});return}if(N(s,"call"))throw new Error(`Computed variable "${t}" ${l} function calls are not supported`);if(N(s,"not")){i(s.not,`${l}.not`);return}let a=Object.keys(s).find(c=>cl.has(c));s[a].forEach((c,u)=>{i(c,`${l}.${a}[${u}]`)})};i(e,o)},ln=(e,{variableId:t,variableConfig:r,variableConfigs:n,dependencies:o,path:i,allowedKeys:s=new Set(["expr","value"])})=>{if(fi(e,`Computed variable "${t}" ${i}`),ir(e,s,i),N(e,"value")){pi(t,r.type,e.value);return}let l=gi(e.expr,{variableId:t,variableConfigs:n,dependencies:o,path:`${i}.expr`});ll(t,r.type,l,`${i}.expr`)},dl=(e,t,r)=>{let n=t.computed;if(!be(n))throw new Error(`Computed variable "${e}" computed must be an object`);let o=new Set,i=N(n,"expr"),s=N(n,"value");if(N(n,"branches")){if(ir(n,new Set(["branches","default"]),`Computed variable "${e}" computed`),i||s)throw new Error(`Computed variable "${e}" cannot combine branches with expr or value`);if(!Array.isArray(n.branches))throw new Error(`Computed variable "${e}" branches must be an array`);if(n.branches.length===0)throw new Error(`Computed variable "${e}" branches must not be empty`);if(!be(n.default))throw new Error(`Computed variable "${e}" requires default`);return n.branches.forEach((a,c)=>{if(!be(a))throw new Error(`Computed variable "${e}" branch ${c} must be an object`);if(ir(a,new Set(["when","expr","value"]),`Computed variable "${e}" branch ${c}`),!N(a,"when"))throw new Error(`Computed variable "${e}" branch ${c} requires when`);ul(a.when,{variableId:e,variableConfigs:r,dependencies:o,path:`computed.branches[${c}].when`}),ln(a,{variableId:e,variableConfig:t,variableConfigs:r,dependencies:o,path:`computed.branches[${c}]`,allowedKeys:new Set(["when","expr","value"])})}),ln(n.default,{variableId:e,variableConfig:t,variableConfigs:r,dependencies:o,path:"computed.default"}),o}if(ir(n,new Set(["expr","value"]),`Computed variable "${e}" computed`),i===s)throw new Error(`Computed variable "${e}" must contain exactly one of expr, value, or branches`);return ln(n,{variableId:e,variableConfig:t,variableConfigs:r,dependencies:o,path:"computed"}),o},Ze=(e={})=>{if(!be(e))throw new Error("Variable configs must be an object");if(N(e,"__proto__"))throw new Error('Variable id "__proto__" is reserved');if(N(e,""))throw new Error("Variable ids must not be empty");let t=new Map;Object.entries(e).forEach(([i,s])=>{if(Ce(s)){if(!be(s))throw new Error(`Computed variable "${i}" must be an object`);if(!N(s,"type"))throw new Error(`Computed variable "${i}" requires type`);if(!N(s,"scope"))throw new Error(`Computed variable "${i}" requires scope`);if(N(s,"default"))throw new Error(`Computed variable "${i}" must not declare a top-level default`);if(kt(s.scope,i),!["number","boolean","string","object"].includes(s.type))throw new Error(`Invalid variable type: ${s.type} for computed variable ${i}`);t.set(i,dl(i,s,e))}});let r=new Set,n=[];t.forEach((i,s)=>{if(r.has(s))return;let l=[{variableId:s,dependencies:[...t.get(s)??[]],nextDependencyIndex:0}],a=new Map([[s,0]]);for(;l.length>0;){let c=l.at(-1);if(c.nextDependencyIndex>=c.dependencies.length){l.pop(),a.delete(c.variableId),r.add(c.variableId),n.push(c.variableId);continue}let u=c.dependencies[c.nextDependencyIndex];if(c.nextDependencyIndex+=1,r.has(u))continue;let d=a.get(u);if(d!==void 0){let f=[...l.slice(d).map(({variableId:p})=>p),u].join(" -> ");throw new Error(`Computed variable cycle detected: ${f}`)}a.set(u,l.length),l.push({variableId:u,dependencies:[...t.get(u)??[]],nextDependencyIndex:0})}});let o=Object.freeze({evaluationOrder:Object.freeze(n)});return hi.set(e,o),o},$t=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let{evaluationOrder:o}=hi.get(r)??Ze(r),i=dt(e,r),s=Object.entries(r).filter(([,I])=>Ce(I)).map(([I])=>I),l=Object.create(null),a=[],c=new Map(o.map((I,b)=>[I,b])),u=-1,d=!1,f=I=>{if(N(l,I))return l[I];let b=r[I];if(!Ce(b))return N(i,I)?i[I]:void 0;let w=a.indexOf(I);if(w>=0){let S=[...a.slice(w),I].join(" -> ");throw new Error(`Computed variable cycle detected: ${S}`)}a.push(I);try{let S=rl(b.computed,g,I);return pi(I,b.type,S),dn(l,I,S),S}finally{a.pop()}},p=I=>{if(N(l,I))return l[I];let b=r[I];if(!Ce(b))return N(i,I)?i[I]:void 0;let w=c.get(I);if(n&&!d&&w!==void 0&&w>u){d=!0;try{for(let S=u+1;S<=w;S+=1)f(o[S]),u=S}finally{d=!1}return l[I]}return f(I)},h=new Proxy({},{get:(I,b)=>{if(typeof b=="string")return p(b)},has:(I,b)=>typeof b=="string"&&(N(i,b)||s.includes(b)),ownKeys:()=>[...new Set([...Object.keys(i),...s])],getOwnPropertyDescriptor:(I,b)=>{if(!(typeof b!="string"||!N(i,b)&&!s.includes(b)))return{enumerable:!0,configurable:!0}}}),g={variables:h,runtime:t,resolveVariable:p};return n?(s.forEach(I=>{p(I)}),{...i,...l}):h},fl=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>{let o=r??n?.resources?.variables??{};return Ze(o),$t({variables:e,runtime:t,variableConfigs:o,eager:!0})},ur=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(Ce(o))return;let i=Hc(o,n);o.scope==="context"?dn(t,n,i):dn(r,n,i)}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},kt=(e,t)=>{let r=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!r.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${r.join(", ")}`)},dr=(e,t,r)=>{let n={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=n[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${r}`);if(!Object.values(n).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${r}" of type "${e}". Valid operations: ${o.join(", ")}`)},pl=2,ri=12,yi=(e=pl)=>{if(!Number.isInteger(e)||e<0||e>ri)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${ri}.`);return e},hl=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},sr=e=>typeof e=="number"&&Number.isFinite(e),yn=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!sr(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!sr(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!sr(r))throw new Error(`Operation "divide" requires value to be a number for variable "${n}".`);if(t==="divide"){if(r===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${n}".`);yi(o.roundTo)}}},fr=(e,t,r,n={})=>{let o=(s,l,a)=>{let c=s??l;if(!sr(c))throw new Error(`Operation "${t}" requires ${a} to be a number.`);return c},i=s=>{let l=o(s,void 0,"value");if(l===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return l};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return hl(o(e,0,"current value")/i(r),yi(n.roundTo));case"increment":return o(e,0,"current value")+o(r,1,"value");case"decrement":return o(e,0,"current value")-o(r,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var bn=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let r=new Date(e),n=s=>String(s).padStart(2,"0"),o=String(r.getFullYear()),i={DD:n(r.getDate()),MM:n(r.getMonth()+1),MMM:Yc[r.getMonth()],YYYY:o,YY:o.slice(-2),HH:n(r.getHours()),mm:n(r.getMinutes()),ss:n(r.getSeconds())};return t.replace(/YYYY|MMM|YY|MM|DD|HH|mm|ss/g,s=>i[s])},ml=(e,t)=>{let r=i=>i?.ui,n=r(e),o=r(t);return JSON.stringify(n)===JSON.stringify(o)?null:n&&!o?{changeType:"delete",data:e}:o&&!n?{changeType:"add",data:t}:o&&n?{changeType:"update",data:t}:null},_t=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,gl=(e,t)=>{let r=e?.character?.sprite,n=t?.character?.sprite,o=_t(r)?r:void 0,i=_t(n)?n: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},ni=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};e.transformId!==void 0&&(t.transformId=e.transformId);for(let r of["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"])e[r]!==void 0&&(t[r]=e[r]);for(let r of["animationName","animationSpeed","loop"])e[r]!==void 0&&(t[r]=e[r]);return t},oi=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},ii=(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,yl=(e,t)=>{let r={},n=ii(ni(e),ni(t)),o=ii(oi(e),oi(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},In=(e={},t={})=>{let r={},n=["sfx","voice"],o=a=>{let c=e[a],u=t[a];u&&!c?r[a]={changeType:"add",data:u}:c&&!u?n.includes(a)||(r[a]={changeType:"delete",data:c}):c&&u&&JSON.stringify(c)!==JSON.stringify(u)&&(r[a]={changeType:"update",data:u})},i=yl(e.background,t.background);i&&(r.background=i),o("screen"),o("bgm"),o("voice");let s=ml(e.dialogue,t.dialogue);s&&(r.dialogue=s);let l=gl(e.dialogue,t.dialogue);return l&&(r.dialogueSprite=l),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),r},An=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,!t.background.resourceId&&!t.background.colorId&&delete t.background);let r=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};r("layout"),r("choice"),r("form"),r("screen"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let n=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(l=>{let a={...l};return delete a.animations,i(a)?a:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return n("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),n("visual",o=>o.resourceId||o.transformId),t},bl=(e,t)=>{if(!e||!t)return;let r=e;for(let n of t.split(".")){if(r==null||!(n in Object(r)))return;r=r[n]}return r},Il=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let r=e.slice(7),n=bl(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},Al={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"])},bi=(e,t)=>{let r=e[e.length-1];return r?Al[r]?.has(t)===!0:!1},hn=(e,t,r=[])=>Array.isArray(e)?e.map(n=>hn(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,bi(r,n)?o:hn(o,t,[...r,n])])):Il(e,t),mn=(e,t,r=[])=>Array.isArray(e)?e.map(n=>mn(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,bi(r,n)?o:mn(o,t,[...r,n])])):typeof e=="string"?Qe(e,t):e,wn=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let r=hn(e,t._event);return mn(r,t)};var H=e=>structuredClone(se(e)?Je(e):e),U=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ii=e=>e?.animations?.playback?.continuity==="persistent",j=(e,t)=>U(e??{},t)&&e[t]!==void 0,Lt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:H(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},wl=e=>j(e,"opacity")||j(e,"blur"),Ci=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Si=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],En=["animationName","animationSpeed","loop"],El=e=>Ci.some(t=>j(e,t)),_i=e=>e?.text&&j(e.text,"content")&&j(e.text,"textStyleId"),Oi=e=>j(e,"text"),xl=(e,t)=>e.resourceId?!0:_i(e)?!t?.text:!1,vl=(e,t)=>{let r={...H(e),...t};return t.text&&e.text&&(r.text={...H(e.text),...H(t.text)}),r},Cl=(e,t)=>{if(Oi(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!_i(e)&&!t?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},Ai=e=>Si.some(t=>j(e,t)),wi=e=>En.some(t=>j(e,t)),Sl=(e,t,{hasAuthoredTransformId:r=!1}={})=>{if(!t)return e;for(let n of Si)!r&&!j(e,n)&&j(t,n)&&(e[n]=t[n]),U(e,n)&&e[n]===void 0&&delete e[n];return e},Ri=(e,t,r)=>{let n=e[r];return n?.id===t?.id?n:e.find(o=>o.id===t?.id)},_l=(e,t)=>{if(!t)return e;for(let r of Ci)!j(e,r)&&j(t,r)&&(e[r]=t[r]),U(e,r)&&e[r]===void 0&&delete e[r];return e},Ol=(e,t)=>(t&&(!j(e,"opacity")&&j(t,"opacity")&&(e.opacity=t.opacity),!j(e,"blur")&&j(t,"blur")&&(e.blur=H(t.blur)),U(e,"opacity")&&e.opacity===void 0&&delete e.opacity,U(e,"blur")&&e.blur===void 0&&delete e.blur),e),$i=(e,t,r=[],{hasPatchFn:n=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,l)=>{let a=Ri(r,s,l),c=t(s,a),u=wl(s),d=El(s),f=n(s),p=U(s,"animations"),h=H(s);return!c&&(u||d||f)&&a&&(h=o?o(a,h):{...H(a),...h},p||delete h.animations),Ol(_l(h,a),a)}).filter(s=>t(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},Rl=e=>{if(e){if(e.character&&U(e.character,"name"))return e.character.name;if(U(e,"characterName"))return e.characterName}},ki=e=>!!e?.character&&U(e.character,"sprite"),$l=e=>{let t={},r=!1,n=Rl(e);return n!==void 0&&(t.name=n,r=!0),ki(e)&&(t.sprite=H(e.character.sprite),r=!0),r?t:void 0},Ei=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},xi=({dialogueState:e,dialogueAction:t,persistCharacter:r})=>U(t,"persistSprite")?t.persistSprite===!0:U(e,"persistSprite")?e.persistSprite===!0:r&&!U(t,"characterId"),vi=({previousCharacter:e,characterFields:t,hasCharacterId:r,persistCharacter:n,persistSprite:o,hasExplicitPersistSprite:i,isAppendingAdvDialogueContent:s})=>{let l={},a=e??{},c=t??{},u=s&&!r,d=u&&!i;return U(c,"name")?l.name=c.name:(n&&!r||u)&&U(a,"name")&&(l.name=H(a.name)),U(c,"sprite")?l.sprite=H(c.sprite):(o||d)&&U(a,"sprite")&&(l.sprite=H(a.sprite)),Object.keys(l).length>0?l:void 0},kl=({dialogueState:e,content:t,append:r=!1})=>{if(!r||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let n=Array.isArray(e.content)?e.content:[];n.length>0?e.initialRevealedContent=n.map(o=>H(o)):delete e.initialRevealedContent,e.content=[...n,...t]},Ll=()=>({}),Tl=(e,t)=>{if(!t.screen)return;let r=j(t.screen,"opacity"),n=j(t.screen,"blur"),o=U(t.screen,"animations");if(!r&&!n){o||delete e.screen;return}let i=e.screen,s={};if(r?s.opacity=t.screen.opacity:j(i,"opacity")&&(s.opacity=i.opacity),n?s.blur=H(t.screen.blur):j(i,"blur")&&(s.blur=H(i.blur)),U(s,"opacity")&&s.opacity===void 0&&delete s.opacity,U(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},Nl=(e,t)=>{if(t.background){let r=j(t.background,"resourceId"),n=j(t.background,"colorId"),o=j(t.background,"opacity"),i=j(t.background,"blur"),s=j(t.background,"transformId"),l=Ai(t.background),a=wi(t.background),{animationsOnly:c,state:u}=Lt(t.background,p=>j(p,"resourceId")||j(p,"colorId")||j(p,"opacity")||j(p,"blur")||j(p,"transformId")||Ai(p)||wi(p));if(c){e.background=e.background?{...H(e.background),...u}:u;return}if(!r&&!n&&!o&&!i&&!s&&!l&&!a){delete e.background;return}let d=e.background,f=H(t.background);if(!r&&d?.resourceId){f.resourceId=d.resourceId,!U(f,"transformId")&&d.transformId&&(f.transformId=d.transformId);for(let p of En)!j(f,p)&&j(d,p)&&(f[p]=d[p])}Sl(f,d,{hasAuthoredTransformId:s}),!n&&d?.colorId&&(f.colorId=d.colorId),!o&&j(d,"opacity")&&(f.opacity=d.opacity),!i&&j(d,"blur")&&(f.blur=H(d.blur)),U(f,"resourceId")&&f.resourceId===void 0&&delete f.resourceId,U(f,"colorId")&&f.colorId===void 0&&delete f.colorId,U(f,"animations")&&f.animations===void 0&&delete f.animations,U(f,"transformId")&&f.transformId===void 0&&delete f.transformId,U(f,"opacity")&&f.opacity===void 0&&delete f.opacity,U(f,"blur")&&f.blur===void 0&&delete f.blur;for(let p of En)U(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&&!U(f,"animations")&&Ii(d)&&(f.animations=H(d.animations)),e.background=f}else e.background?.animations&&!Ii(e.background)&&(e.background.animations={})},Pl=(e,t)=>{if(!t.dialogue){if(e.dialogue&&(Ei(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=xi({dialogueState:e.dialogue,dialogueAction:{},persistCharacter:u});u||delete e.dialogue.characterId,e.dialogue.character=vi({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 r=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:u,state:d}=Lt(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 n=t.dialogue.append===!0&&r!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&kl({dialogueState:e.dialogue,content:t.dialogue.content,append:n}),U(t.dialogue,"textSpeed")?e.dialogue.textSpeed=t.dialogue.textSpeed:delete e.dialogue.textSpeed;let o=U(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=xi({dialogueState:e.dialogue,dialogueAction:t.dialogue,persistCharacter:o});U(t.dialogue,"persistSprite")&&(e.dialogue.persistSprite=i);let s=U(t.dialogue,"characterId"),l=$l(t.dialogue),a=ki(t.dialogue);s?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId;let c=vi({previousCharacter:e.dialogue.character,characterFields:l,hasCharacterId:s,persistCharacter:o,persistSprite:i,hasExplicitPersistSprite:U(t.dialogue,"persistSprite"),isAppendingAdvDialogueContent:n});if(c?e.dialogue.character=c:delete e.dialogue.character,a||Ei(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=H(e.dialogue.character)),e.dialogue.lines.push(u)}},Dl=(e,t)=>{if(t.sfx){let r=Array.isArray(t.sfx.items)&&t.sfx.items.length>0,n=Array.isArray(t.sfx.channels)&&t.sfx.channels.length>0;if(!r&&!n){delete e.sfx;return}e.sfx=H(t.sfx)}else e.sfx&&delete e.sfx},Vl=(e,t)=>{if(t.bgm){let r=Array.isArray(t.bgm.sounds);if(!t.bgm.resourceId&&!r||r&&t.bgm.sounds.length===0){e.bgm=void 0;return}e.bgm=H(t.bgm),t.bgm.resourceId&&(e.bgm.loop=t.bgm.loop??!0)}},jl=(e,t)=>{if(t.visual){let r=e.visual?.items||[];t.visual.items?.forEach((i,s)=>{Cl(i,Ri(r,i,s))});let{hasValidItems:n,processedItems:o}=$i(t.visual.items,xl,r,{hasPatchFn:Oi,mergeItemFn:vl});n?e.visual={items:o}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(r=>r.animations?{...r,animations:{}}:r))},Ml=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:r,processedItems:n}=$i(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);r?e.character={items:n}:delete e.character},Fl=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Ul=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=Lt(t.layout,o=>!!o.resourceId);if(r){e.layout=n;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},Bl=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=Lt(t.choice,o=>!!o.resourceId);if(r){e.choice={...e.choice,...n};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},Gl=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=Lt(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=H(t.form)}else e.form&&delete e.form},zl=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},ql=(e,t)=>{if(t.voice){let r=Array.isArray(t.voice.sounds);if(!t.voice.resourceId&&!r||r&&t.voice.sounds.length===0){delete e.voice;return}e.voice=H(t.voice)}else e.voice&&delete e.voice},Yl=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},et=e=>cr(Ll,[Yl,Tl,Nl,Dl,Vl,jl,Pl,Ml,Fl,Ul,Bl,Gl,zl,ql])(e);var ft=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=Qe(e,t);return r&&typeof r=="object"?e:r};var Hl=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"}}),tt=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}),Tt=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Li=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"}),xn=Object.freeze(["dialogueTextSpeed","autoForwardDelay","autoForwardSpeed","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),vn=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Wl=(e,t)=>{if(t.startsWith("global.")){let r=t.slice(7);return e?.global?.[r]}if(t.startsWith("context.runtime.")){let r=t.slice(16),n=Array.isArray(e?.contexts)?e.contexts:[];return n[n.length-1]?.runtime?.[r]}},rt=e=>Object.fromEntries(Object.entries(Hl).map(([t,r])=>{let n=Wl(e,r.source),o=n!==void 0?n:tt[t]??Tt[t];return[t,o]})),Me=(e,t)=>rt(e)[t],Ti=(e={})=>Object.fromEntries(xn.map(t=>[t,e[t]??tt[t]]));var pt=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}),ke=Object.freeze({BEHIND_BACKGROUND:pt.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:pt.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:pt.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:pt.VISUAL_BEHIND_CHOICE,FOREGROUND:pt.VISUAL_FOREGROUND}),Cn=ke.BEHIND_DIALOGUE,Sn=Object.freeze(Object.values(ke).sort((e,t)=>e-t));var Kl={__arrayOrEmpty:e=>Array.isArray(e)?e:[],objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:bn},Jl=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+?)(?::)?$/,Nt=e=>Array.isArray(e)?e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).length!==1)return Nt(t);let[r]=Object.keys(t),n=Jl.exec(r);if(!n)return Nt(t);let[,o,i,s]=n,l=`$for ${o}${i?`, ${i}`:""} in __arrayOrEmpty(${s.trim()})`,a=Array.isArray(t[r])?t[r]:[];return{[l]:Nt(a)}}):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Nt(r)])),Le=(e,t)=>{let r={functions:Kl};return Qe(Nt(e),t,r)},Gn=({animationType:e,animationId:t,animationPath:r})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${r}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},Xl=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);if(Gn({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n!==void 0){let s=tu(n,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},Ql=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Gn({animationType:e.type,animationId:t,animationPath:r}),e.type},Zl=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},eu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},tu=(e,t="animation.playback")=>{if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`[${t}] playback must be an object.`);if(e.continuity!==void 0&&e.continuity!=="render"&&e.continuity!=="persistent")throw new Error(`[${t}] playback.continuity must be "render" or "persistent".`);if(e.speed!==void 0&&(typeof e.speed!="number"||!Number.isFinite(e.speed)||e.speed<=0))throw new Error(`[${t}] playback.speed must be a finite number greater than 0.`);let r={};return e.continuity!==void 0&&(r.continuity=e.continuity),e.speed!==void 0&&e.speed!==1&&(r.speed=e.speed),Object.keys(r).length>0?r:void 0},ru=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},nt=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),qi=e=>e?.playback?.continuity==="persistent",Nn=e=>Array.isArray(e)?e.map(Nn):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=Nn(e[r]),t),{}),yr=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(Nn(t))},Yi=(e=[])=>e.filter(t=>qi(t)).map(t=>structuredClone(t)),Hi=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,r)=>{let n=typeof r?.duration=="number"&&Number.isFinite(r.duration)?r.duration:0;return t+n},0):0,_n=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,Hi(r)),0),Wi=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(_n(e.tween),_n(e.prev?.tween),_n(e.next?.tween),Hi(e.mask?.progress))/ru(e),Ni=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let r=new Set(t.map(yr).filter(Boolean));return e.some(n=>{if(!qi(n))return!1;let o=yr(n);return o?r.has(o):!1})},Se=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||Ni({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:Ni({animationInstances:e,activePersistentAnimations:o}),nu=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),ou=(e,t)=>{if(nu(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},iu=({resources:e,animationId:t,playback:r,instanceId:n,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?Xl({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},su=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Gn({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},zn=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(su(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Pn=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(r=>r===null||typeof r!="object"||Array.isArray(r)))throw new Error(`${t} must be an array of objects`);return e},au=({content:e,path:t,variables:r})=>Pn(e,t).reduce((n,o)=>{let i=ft(o.text,{variables:r});return n+`${i??""}`.length},0),Pi=(e=[])=>{let t=new Map;for(let r of e)r?.id&&t.set(r.id,(t.get(r.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,r])=>r>1).map(([r])=>r))},pr=(e,t=0,r=new Set)=>{if(!r.has(e?.id))return`character-container-${e.id}`;let n=e?.sprites?.map(({resourceId:o})=>o)||[];return n.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${n.join("-")}`},hr=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return r},cu=(e,t={})=>{if(!t?.transformId)return;let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for background`);return r},lu=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],uu=(e={})=>lu.some(t=>nt(e,t)),Ki=(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"}},gr=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},du=(e={})=>e.textStyles||{},fu=(e={})=>e.images||{},pu=.5,hu=(e={},t,r)=>{if(t){if(!e.animations?.[t])throw new Error(`Animation '${t}' not found in spritesheet resource '${r}'`);return t}return Object.keys(e.animations??{})[0]},Ji=({id:e,resourceId:t,spritesheet:r,animationName:n,animationSpeed:o,loop:i,transform:s={}}={})=>{let l=hu(r,n,t),a=l?r.animations?.[l]:void 0;if(!a){console.warn(`Spritesheet animation not found: ${t}`);return}return{id:e,type:"spritesheet-animation",...s,width:r.width,height:r.height,src:r.fileId,atlas:r.jsonData,playback:{frames:a.frames,animationSpeed:o??a.animationSpeed??pu,loop:i??a.loop??!0}}},Xi=({id:e,item:t,resources:r={}}={})=>{let n=r.images?.[t.resourceId];if(n)return{type:"sprite",id:e,src:n.fileId,width:n.width,height:n.height,x:0,y:0};let o=r.spritesheets?.[t.resourceId];if(o)return Ji({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}`)},mu=(e={})=>e.colors||{},gu=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Vt=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,mt=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},On=(e,t,r)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);return e},Rn=(e,t,r,n,{minimum:o}={})=>{if(e===void 0)return n;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 "${r}" must be ${i}`)}return e},Ar=(e,t)=>{if(typeof e!="string"||!gu.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(r=>r.repeat(2)).join("")}`:e},Di=(e,t,r)=>{let n=Ar(e,r);if(t===1)return n;let o=Number.parseInt(n.slice(1,3),16),i=Number.parseInt(n.slice(3,5),16),s=Number.parseInt(n.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},yu=(e={},t)=>{let r=du(e)?.[t];if(!r)throw new Error(`Text style "${t}" not found`);let o=(Array.isArray(r.fontId)?r.fontId:[r.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?.[r.colorId];if(!i)throw new Error(`Color "${r.colorId}" not found for text style "${t}"`);let s=On(r.colorAlpha,"colorAlpha",t),l={fontFamily:Array.isArray(r.fontId)?o.join(", "):o[0],fontSize:r.fontSize??16,fontWeight:r.fontWeight??"400",fontStyle:r.fontStyle??"normal",lineHeight:r.lineHeight??1.2,fill:Di(i.hex,s,`Color "${r.colorId}" for text style "${t}"`)};if(r.align!==void 0&&(l.align=r.align),r.wordWrap!==void 0&&(l.wordWrap=r.wordWrap),r.breakWords!==void 0&&(l.breakWords=r.breakWords),r.wordWrapWidth!==void 0&&(l.wordWrapWidth=r.wordWrapWidth),r.strokeColorId){let a=e.colors?.[r.strokeColorId];if(!a)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let c=On(r.strokeAlpha,"strokeAlpha",t);l.strokeColor=Di(a.hex,c,`Stroke color "${r.strokeColorId}" for text style "${t}"`)}else if(r.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);if(r.strokeWidth!==void 0&&(l.strokeWidth=r.strokeWidth),r.shadow!==void 0){let a=e.colors?.[r.shadow.colorId];if(!a)throw new Error(`Shadow color "${r.shadow.colorId}" not found for text style "${t}"`);l.shadow={color:Ar(a.hex,`Shadow color "${r.shadow.colorId}" for text style "${t}"`),alpha:On(r.shadow.alpha,"shadow.alpha",t),blur:Rn(r.shadow.blur,"blur",t,0,{minimum:0}),offsetX:Rn(r.shadow.offsetX,"offsetX",t,2),offsetY:Rn(r.shadow.offsetY,"offsetY",t,2)}}return l},Dn=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Dn(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${r}". Use textStyleId instead`);let n={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(n[o]=Dn(i,t,Vt(r,o)));return e.textStyleId!==void 0&&(mt(e.textStyleId,r,"textStyleId"),n.textStyle=yu(t,e.textStyleId)),n},qn=(e={},t)=>{let r=mu(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return Ar(r.hex,`Color "${t}"`)},Qi=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",$n=(e,t,r)=>{let n=e?.[t];if(!(!n||typeof n!="object"||Array.isArray(n))&&Object.prototype.hasOwnProperty.call(n,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${r}". Use ${Qi(`${t}.fill`)} instead`)},bu=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>jt(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;let n={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(n[o]=jt(i,t,Vt(r,o)));return e.colorId!==void 0&&(mt(e.colorId,r,"colorId"),n.fill=qn(t,e.colorId)),n},jt=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>jt(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${r}". Use ${Qi("fill")} instead`);$n(e,"hover",r),$n(e,"click",r),$n(e,"rightClick",r)}let n={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){n[o]=bu(i,t,Vt(r,o));continue}n[o]=jt(i,t,Vt(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(mt(e.colorId,r,"colorId"),n.fill=qn(t,e.colorId)),n},kn=(e={},t)=>{let r=fu(e)?.[t];return r||null},Zi=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",Vi=(e,t,r,n)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,n))throw new Error(`Inline ${t}.${n} is not allowed in sprite layout elements at "${r}". Use ${Zi(`${t}.${n}`)} instead`)},ji=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},Vn=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Vn(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${r}". Use ${Zi(o)} instead`);Vi(e,"hover",r,"src"),Vi(e,"click",r,"src")}let n={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(n[o]=Vn(i,t,Vt(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){mt(e.imageId,r,"imageId");let o=kn(t,e.imageId),i=o?.fileId??e.imageId;n.src=i,n.width===void 0&&o?.width!==void 0&&(n.width=o.width),n.height===void 0&&o?.height!==void 0&&(n.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(mt(e.hoverImageId,r,"hoverImageId"),ji(n,"hover",kn(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(mt(e.clickImageId,r,"clickImageId"),ji(n,"click",kn(t,e.clickImageId)?.fileId??e.clickImageId)),n},Yn=(e,t={},r="root")=>Vn(jt(Dn(e,t,r),t,r),t,r),Te=Yn,it=(e=[])=>e.find(t=>t.id==="story"),Iu="#000000",jn="bg-cg-background-color",Au=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?Ar(r?.backgroundColor??Iu,"screen.backgroundColor"):qn(e,t.colorId),es=(e={})=>{if(nt(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},wu=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Mi=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=es(e),n=wu(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},Eu=(e={})=>{if(nt(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},xu=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},ts=(e={})=>{let t=Eu(e),r=xu(e),n={};return t!==void 0&&(n.alpha=t),r&&(n.blur=r),n},Pt=(e={})=>ts(e),Fe=(e={},t={})=>{let r={x:t.x??e.x,y:t.y??e.y,anchorX:t.anchorX??e.anchorX,anchorY:t.anchorY??e.anchorY,rotation:t.rotation??e.rotation,scaleX:t.scaleX??e.scaleX,scaleY:t.scaleY??e.scaleY},n=t.originX??e.originX,o=t.originY??e.originY;return n!==void 0&&(r.originX=n),o!==void 0&&(r.originY=o),r},vu=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],Hn=(e={})=>e.text&&nt(e.text,"content")&&nt(e.text,"textStyleId"),Fi=(e={})=>{if(e.resourceId)return e.resourceId;if(Hn(e))return"text"},Cu=e=>{if(e.text){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!Hn(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let t of vu)if(nt(e.text,t))throw new Error(`Visual item "${e.id}" text.${t} is reserved for the visual item`)}},Su=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:jn,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:Au({resources:e,background:t,screen:r})};if(n){let i=es(t);i!==void 0&&(o.alpha=i)}return o},_u=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.spritesheets?.[t]||e.layouts?.[t]):!1,Ui=({resources:e={},resourceId:t,colorId:r})=>{let n=Ki(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:gr({resourceId:t,kind:n})}:r!==void 0?{resourceId:jn,targetId:jn}:{resourceId:void 0,targetId:void 0}},rs=100,ot=rs,Ou="channel:bgm",Ru="channel:voice",$u="default",ku=e=>String(e).replaceAll("%","%25").replaceAll(":","%3A"),Dt=(...e)=>e.map(ku).join(":"),br=(e,t,r)=>{let n=new Set;e.forEach(({id:o})=>{if(n.has(o)){let i=r?` in ${r}`:"";throw new Error(`Duplicate ${t} id "${o}"${i}.`)}n.add(o)})},Lu=(e,t)=>e*t/rs,ns=(e={},t)=>e?.[t]??tt[t],Wn=(e={},t,r=ot)=>Lu(r,ns(e,t)),Kn=({id:e,volume:t,muted:r,pan:n,loop:o,interruption:i,children:s,runtime:l})=>{let a={id:e,type:"audio-channel",volume:t,muted:!!l?.muteAll||(r??!1),pan:n??0,children:s};return o!==void 0&&(a.loop=o),i!==void 0&&(a.interruption=i),a},mr=(e,t,r,n)=>e[r]!==void 0?e[r]:t[r]!==void 0?t[r]:n,Tu=["muted","pan","playbackRate","startAt","endAt"],Jn=({id:e,sound:t,resource:r,defaultLoop:n=!1})=>{let o={id:e,type:"sound",src:r.fileId,loop:mr(t,r,"loop",n),volume:mr(t,r,"volume",ot),startDelayMs:mr(t,r,"startDelayMs",0)};Tu.forEach(s=>{let l=mr(t,r,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},_e=({variables:e,imageGallery:t,runtime:r,saveSlots:n=[],dialogueState:o,includeInactiveAdvDialogue:i=!1,isLineCompleted:s,autoMode:l,skipMode:a,isChoiceVisible:c,isFormVisible:u,canRollback:d,confirmDialog:f,form:p,historyDialogue:h=[],characters:g={},dialogueUIHidden:I,skipOnlyViewedLines:b,skipTransitionsAndAnimations:w}={})=>{let S={dialogueTextSpeed:r?.dialogueTextSpeed??50,autoForwardDelay:r?.autoForwardDelay??1e3,autoForwardSpeed:r?.autoForwardSpeed??1,skipUnseenText:r?.skipUnseenText??!1,skipTransitionsAndAnimations:r?.skipTransitionsAndAnimations??!1,soundVolume:r?.soundVolume??50,musicVolume:r?.musicVolume??50,muteAll:r?.muteAll??!1,saveLoadPagination:r?.saveLoadPagination??1,menuPage:r?.menuPage??"",menuEntryPoint:r?.menuEntryPoint??"",autoMode:r?.autoMode??l??!1,skipMode:r?.skipMode??a??!1,dialogueUIHidden:r?.dialogueUIHidden??I??!1,isLineCompleted:r?.isLineCompleted??s??!1},O=ju({dialogueState:o,includeInactiveAdvDialogue:i,characters:g,variables:e,runtime:S}),$={variables:e,imageGallery:t,runtime:S,saveSlots:n,isChoiceVisible:c,isFormVisible:u,canRollback:d,confirmDialog:f,form:p,historyDialogue:h,characters:g};return O&&($.dialogue=O,$.dialogueLines=O.lines),$},Bi=100,Ir=(e,t)=>{if(Array.isArray(e))return e.map(n=>Ir(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=Ir(r[n],t)}),r.type==="text-revealing"?t(r):r},Nu=e=>Ir(e,t=>({...t,revealEffect:"none"})),Pu=e=>Ir(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,Bi):Bi;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),Ue=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?Nu(e):r?Pu(e):e,os=({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:{}}}}),Mn=e=>{if(Array.isArray(e))return e.map(Mn);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Mn(s);let r=t.click?.payload;if(!r||typeof r!="object"||Array.isArray(r))return t;let n=r.actions,o=n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"nextLine")?{...n.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...r,bypassChoice:!0,...o?{actions:{...n,nextLine:o}}:{}}}}},Du=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),Gi="submit",Ln=(e,t,r={})=>{let n=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},o=n.actions&&typeof n.actions=="object"?n.actions:{},i=r.replaceActions===!0?t:{...o,...t};return{...e||{},payload:{...n,actions:i}}},Fn=(e,t,r={})=>{if(Array.isArray(e))return e.map(c=>Fn(c,t,r));if(!e||typeof e!="object")return e;let n=typeof e.type=="string",o=n&&e.formRole===Gi,i=n&&r.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},l={};for(let[c,u]of Object.entries(e))l[c]=Fn(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:Ln(a.change,u),submit:Ln(a.submit,t.submitActions)}}}return a.formRole===Gi||i?{...a,click:Ln(a.click,t.submitActions,{replaceActions:!0})}:a},Un=(e,t)=>{if(Array.isArray(e))return e.map(n=>Un(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Un(o,t);for(let n of Du){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form"}})}return r},Bn=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0,s=lr({characterId:e,character:t,characterName:r,characters:n,variables:o});return{...i||{},...t||{},name:s}},is=(e=[],t={},r={})=>e.map(n=>{let o=Bn({characterId:n.characterId,character:n.character,characterName:n.characterName,characters:t,variables:r}),i=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(s=>s?.text??"").join(""):"";return{...n,text:i,character:o,characterName:o.name}}),Vu=e=>!(!e||e.mode==="adv"&&e.content===void 0),ju=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n,runtime:o}={})=>{if(!t&&!Vu(e))return;let i=e.content===void 0?[{text:""}]:Pn(e.content,"dialogue.content"),s=e.content===void 0?0:au({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),l=o?.dialogueTextSpeed??tt.dialogueTextSpeed,a=e.textSpeed??l,c=(e.lines||[]).map((d,f)=>{let p=Pn(d.content,`dialogue.lines[${f}].content`),h=Bn({characterId:d.characterId,character:d.character,characterName:d.characterName,characters:r,variables:n});return{...d,textSpeed:d.textSpeed??l,content:p.map(g=>({...g,text:ft(g.text,{variables:n})})),character:h,characterName:h.name}}),u=Bn({characterId:e.characterId,character:e.character,characters:r,variables:n});return{characterId:e.characterId,persistCharacter:e.persistCharacter,persistSprite:e.persistSprite,character:u,textSpeed:a,content:i.map(d=>({...d,text:ft(d.text,{variables:n})})),initialRevealedCharacters:s,lines:c}},ss=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=Le(e,r);return Te(Ue(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},Tn=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),zi=({renderStateKeyboard:e,keyboard:t,phase:r})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([n,o])=>{let i=e[n]??{},s=r==="keydown"?o?.keydown:o?.keyup;if(r==="keydown"&&s&&typeof s=="object"){e[n]={...i,keydown:{payload:Tn(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:Tn(o.keyup)});return}e[n]={...i,[r]:{payload:Tn(o)}}})},Mu=(e={},t={})=>{let r={};return zi({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),zi({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},Ne=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l})=>{if(!e)return[];let a=[],c=({instanceId:b,targetId:w})=>{let S=iu({resources:t,animationId:p,playback:h,instanceId:b,targetId:w,animationPath:s});S&&a.push(S)},u=r!=null&&r!==!1,d=n!=null&&n!==!1,f=o&&i&&o===i;ou(e,s);let p=Zl(e),h=eu(e),g=t?.animations?.[p],I=Ql(g,{animationId:p,animationPath:s});if(I==="update")return d&&i?c({instanceId:`${l}-animation-update`,targetId:i}):u&&o&&c({instanceId:`${l}-animation-update`,targetId:o}),a;if(I==="transition"){let b=`${l}-animation-transition`,w=h?.continuity==="persistent"?b:`${l}-animation-in`;if(u&&d&&f)return c({instanceId:b,targetId:i}),a;u&&c({instanceId:`${l}-animation-out`,targetId:o}),d&&c({instanceId:w,targetId:i})}return a},Fu=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Uu=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:a,imageGallery:c,runtime:u,activePersistentAnimations:d,restoredPersistentAnimations:f,autoMode:p,skipMode:h,isChoiceVisible:g,isFormVisible:I,canRollback:b,form:w,saveSlots:S=[]})=>{let{elements:O,animations:$}=e;if(t.background){let G=n===void 0?!0:nt(n?.background??{},"animations"),T=O.find(le=>le.id==="story");if(!T)return e;let x=cu(o,t.background),q=x||uu(t.background),Y=r?.background?.resourceId,W=r?.background?.colorId,B=t.background.resourceId??(t.background.animations?Y:void 0),te=t.background.colorId??(t.background.animations?W:void 0),re=_u(o,B),de={...t.background,colorId:te};if((te!==void 0||re)&&T.children.push(Su({resources:o,background:de,screen:i,includeOpacity:!re})),B){let{images:le={},videos:ie={},spritesheets:Z={}}=o,X=Ki(o,B),v;if(X==="sprite"?v=le[B]:X==="video"?v=ie[B]:X==="spritesheet-animation"&&(v=Z[B]),v){let R=X==="video",M=X==="spritesheet-animation",fe={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...x},me={...Mi(t.background,{includeDefaultAlpha:!0}),...Fe(fe,t.background)},F;M?F=Ji({id:gr({resourceId:B,kind:X}),resourceId:B,spritesheet:v,animationName:t.background.animationName,animationSpeed:t.background.animationSpeed,loop:t.background.loop,transform:me}):F={id:gr({resourceId:B,kind:X}),type:R?"video":"sprite",src:v.fileId,width:v.width,height:v.height,...me},R&&(F.loop=t.background.loop??!1,F.volume=v.volume??50),F&&T.children.push(F)}}if(B){let{layouts:le={}}=o,ie=le[B];if(ie){let Z={id:gr({resourceId:B,kind:"container"}),type:"container",children:ie.elements,...Mi(t.background)};q&&Object.assign(Z,Fe({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...x},t.background));let X=Le(Z,_e({variables:a,imageGallery:c,runtime:u,saveSlots:S,dialogueState:t.dialogue,isLineCompleted:s,autoMode:p,skipMode:h,isChoiceVisible:g,isFormVisible:I,canRollback:b,form:w,characters:o.characters||{},skipTransitionsAndAnimations:l}));T.children.push(Te(Ue(X,{isLineCompleted:s,skipMode:h,skipTransitionsAndAnimations:l}),o))}}let Oe=Ui({resources:o,resourceId:Y,colorId:W}),ne=Ui({resources:o,resourceId:B,colorId:te}),oe=Ne({animationsDef:t.background.animations,resources:o,previousResourceId:Oe.resourceId,currentResourceId:ne.resourceId,previousTargetId:Oe.targetId,currentTargetId:ne.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});Se({animationInstances:oe,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:d,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:G})&&$.push(...oe)}return e},Bu=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:a}=e;if(t.character&&n){let c=l.find(h=>h.id==="story");if(!c)return e;let u=t.character.items||[],d=r?.character?.items||[],f=Pi(u),p=Pi(d);for(let h=0;h<u.length;h++){let g=u[h],{transformId:I,sprites:b}=g,w=d.find(W=>W.id===g.id),S=d.findIndex(W=>W.id===g.id),O=w?.sprites&&w.sprites.length>0,$=b&&b.length>0,G=S>=0?pr(w,S,p):void 0,T=Ne({animationsDef:g.animations,resources:n,previousResourceId:G,currentResourceId:$?pr(g,h,f):void 0,previousTargetId:G,currentTargetId:$?pr(g,h,f):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!I&&O&&Se({animationInstances:T,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...T);continue}if(g.animations&&!b&&!I)continue;if(!b||b.length===0||!I){console.warn("Character item missing sprites or transformId:",g);continue}let x=pr(g,h,f),q=n.transforms[I];if(!q){console.warn("Transform not found:",I);continue}let Y={type:"container",id:x,...Fe(q,g),...Pt(g),children:[]};for(let W of b){let B=Xi({id:`${x}-${W.id}`,item:W,resources:n});B&&Y.children.push(B)}c.children.push(Y),Se({animationInstances:T,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...T)}}return e},as=(e,t)=>{if(!Sn.includes(e))throw new Error(`${t} must be one of: ${Sn.join(", ")}.`)},Gu=(e,t)=>{let r=!!e.resourceId||Hn(e),n=e.layer??(r?void 0:t?.layer)??Cn;return as(n,`Visual item "${e.id}" layer`),n},zu=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,imageGallery:l,runtime:a,activePersistentAnimations:c,autoMode:u,skipMode:d,isChoiceVisible:f,isFormVisible:p,canRollback:h,form:g,saveSlots:I=[],visualLayer:b})=>{let{elements:w,animations:S}=e;if(t.visual&&n){let O=w.find(x=>x.id==="story");if(!O)return e;let $=t.visual.items,G=r?.visual?.items||[],T=_e({variables:s,imageGallery:l,runtime:a,saveSlots:I,dialogueState:t.dialogue,isLineCompleted:o,autoMode:u,skipMode:d,isChoiceVisible:f,isFormVisible:p,canRollback:h,form:g,characters:n.characters||{},skipTransitionsAndAnimations:i});b!==void 0&&as(b,"visualLayer");for(let x of $){let q=G.find(re=>re.id===x.id),Y=Gu(x,q);if(b!==void 0&&Y!==b)continue;if(Cu(x),x.text){let re=hr(n,x),de={...structuredClone(x.text),id:`visual-${x.id}`,type:"text",...Fe(re,x)};Object.assign(de,Pt(x)),O.children.push(Te(Le(de,T),n))}if(x.resourceId){let{images:re={},videos:de={},spritesheets:Oe={}}=n,ne=Oe[x.resourceId];if(ne){let oe=hr(n,x),le=x.animationName;if(le){let ie=ne.animations?.[le];if(!ie)throw new Error(`Animation '${le}' not found in spritesheet resource '${x.resourceId}'`);let Z=Pt(x),X={id:`visual-${x.id}`,type:"spritesheet-animation",...Fe(oe,x),width:x.width??ne.width,height:x.height??ne.height,alpha:Z.alpha??x.alpha??1,src:ne.fileId,atlas:ne.jsonData,playback:{frames:ie.frames,animationSpeed:x.animationSpeed??ie.animationSpeed??.5,loop:x.loop??ie.loop??!0}};Z.blur&&(X.blur=Z.blur),O.children.push(structuredClone(X))}}else{let oe=re[x.resourceId]||de[x.resourceId];if(oe){let le=de[x.resourceId]!==void 0,ie=hr(n,x),Z={id:`visual-${x.id}`,type:le?"video":"sprite",src:oe.fileId,width:oe.width,height:oe.height,...Fe(ie,x)};Object.assign(Z,Pt(x)),le&&(Z.loop=oe.loop??!1,Z.volume=oe.volume??50),O.children.push(Z)}}}if(x.resourceId){let{layouts:re={}}=n,de=re[x.resourceId];if(de){let Oe=hr(n,x),ne={id:`visual-${x.id}`,type:"container",children:structuredClone(de.elements),...Fe(Oe,x)};Object.assign(ne,Pt(x));let oe=Le(ne,T);O.children.push(Te(Ue(oe,{isLineCompleted:o,skipMode:d,skipTransitionsAndAnimations:i}),n))}}let W=Fi(q),B=Fi(x),te=Ne({animationsDef:x.animations,resources:n,previousResourceId:W,currentResourceId:B,previousTargetId:W?`visual-${x.id}`:void 0,currentTargetId:B?`visual-${x.id}`:void 0,animationPath:`visual.items[${x.id}].animations`,idPrefix:x.id});Se({animationInstances:te,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:c})&&S.push(...te)}}return e},ht="dialogue-character-sprite",qu=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=it(e.elements);if(!a)return e;let c=t.dialogue?.character?.sprite,u=r?.dialogue?.character?.sprite,d=_t(c),f=_t(u),p=Ne({animationsDef:c?.animations,resources:n,previousResourceId:f?ht:void 0,currentResourceId:d?ht:void 0,previousTargetId:f?ht:void 0,currentTargetId:d?ht:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!d)return c?.animations&&f&&Se({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e;let h=n.transforms?.[c.transformId];if(!h)return console.warn("Transform not found:",c.transformId),e;let g={type:"container",id:ht,...Fe(h),children:[]};for(let I of c.items){let b=Xi({id:`${ht}-${I.id}`,item:I,resources:n});b&&g.children.push(b)}return a.children.push(g),Se({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e},Yu=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,skipOnlyViewedLines:d,isLineCompleted:f,skipTransitionsAndAnimations:p,variables:h,imageGallery:g,runtime:I,activePersistentAnimations:b,saveSlots:w=[]})=>{let{elements:S,animations:O}=e;if(!t.dialogue||o)return e;let $=S.find(T=>T.id==="story");if(!$)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:T={}}=n,x=T[t.dialogue.ui.resourceId];if(x){let q={elements:x.elements},Y=_e({variables:h,imageGallery:g,runtime:I,saveSlots:w,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:f,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:d,skipTransitionsAndAnimations:p}),W=Le(q,Y),B=Te(Ue(W?.elements,{isLineCompleted:f,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(B))for(let te of B)$.children.push(te);else B&&$.children.push(B)}}qu(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:b});let G=Ne({animationsDef:t.dialogue.ui?.animations,resources:n,previousResourceId:r?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:r?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return Se({animationInstances:G,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:b})&&O.push(...G),e},Hu=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,imageGallery:a,runtime:c,autoMode:u,skipMode:d,isChoiceVisible:f,isFormVisible:p,canRollback:h,form:g,activePersistentAnimations:I,saveSlots:b=[]})=>{let{elements:w,animations:S}=e;if(t.choice&&n){let O=it(w);if(!O)return e;let $=n?.layouts[t.choice.resourceId];if($&&$.elements){let T={elements:$.elements},x=Le(T,{..._e({variables:l,imageGallery:a,runtime:c,saveSlots:b,dialogueState:t.dialogue,isLineCompleted:i,autoMode:u,skipMode:d,isChoiceVisible:f??!!t.choice,isFormVisible:p,canRollback:h,form:g,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}}),q=Mn(Te(Ue(x?.elements,{isLineCompleted:i,skipMode:d,skipTransitionsAndAnimations:s}),n));if(Array.isArray(q))for(let Y of q)O.children.push(Y);else q&&O.children.push(q)}let G=Ne({animationsDef:t.choice.animations,resources:n,previousResourceId:r?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:r?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});Se({animationInstances:G,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:I})&&S.push(...G)}return e},Wu=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,imageGallery:a,runtime:c,autoMode:u,skipMode:d,isChoiceVisible:f,isFormVisible:p,canRollback:h,activePersistentAnimations:g,saveSlots:I=[],form:b})=>{let{elements:w,animations:S}=e;if(!b?.resourceId||!n)return e;let O=it(w);if(!O)return e;let $=n?.layouts?.[b.resourceId];if(!$)return console.warn(`Form layout not found: ${b.resourceId}`),e;let G={id:"form-container",type:"container",x:0,y:0,children:$.elements||[]},T={..._e({variables:l,imageGallery:a,runtime:c,saveSlots:I,dialogueState:t.dialogue,isLineCompleted:i,autoMode:u,skipMode:d,isChoiceVisible:f,isFormVisible:p,canRollback:h,characters:n.characters||{},skipTransitionsAndAnimations:s,form:b}),form:b},x=Le(G,T),q=Un(Te(Ue(Fn(x,b),{isLineCompleted:i,skipMode:d,skipTransitionsAndAnimations:s}),n),b);q&&O.children.push(q);let Y=Ne({animationsDef:b.animations,resources:n,previousResourceId:r?.form?.resourceId,currentResourceId:b.resourceId,previousTargetId:r?.form?.resourceId?"form-container":void 0,currentTargetId:b.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return Se({animationInstances:Y,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&S.push(...Y),e},Ku=(e,{presentationState:t,resources:r={},variables:n,imageGallery:o,runtime:i,isLineCompleted:s,autoMode:l,skipMode:a,isChoiceVisible:c,isFormVisible:u,canRollback:d,form:f,saveSlots:p=[],skipTransitionsAndAnimations:h})=>{if(!t.control?.resourceId)return e;let g=r.controls?.[t.control.resourceId];if(!g)return e;let I=Mu(g.keyboard,g.keyup);if(I&&Object.keys(I).length>0&&(e.global.keyboard=I),!Array.isArray(g.elements)||g.elements.length===0)return e;let b=it(e.elements);if(!b)return e;let w={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:g.elements};return b.children.push(ss({container:w,resources:r,templateData:_e({variables:n,imageGallery:o,runtime:i,saveSlots:p,dialogueState:t.dialogue,isLineCompleted:s,autoMode:l,skipMode:a,isChoiceVisible:c,isFormVisible:u,canRollback:d,form:f,characters:r.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:s,skipMode:a,skipTransitionsAndAnimations:h})),e},Ju=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!it(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=!c&&a.loop===!0,f=[];if(c||br(u,"BGM sound"),d){let h=u.find(g=>g.loop===!0);if(h)throw new Error(`BGM sound "${h.id}" cannot loop inside a looping BGM channel.`)}if(u.forEach(h=>{let g=r.sounds?.[h.resourceId];if(!g)return;let I=d?{...h,loop:h.loop??!1}:h;f.push(Jn({id:Dt("bgm",c?"default":h.id),sound:I,resource:g,defaultLoop:!d}))}),f.length===0)return e;let p=_e({variables:o,runtime:n}).runtime;s.push(Kn({id:Ou,volume:Wn(p,"musicVolume",c?ot:a.volume??ot),muted:a.muted,pan:a.pan,loop:c?void 0:a.loop,interruption:a.interruption,children:f,runtime:p}))}return e},Xu=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx,s=!Array.isArray(i.channels),l=s?[{id:$u,sounds:i.items??[]}]:i.channels;s||br(l,"SFX channel"),l.forEach(a=>{let c=!s&&a.loop===!0,u=[];if(s||br(a.sounds,"SFX sound",`SFX channel "${a.id}"`),c){let d=a.sounds.find(f=>f.loop===!0);if(d)throw new Error(`SFX sound "${d.id}" cannot loop inside looping SFX channel "${a.id}".`)}a.sounds.forEach((d,f)=>{let p=r.sounds?.[d.resourceId];if(!p)return;let h=c?{...d,loop:d.loop??!1}:d;u.push(Jn({id:s?Dt("sfx","default",f,d.id):Dt("sfx",a.id,d.id),sound:h,resource:p,defaultLoop:c?!1:void 0}))}),u.length!==0&&o.push(Kn({id:Dt("channel","sfx",a.id),volume:Wn(n,"soundVolume",a.volume??ot),muted:a.muted,pan:a.pan,loop:s?void 0:a.loop,interruption:s?void 0:a.interruption,children:u,runtime:n}))})}return e},Qu=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},Zu=(e,{presentationState:t,resources:r,currentSceneId:n,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:ot,startDelayMs:l.startDelayMs??0}]:[]:l.sounds,u=!a&&l.loop===!0,d=[];if(a||br(c,"Voice sound"),u){let p=c.find(h=>h.loop===!0);if(p)throw new Error(`Voice sound "${p.id}" cannot loop inside a looping Voice channel.`)}if(c.forEach(p=>{let h=Qu(r,n,p.resourceId);if(!h)return;let g=u?{...p,loop:p.loop??!1}:p;d.push(Jn({id:Dt("voice",n,a?"default":p.id),sound:g,resource:h,defaultLoop:u?!1:void 0}))}),d.length===0)return e;let f=_e({variables:i,runtime:o}).runtime;return s.push(Kn({id:Ru,volume:a?l.volume??ns(f,"soundVolume"):Wn(f,"soundVolume",l.volume??ot),muted:l.muted,pan:l.pan,loop:a?void 0:l.loop,interruption:l.interruption,children:d,runtime:f})),e},ed=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,imageGallery:i,runtime:s,autoMode:l,skipMode:a,isChoiceVisible:c,isFormVisible:u,canRollback:d,form:f,saveSlots:p=[],isLineCompleted:h,skipTransitionsAndAnimations:g,activePersistentAnimations:I})=>{let{elements:b,animations:w}=e;if(t.layout){let G=it(b);if(!G)return e;let T=n.layouts[t.layout.resourceId];if(!T)return e;Array.isArray(T.transitions)&&!h&&!g&&zn({animations:w,transitions:T.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let x={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:T.elements||[]};G.children.push(ss({container:x,resources:n,templateData:_e({variables:o,imageGallery:i,runtime:s,saveSlots:p,dialogueState:t.dialogue,isLineCompleted:h,autoMode:l,skipMode:a,isChoiceVisible:c,isFormVisible:u,canRollback:d,form:f,characters:n.characters||{},skipTransitionsAndAnimations:g}),isLineCompleted:h,skipMode:a,skipTransitionsAndAnimations:g}))}let S=r?.layout?.resourceId,O=t.layout?.resourceId,$=Ne({animationsDef:t.layout?.animations,resources:n,previousResourceId:S,currentResourceId:O,previousTargetId:S?`layout-${S}`:void 0,currentTargetId:O?`layout-${O}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return Se({animationInstances:$,isLineCompleted:h,skipTransitionsAndAnimations:g,activePersistentAnimations:I})&&w.push(...$),e},td=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=t?.screen?.animations;if(!a)return e;let c=r!=null,u=Ne({animationsDef:a,resources:n,previousResourceId:c?"story":void 0,currentResourceId:"story",previousTargetId:c?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return Se({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...u),e},rd=(e,{presentationState:t})=>{let r=it(e.elements);return!r||!t?.screen||Object.assign(r,ts(t.screen)),e},nd=(e,{presentationState:t,resources:r={},variables:n,imageGallery:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,overlayStack:f=[],dialogueHistory:p=[],saveSlots:h=[],screen:g,isLineCompleted:I,skipTransitionsAndAnimations:b})=>{let{elements:w,animations:S}=e;return f&&f.length>0&&f.forEach((O,$)=>{let G=r.layouts[O.resourceId];if(!G){console.warn(`Overlay layout not found: ${O.resourceId}`);return}Array.isArray(G.transitions)&&(b||zn({animations:S,transitions:G.transitions,defaultTargetId:`overlayStack-${$}`,idPrefix:`overlayStack-${$}`,animationPathPrefix:`overlayStack[${$}]`}));let T={id:`overlayStack-${$}`,type:"container",x:0,y:0,children:[os({id:`overlayStack-${$}-blocker`,screen:g}),...G.elements||[]]},x=is(p,r.characters,n),q=_e({variables:n,imageGallery:o,runtime:i,saveSlots:h,dialogueState:t?.dialogue,isLineCompleted:I,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,historyDialogue:x,characters:r.characters||{},skipTransitionsAndAnimations:b}),Y=Le(T,q),[W,...B]=Y.children||[],te=Te(Ue({...Y,children:B},{isLineCompleted:I,skipMode:l,skipTransitionsAndAnimations:b}),r);w.push({...te,children:W?[W,...te.children||[]]:te.children})}),e},od=(e,{presentationState:t,resources:r={},variables:n,imageGallery:o,runtime:i,saveSlots:s=[],autoMode:l,skipMode:a,isChoiceVisible:c,isFormVisible:u,canRollback:d,form:f,confirmDialog:p,dialogueHistory:h=[],screen:g,isLineCompleted:I,skipTransitionsAndAnimations:b})=>{let{elements:w,animations:S}=e;if(!p?.resourceId)return e;let O=r.layouts?.[p.resourceId];if(!O)return console.warn(`ConfirmDialog layout not found: ${p.resourceId}`),e;Array.isArray(O.transitions)&&!b&&zn({animations:S,transitions:O.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let $={id:"confirmDialog",type:"container",x:0,y:0,children:[os({id:"confirmDialog-blocker",screen:g}),...O.elements||[]]},G=is(h,r.characters,n),T=Le($,_e({variables:n,imageGallery:o,runtime:i,saveSlots:s,dialogueState:t?.dialogue,isLineCompleted:I,autoMode:l,skipMode:a,isChoiceVisible:c,isFormVisible:u,canRollback:d,form:f,confirmDialog:p,historyDialogue:G,characters:r.characters||{},skipTransitionsAndAnimations:b})),[x,...q]=T.children||[],Y=Te(Ue({...T,children:q},{isLineCompleted:I,skipMode:a,skipTransitionsAndAnimations:b}),r);return w.push({...Y,children:x?[x,...Y.children||[]]:Y.children}),e},Mt=e=>(t,r)=>zu(t,{...r,visualLayer:e}),id=Mt(ke.BEHIND_BACKGROUND),sd=Mt(ke.BEHIND_CHARACTER),ad=Mt(ke.BEHIND_DIALOGUE),cd=Mt(ke.BEHIND_CHOICE),ld=Mt(ke.FOREGROUND),cs=e=>cr(Fu,[Ku,id,Uu,sd,Bu,ad,Yu,cd,Hu,Wu,ed,ld,rd,td,Ju,Xu,Zu,nd,od])(e);function ls(e,t=""){let r=[],n=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<n;){let a=s+1+l();s=a+l(),r.push([a,s,t?parseInt(t[i++],36):0])}return r}function us(e,t,r){let n=0,o=t.length-1;for(;n<=o;){let i=n+o>>>1,s=r[i];if(e<t[i])o=i-1;else if(e>s>>>5)n=i+1;else return s&31}return 0}var ds="090001000h1v5g2903000hl2v6jh16ng1s210111110o35aa10u2k1g10l6600152113h2010u1q1r5aq3890o13181214r22k3158q2n1000v100h1k20000001207030001160721k171001h1j11610332010010321210090411021c1c02100o301201412230u1130b100h1j116111420120411001100k11l10051001h1j11611142011000321210072411021d0g10r3000000132120090o200200g1j11f2012031213711271t1001o301001000001121371b1f0c101h1l2011001031212000080a1t1001m40400102101600i11t301006c7i601008b6p41r10101041h3d0004115a1j290p3q223000511010100g1501010302003172030c0010016000e0i6v50n40n5tl12ir33s12t11u11cj30100060700010a90t220000l71i20m7203010241000502rd101004k300000006101027050920g3t22bk1300616g209030207u18c1000t10003010501b2o20000102000004g37070101o921c000640602001mcv3rg20000001o16d0c0m1fg6g2h30m10q55f1vm11c0ma0p1a42nc0ne1a090q3314902021204020112030318250105bb1201110i1021i15101131502141b15120511011k1155132040202510201010603060a1f02040104210b1g3290e0e0kn11vs12j11j3040pp12t80g6v1vmo7319g21g51gh103040n11010040j51i3f01q1h1d0m27p1a0000cs13200523j200010301010100v140018a4q2501010101c08000i1f12601011g3012215110u1a0001015000pcq181000100011000iji5fvc0u91g5bhg20ie0l94lo6002115303121s12240la1tj23h44tj11t45m4ah33q700000l3ep2021a200t220301012040a0i320j2040007f00100r20c100g3208000011531000s520201036020t900207l1101n311000000321210090a12634b910201l22001051020120011020000e1i520701020000n10h5001050000010000010001re0010323010001r11i520701000001q6000000107l600000230004gg12080001lc62027111n1000411230000000000t820321030030r10090n205001380800501020n2050c0001mc00002000000nc006150000i5l1100600010001q753011160000i441111000000rl11019100000c1h201043102n10ltk1f006eoss2b0202gs94r36si2033ku101m373h50b1rqs4113sli1t22m1uh2435070726u13k92rr7m34h380e0m141egl561g1261114k60ga6nn10t33sv13uf1jf0207150qt16t66pr60n23k6bf1f0e1l29g71c1e029j1n30p11ea0k1028139m16rb2v621122i52213040tf1u3b51n17127c0232041d120819052c28220104060306l5g3l4572g130152cqdl2c3o37a5o27u11c32d9m2cu2191obo57eh9gg1tv3",fs="262122424333333393233393339333333333393393bf3b3b3b3b3f3f3bffff33b3bb33ff3f33b3b3333333bffff3b33bb33f33bffff33b3bb33ff3f33b3bbb333b3ff33b333f33b3b3b3b3333b3bf33b3bb39333b33b33b3b3b333b333333b3b33333f3b33b3ffb3f3fff3f3b33f35dc33333f3b3b3b33323333b3bb3b33b3fb3b3333b33333bff3b3f33bfb3b3ff3b3b3b3b3b333b333b3323e22442344444444444444444444444444444444444444444444444444444444444444444444444444444443333333333b3b3bb33333b353bff3b3b3b3f3ff3b3b333bfff3f33333fb3bb3fb3b3bb33232333f333fff333333333b3b3333bb3b39393f3b3fbf33bb3b393b3b3b3333b33b33b3bbb33b33ffff3b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b3fffff3bb39b9b3b33b3bf3f3b33f3b3f93b33b3b3bb33b33b3b3b3333393b3b3b33b39bffb3b332333b333dd3b3333233332333333333333333333333333333444444444444a4444444444444344444444444444444444444444444444444444444444",ps="0001000000010010000000100000000000000000000000000001000000010014000100000001001000010101100101100000000000000000000100000001111000010000000110101001110111111111000100000021001000010000000100100001000000011010000100000001111000013000000100140001000000010010";var hs=65535,Xn=40960,wr=126976,ys=new Uint8Array(12288),bs=new Uint8Array(3072),Is=new Uint8Array(2816),As,ws;{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),r=new Uint32Array(320),n=0;for(let[o,i,s]of ls(ds,fs))e(ys,0,o,i,s),e(bs,Xn,o,i,s),e(Is,wr,o,i,s),i>=65040&&!(o>=wr&&i<=129791)&&(t[n]=o,r[n++]=i<<5|s);As=t.slice(0,n),ws=r.slice(0,n)}function ms(e){return e<12288?ys[e]:e<Xn?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?bs[e-Xn]: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>=wr&&e<129792?Is[e-wr]:e>=917504?e>921599?0:e>=917536&&e<917632||e>=917760&&e<918e3?3:2:us(e,As,ws)}var Es=Uint8Array.from(ps,Number);function ud(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 gs(e,t,r){switch(t){case 3:return e&24?r===8204?e&6:(e&24)===16||ud(r)?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*xs(e){let t=e.length;if(t===0)return;let r=e.codePointAt(0),n=r>hs?2:1,o=ms(r),i=50200>>o&1?gs(0,o,r):0,s=0,l=r,a=o;for(;n<t;){r=e.codePointAt(n);let c=r>hs?2:1,u=ms(r),d=Es[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)?gs(i,u,r):0,f&&(yield{segment:e.slice(s,n),index:s,input:e,_hd:l,_catBegin:a===15?0:a,_catEnd:o===15?0:o},s=n,l=r,a=u),n+=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*vs(e){for(let t of xs(e))yield t.segment}{let e=xs("_");Es._keep=[e,e.next()]}var Cs=1e3,dd=1,fd=60,pd=3,hd=.5,md=2e4,gd=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,yd=/^\s+$/u,Ss,bd=e=>{let t=`${e??""}`.normalize("NFC"),r=globalThis.Intl?.Segmenter;return typeof r!="function"?Array.from(vs(t)):(Ss??=new r(void 0,{granularity:"grapheme"}),Array.from(Ss.segment(t),({segment:n})=>n))},Id=e=>bd(e).reduce((t,r)=>yd.test(r)?t+hd:gd.test(r)?t+pd:t+1,0),_s=({text:e="",baseDelay:t=Cs,speed:r=dd}={})=>{let n=Number.isFinite(t)?Math.max(0,t):Cs,o=Number.isFinite(r)&&r>0?r:1,i=Id(e)*fd/o,s=Math.max(n,md);return Math.min(n+i,s)};var Er={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Ts=1,Zn=1,yt="choice",Be="form",Cr=()=>({manual:{...Er.manual},auto:{...Er.auto},applyMode:Er.applyMode}),eo=()=>({groupId:null,variantId:null,pageIndex:0}),to=new Set,Ad=new Set(["groupId","variantId"]),wd=new Set(["pageIndex"]),ro=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...Cr()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},D=e=>{let t=se(e)?Je(e):e;return structuredClone(t)},P=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ns=(e,t)=>{if(typeof t!="string"||t.length===0)throw new Error("Achievement action requires a non-empty resourceId");let r=e.projectData.resources?.achievements?.[t];if(!r)throw new Error(`Achievement resource "${t}" not found`);if(r.type!=="boolean"&&r.type!=="number")throw new Error(`Achievement resource "${t}" has invalid type "${r.type}"`);return r},Bt=e=>String(e),Ps=()=>({sections:[],resources:[]}),Ed=e=>P(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Ps(),xd=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",vd=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:xd(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),Cd=()=>({resourceId:void 0}),Sd=e=>{if(!P(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},bt=(e,t)=>{let r=e?.story?.scenes??{};for(let[n,o]of Object.entries(r))if(o?.sections?.[t])return{sceneId:n,section:o.sections[t]};return{sceneId:void 0,section:void 0}},Ds=e=>{let t=e?.story?.scenes??{},r=new Map;for(let[n,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let l=r.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},Vs=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},js=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Ts)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},_d=(e,t={})=>{let r;try{r=js(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:Vs(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},Od=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,_d(t,r)])),Ms=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Up(r));return t.length>0?t:void 0},Rd=e=>{!P(e)||!Array.isArray(e.timeline)||(e.returnabilityVersion=Zn,e.timeline.forEach(t=>{if(!P(t))return;typeof t.returnable!="boolean"&&delete t.returnable;let r=Ms(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions}))},Os=(e,t,r,n="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!P(e))throw new Error(`Malformed ${n}.${t}[${r}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${n}.${t}[${r}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${n}.sections[${r}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},$d=(e,t="viewedRegistry")=>{if(e===void 0)return Ps();if(!P(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let r=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Os(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Os(o,"resources",i,t);return[s.resourceId,s]})))}},Fs=(e,t,r)=>{if(!P(e))throw new Error(`Malformed save slot ${r}.`);let{sectionId:n,lineId:o}=e;if(typeof n!="string"||n.length===0)throw new Error(`Malformed save slot ${r}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${r}: missing lineId.`);let{sceneId:i,section:s}=bt(t,n);if(!s)throw new Error(`Malformed save slot ${r}: section "${n}" does not exist in projectData.`);if(!s.lines?.some(a=>a.id===o))throw new Error(`Malformed save slot ${r}: line "${o}" does not exist in section "${n}".`);return{sceneId:i,sectionId:n,lineId:o}},Us=(e,t)=>e?.sectionId===t?.sectionId&&e?.lineId===t?.lineId,kd=(e,t)=>{let{section:r}=bt(e,t?.sectionId);return r?.lines?.find(n=>n.id===t?.lineId)},Ld=(e,t)=>{let{section:r}=bt(e,t?.sectionId),n=r?.lines?.findIndex(i=>i.id===t?.lineId);if(typeof n!="number"||n<0)return null;let o=r.lines[n+1];return o?{sectionId:t.sectionId,lineId:o.id}:null},Bs=(e,t,r)=>{if(typeof t?.sectionId!="string")return!1;let{section:n}=bt(e,t.sectionId);return Us({sectionId:t.sectionId,lineId:n?.lines?.[0]?.id},r)},Td=new Set(["jumpToLine","rollbackByOffset","rollbackToLine","sectionTransition","resetStoryAtSection"]),gt={always:"always",maybe:"maybe",never:"never"},Nd=e=>{if(!Object.prototype.hasOwnProperty.call(e??{},"when"))return gt.always;let t=e.when,r;if(t===null||typeof t=="boolean"||typeof t=="number")r=t;else if(P(t)&&Object.keys(t).length===1&&Object.prototype.hasOwnProperty.call(t,"literal"))r=t.literal;else return gt.maybe;return r?gt.always:gt.never},Gs=(e,t)=>{if(!Array.isArray(e?.branches))return!1;for(let r of e.branches){let n=Nd(r);if(n!==gt.never){if(t(r))return!0;if(n===gt.always)return!1}}return!1},zs=e=>Gs(e,t=>Object.entries(t?.actions??{}).some(([r,n])=>r==="conditional"?zs(n):Td.has(r))),qs=(e,t,r)=>Gs(t,n=>Object.entries(n?.actions??{}).some(([o,i])=>o==="sectionTransition"?Bs(e,i,r):o==="conditional"?qs(e,i,r):!1)),Pd=(e,t,r)=>{if(!t)return!0;let n=kd(r,e)?.actions;if(!P(n))return!0;if(Bs(r,n.sectionTransition,t))return!1;let o=n.conditional;return o?!(qs(r,o,t)||!(n.choice?.resourceId||n.form?.resourceId)&&!zs(o)&&Us(Ld(r,e),t)):!0},Dd=(e,t,r)=>{if(!P(e)||!Array.isArray(e.timeline))return Ut({pointer:t,replayStartIndex:1});let n=new WeakSet,o=e.timeline.flatMap((c,u)=>{if(!P(c))return[];try{let d=Fs(c,r,`rollback.timeline[${u}]`),f=vr({sectionId:d.sectionId,lineId:d.lineId,rollbackPolicy:c.rollbackPolicy,returnable:c.returnable});typeof c.returnable=="boolean"&&n.add(f);let p=Ms(D(c.executedActions));return p&&(f.executedActions=p),[f]}catch{return[]}});if(o.length===0)return Ut({pointer:t,replayStartIndex:1});e.returnabilityVersion!==Zn&&o.forEach((c,u)=>{!n.has(c)&&!Pd(c,o[u+1],r)&&(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(vr({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}},Vd=(e,t,r)=>{if(!P(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=io(t),o=Fs(e.pointers?.read,t,`contexts[${r}].pointers.read`);if(e.variables!==void 0&&!P(e.variables))throw new Error(`Malformed save slot contexts[${r}].variables entry.`);if(e.runtime!==void 0&&!P(e.runtime))throw new Error(`Malformed save slot contexts[${r}].runtime entry.`);let i=e.variables?dt(D(e.variables),t.resources?.variables??{}):{},s=Jd({loadedContextRuntime:P(e.runtime)?D(e.runtime):{}}),l={currentPointerMode:"read",pointers:{read:o},configuration:P(e.configuration)?D(e.configuration):{},views:Array.isArray(e.views)?D(e.views):[],bgm:P(e.bgm)?D(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:Dd(e.rollback,o,t)};return s&&(l.runtime=s),l},jd=(e,t)=>{if(!P(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((r,n)=>Vd(r,t,n))}},Md=(e,t)=>{if(!P(e))throw new Error("Malformed save slot.");let r=js(e.formatVersion);return{...e,formatVersion:r,state:jd(e.state,t)}},Rs=(e,t,{required:r=!1}={})=>{if(e===void 0){if(r)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let n=D(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},Fd=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Rs(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Rs(e.cancelActions,"cancelActions")}},It=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Ud=e=>(P(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),At=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},Ys=e=>{if(!(!P(e)||!e.animations))return{animations:D(e.animations)}},Bd=(e,t)=>{let r=Ys(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},Gd=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},zd=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},xr=e=>String(e??""),Hs=(e,t)=>{let r=xr(t);return e?.trim===!0?r.trim():r},qd=e=>P(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>P(t)).map(([t,r])=>[t,{id:t,...D(r)}])):{},Yd=(e,t)=>{if(!t||!P(e.global.formDrafts))return;let r=e.global.formDrafts[t];return P(r)?r:void 0},Ws=(e,t)=>{let r=Ud(e);P(r[t])||(r[t]={values:{},touched:{},errors:{},submitted:!1});let n=r[t];return P(n.values)||(n.values={}),P(n.touched)||(n.touched={}),P(n.errors)||(n.errors={}),typeof n.submitted!="boolean"&&(n.submitted=!1),n},no=(e,t)=>{let r=Hs(e,t);return e?.required===!0&&r.length===0?"required":null},Hd=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=ce({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:et(n.slice(0,o+1).map(i=>i.actions||{}))},Wd=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=Gd(t),o=zd(r,n);if(!n||!o)return null;let i=Yd(e,o),s=qd(t),l=_r({state:e}),a={},c=[],u={},d=!0;return Object.entries(s).forEach(([f,p])=>{let h=xr(l?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},f)?xr(i.values[f]):h,I=i?.touched?.[f]===!0,b=no(p,g),w=i?.submitted||I?b:null,S=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,O={id:f,variableId:p.variableId,value:g,initialValue:h,valid:!b,error:w,touched:I,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...S!==void 0?{maxLength:S}:{}};b&&(d=!1),a[f]=O,c.push(O),u[f]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:d,submitted:i?.submitted===!0,fields:a,fieldList:c,values:u,submitActions:{submitForm:{formKey:o,actions:D(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:D(t.cancelActions??{})}}}},st=[],$s="line",oo="interaction",vr=({sectionId:e,lineId:t,rollbackPolicy:r,returnable:n})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free",...typeof n=="boolean"?{returnable:n}:{}}),io=e=>{let{contextVariableDefaultValues:t}=ur(e??{});return D(t)},Ks=()=>({...D(Tt)}),Js=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:D(r),hasLoadedValues:!1};if(!P(e))throw new Error(`Malformed ${n}.`);let o=D(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Xs(s,D(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Kd=({loadedGlobalRuntime:e={}})=>Js({loadedRuntime:e,runtimeIds:xn,defaults:tt,path:"global.runtime"}).runtimeState,Jd=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=Js({loadedRuntime:e,runtimeIds:vn,defaults:Ks(),path:"context.runtime"});return r?t:void 0},Sr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Xd=e=>e.runtime?(vn.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=D(Tt[t]))}),e.runtime):(e.runtime=Ks(),e.runtime),Qd=e=>Ti(e.global),Zd=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Qd(e)}})},ef=e=>Li[e],tf=(e,t)=>{let r=ef(e);if(r==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(r==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(r==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},Xs=(e,t)=>{if(tf(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},Qs=(e,t,r)=>{let n=Xs(t,r);if(t in Tt){let o=Sr(e);if(!o)return n;let i=Xd(o);return i[t]=n,n}return e.global[t]=n,n},Zs=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:D(e)},configuration:{},views:[],bgm:Cd(),variables:io(t),rollback:Ut({pointer:e})}),wt=e=>e?(e.currentPointerMode="read",P(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,rf=(e,{queueRender:t=!0}={})=>{let r=e.contexts?.[e.contexts.length-1],n=r?.pointers?.read;if(!r||!n?.sectionId||!n?.lineId)return null;let o=Zs({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,nf(e,{queueRender:t}),o},nf=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,It(e),At(e),e.global.nextLineConfig=Cr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},ea=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},Ut=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[vr({sectionId:e.sectionId,lineId:e.lineId})]:[]}},ct=(e,t={})=>{if(e?.rollback)return ea(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let r=e?.pointers?.read;return e.rollback=Ut({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},so=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=ct(r);n.isRestoring||(n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1)),n.timeline.push(vr(t)),n.currentIndex=n.timeline.length-1)},of=({state:e})=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;return!Array.isArray(r?.timeline)||typeof r.currentIndex!="number"?null:{checkpointIndex:r.currentIndex,checkpoint:r.timeline[r.currentIndex]??null}},sf=({state:e},t={})=>{let{checkpointIndex:r,checkpointIdentity:n,sectionId:o,lineId:i}=t,l=e.contexts?.[e.contexts.length-1]?.rollback;if(!Number.isInteger(r)||!Array.isArray(l?.timeline)||typeof l.currentIndex!="number")return e;let a=l.timeline[r];return(se(a)?Hr(a):a)!==n||a?.sectionId!==o||a?.lineId!==i||(a.returnable=!1),e},af=({state:e},t={})=>{let{slotId:r,saveSlotIdentity:n,checkpointIndex:o,sectionId:i,lineId:s}=t,l=Bt(r),a=e.global.saveSlots?.[l],c=se(a)?Hr(a):a;if(!a||c!==n)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=Zn,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}})),e},cf=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;if(!r||r.isRestoring||!Array.isArray(r.timeline)||typeof r.currentIndex!="number")return null;let n=st[st.length-1],o=typeof n?.checkpointIndex=="number"?n.checkpointIndex:r.currentIndex;return o<0||o>=r.timeline.length?null:(typeof n?.checkpointIndex!="number"&&o<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,o+1)),r.timeline[o]??null)},lf=({state:e},t={})=>{let r=t?.source===$s?$s:oo,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?(st.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),st.push({checkpointIndex:o.currentIndex,source:r}),e)},uf=({state:e})=>(st.pop(),e),Re=(e,t,r)=>{let o=st[st.length-1]?.source??oo;if(!Bp(t,o))return;let i=cf(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:D(r)}))},ks=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:l}of n){let a=e.projectData.resources?.variables?.[o],c=a?.scope,u=a?.type;if(Ce(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);kt(c,o),dr(u,i,o),yn(u,i,s,o,{roundTo:l}),c==="context"&&(r.variables[o]=fr(r.variables[o],i,s,{roundTo:l}))}},df=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{Gp(e,r,n)})},ff=(e,t)=>{let{sectionId:r,lineId:n}=t,s=ce({state:e},{sectionId:r})?.lines?.find(l=>l.id===n)?.actions;s&&Object.entries(s).forEach(([l,a])=>{Ea(e,l,a)})},ta=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=ct(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&zt({state:e}),e.global.skipMode&&Ge({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=io(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=D(Er),e.global.overlayStack=[],It(e),At(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let l=i;l<=t;l++)l>i&&ro(e),ff(e,n.timeline[l]),df(e,n.timeline[l]);let s=wt(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},pf=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;Ds(t),Rt(t),Ze(t?.resources?.variables??{});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}=ur(t),p={...f,...dt(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:$d(s,"accountViewedRegistry"),nextLineConfig:Cr(),imageGalleryNavigation:eo(),saveSlots:Od(n),overlayStack:[],variables:p,...Kd({loadedGlobalRuntime:i})},contexts:[Zs({pointer:d,projectData:t})]}},hf=({state:e})=>e.global.overlayStack||[],mf=({state:e})=>e.global.pendingEffects,ra=({state:e})=>e.global.skipMode,gf=({state:e})=>e.global.autoMode,na=({state:e})=>e.global.dialogueUIHidden,oa=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(!r)return[];let{sectionId:n,lineId:o}=r.pointers.read,i=ce({state:e},{sectionId:n});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=$t({variables:{...e.global?.variables??{},...Sr(e)?.variables??{}},runtime:rt(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let d of l){let f=d.actions||{};if(c=et([c,f]),!f.dialogue)continue;let p=c.dialogue||{},h=lr({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:u}),g=vd({sectionId:n,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},yf=({state:e})=>e.global.confirmDialog??null,Gt=({state:e},{pointer:t}={})=>{let r=t??Ee({state:e})?.pointer,n=Hd({state:e,pointer:r});return Wd({state:e,form:n.form,pointer:r})},bf=({state:e},{pointer:t}={})=>!!Gt({state:e},{pointer:t}),xe=({state:e},{pointer:t}={})=>{let r=Gt({state:e},{pointer:t});if(r)return{source:Be,formId:r.id,formKey:r.key};let n=aa({state:e,pointer:t});return n?{source:yt,resourceId:n}:null},If=({state:e,registry:t},r)=>{let{sectionId:n,lineId:o}=r,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===n);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let l=ce({state:e},{sectionId:n});if(!l||!l.lines||!Array.isArray(l.lines))return s.lastLineId===o;let a=l.lines.findIndex(u=>u.id===s.lastLineId),c=l.lines.findIndex(u=>u.id===o);return a===-1||c===-1?s.lastLineId===o:c<=a},ia=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},ao=({state:e},t)=>If({state:e,registry:e.global.accountViewedRegistry},t),Af=({state:e},t)=>ia({registry:e.global.accountViewedRegistry},t),Ft=(e,t)=>!ia({registry:e.global.accountViewedRegistry},{resourceId:t.imageId}),co=e=>e.groups.length===0?0:Math.ceil(e.groups.length/e.pageSize),lo=(e,t)=>{let r=co(e);if(r===0)return 0;let n=Number.isInteger(t?.pageIndex)?t.pageIndex:0;return Math.min(Math.max(n,0),r-1)},Qn=(e,t,r,n)=>{for(let o=r+n;o>=0&&o<t.length;o+=n)if(!Ft(e,t[o]))return t[o]},wf=({state:e})=>{let t=e.projectData?.resources?.imageGallery;return t===void 0?void 0:D(t)},sa=({state:e})=>{let t=e.projectData?.resources?.imageGallery;if(t===void 0)return null;let r=e.global.imageGalleryNavigation??eo(),n=co(t),o=lo(t,r),i=o*t.pageSize,s=t.groups.slice(i,i+t.pageSize).map(a=>({groupId:a.id,locked:Ft(e,a.variants[0]),variants:a.variants.map(c=>({variantId:c.id,imageId:c.imageId,locked:Ft(e,c)}))})),l=null;if(typeof r.groupId=="string"&&typeof r.variantId=="string"){let a=t.groups.findIndex(p=>p.id===r.groupId),c=t.groups[a],u=c?.variants.findIndex(p=>p.id===r.variantId),d=u===void 0||u<0?void 0:c.variants[u],f=a<0?-1:Math.floor(a/t.pageSize);d&&f===o&&!Ft(e,d)&&(l={groupId:c.id,variantId:d.id,imageId:d.imageId,canMoveToPreviousVariant:Qn(e,c.variants,u,-1)!==void 0,canMoveToNextVariant:Qn(e,c.variants,u,1)!==void 0})}return{pageGroups:s,selection:l,pagination:{pageIndex:o,pageCount:n,canMoveToPreviousPage:o>0,canMoveToNextPage:o+1<n}}},Ef=({state:e})=>e.global.nextLineConfig,aa=({state:e,pointer:t}={})=>{let r=t??Ee({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=ce({state:e},{sectionId:n})?.lines||[],l=s.findIndex(c=>c.id===o);if(l<0)return;let a;for(let c of s.slice(0,l+1)){let u=c?.actions;if(u?.cleanAll&&(a=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){a=void 0;continue}let d=u.choice;if(d?.resourceId){a=d.resourceId;continue}d?.animations||(a=void 0)}return a},ca=({state:e})=>!!aa({state:e}),xf=({state:e})=>structuredClone(e),vf=({state:e})=>D(e.projectData.resources?.achievements??{}),Cf=({state:e},t)=>{let r=e.projectData.resources?.achievements?.[t?.resourceId];return r===void 0?void 0:D(r)},la=({state:e})=>e.global.saveSlots,Sf=({state:e},t)=>{let r=t?.slotId,n=Bt(r);return e.global.saveSlots[n]},uo=({state:e})=>rt(e),_f=({state:e},t)=>Me(e,t?.runtimeId),_r=({state:e})=>{let t={...e.global?.variables??{},...Sr(e)?.variables??{}};return $t({variables:t,runtime:rt(e),variableConfigs:e.projectData.resources?.variables??{}})},Ee=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},ce=({state:e},t)=>{let{sectionId:r}=t;return bt(e.projectData,r).section},Or=({state:e})=>{let t=Ee({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=ce({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},ua=({state:e})=>{let{sectionId:t,lineId:r}=Ee({state:e}).pointer,o=ce({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===r),l=o.slice(0,i+1).map(c=>{let u=c.actions||{},d={};return Object.keys(u).forEach(f=>{d[f]=u[f]}),d});return et(l)},Of=e=>{let t=Or({state:e})?.actions?.dialogue;if(t?.clear===!0||!Array.isArray(t?.content))return"";let r=_r({state:e});return t.content.map(n=>`${ft(n?.text,{variables:r})??""}`).join("")},Rr=({state:e})=>_s({text:Of(e),baseDelay:Me(e,"autoForwardDelay"),speed:Me(e,"autoForwardSpeed")}),Rf=({state:e})=>{let t=da({state:e}),n=Or({state:e})?.actions??{},o=et([t??{},n]);return In(t??{},o??{})},$f=({state:e},{sectionId:t})=>{let r=ce({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},l=et([o,s]),a=In(o,l);n.push({id:i.id,changes:a,presentationState:l}),o=An(l)}return n},kf=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=$f({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},da=({state:e})=>{let{sectionId:t,lineId:r}=Ee({state:e}).pointer,o=ce({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===r);if(i<=0)return null;let l=o.slice(0,i).map(a=>{let c=a.actions||{},u={};return Object.keys(c).forEach(d=>{u[d]=c[d]}),u});return An(et(l))},fo=({state:e},{slotsPerPage:t=6}={})=>{let o=((uo({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[Bt(l)]||{};i.push({...a,slotId:l})}return{saveSlots:i}},Lf=la,Tf=fo,Nf=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;return!r||!Array.isArray(r.timeline)||typeof r.currentIndex!="number"?!1:r.currentIndex>=0&&r.currentIndex<r.timeline.length-1},Pf=({state:e},t={})=>{let r=ua({state:e}),n=da({state:e}),o=Or({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:D(i)}:o,l=i?.animations&&n===null?{}:n,{sectionId:a}=Ee({state:e}).pointer,{sceneId:c}=bt(e.projectData,a),u=uo({state:e}),d=t?.activePersistentAnimations??[],f=t?.restoredPersistentAnimations??[],p=Gt({state:e}),h=ca({state:e}),g=sa({state:e}),I=_r({state:e}),{saveSlots:b}=fo({state:e}),w=Nf(e);return cs({presentationState:r,previousPresentationState:l,currentLineActions:s,resources:e.projectData.resources,currentSceneId:c,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:Ca({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||w,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:oa({state:e}),saveSlots:b,variables:I,runtime:u,activePersistentAnimations:d,restoredPersistentAnimations:f,imageGallery:g})},Df=({state:e},t)=>(e.global.confirmDialog=Fd(t),e.global.pendingEffects.push({name:"render"}),e),Vf=({state:e})=>(e.global.confirmDialog&&(It(e),e.global.pendingEffects.push({name:"render"})),e),jf=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Re(e,"pushOverlay",t),e),Mf=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Re(e,"popOverlay",void 0),e),Ff=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),Re(e,"replaceLastOverlay",t),e),Uf=({state:e})=>(e.global.overlayStack=[],It(e),At(e),e.global.pendingEffects.push({name:"render"}),Re(e,"clearOverlays",void 0),e),Bf=(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"})},$r=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,Bd(e,r),At(e);let n=xe({state:e},{pointer:t}),o=n?.source===yt,i=n?.source===Be;return Bf(e,{activeInteraction:n}),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},kr=(e,t,r)=>{!(t?.source===yt||t?.source===Be)||r||!e.global.skipMode||e.global.pendingEffects.push({name:"startSkipNextTimer"})},fa=({state:e})=>(xe({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:Rr({state:e})}}),e.global.pendingEffects.push({name:"render"})),e),zt=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Gf=({state:e})=>{let t=e.global.autoMode;return xe({state:e})&&!t||(t?zt({state:e}):fa({state:e})),e},pa=({state:e})=>(xe({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),Ge=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),zf=({state:e})=>{let t=ra({state:e});return xe({state:e})&&!t||(t?Ge({state:e}):pa({state:e})),e},Lr=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Re(e,"showDialogueUI",void 0),e),ha=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Re(e,"hideDialogueUI",void 0),e),qf=({state:e})=>(na({state:e})?Lr({state:e}):ha({state:e}),e),ze=(e,t,r)=>(Qs(e,t,r),Zd(e),e.global.pendingEffects.push({name:"render"}),e),qt=(e,t,r,n)=>{let o=Qs(e,t,r);return e.global.pendingEffects.push({name:"render"}),Re(e,n,{value:o}),e},Yf=({state:e},t)=>ze(e,"dialogueTextSpeed",t?.value),Hf=({state:e},t)=>ze(e,"autoForwardDelay",t?.value),Wf=({state:e},t)=>ze(e,"autoForwardSpeed",t?.value),Kf=({state:e},t)=>ze(e,"skipUnseenText",t?.value),Jf=({state:e},t)=>ze(e,"skipTransitionsAndAnimations",t?.value),Xf=({state:e},t)=>ze(e,"soundVolume",t?.value),Qf=({state:e},t)=>ze(e,"musicVolume",t?.value),Zf=({state:e},t)=>ze(e,"muteAll",t?.value),ep=({state:e},t)=>qt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),tp=({state:e})=>{let t=Me(e,"saveLoadPagination")+1;return qt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},rp=({state:e})=>{let t=Me(e,"saveLoadPagination")-1;return qt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},np=({state:e},t)=>qt(e,"menuPage",t?.value,"setMenuPage"),op=({state:e},t)=>qt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),ip=({state:e})=>(e.global.pendingEffects=[],e),sp=({state:e},t)=>(e.global.pendingEffects.push(t),e),ap=({state:e},t)=>{let r=t?.resourceId;return Ns(e,r),e.global.pendingEffects.push({name:"completeAchievement",payload:{resourceId:r}}),e},cp=({state:e},t)=>{let r=t?.resourceId,n=Ns(e,r);if(n.type!=="number")throw new Error(`Achievement resource "${r}" does not support numeric progress`);let o=t?.current;if(!Number.isInteger(o)||o<0)throw new Error(`Achievement progress for "${r}" must be a non-negative integer`);if(!Number.isInteger(n.target)||n.target<1)throw new Error(`Achievement resource "${r}" must have a positive integer target`);let i=Math.min(o,n.target);return e.global.pendingEffects.push({name:"setAchievementProgress",payload:{resourceId:r,current:i,target:n.target,completed:i>=n.target}}),e},ma=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!Ys(n),i=ce({state:e},{sectionId:t});if(!i)return console.warn(`Section not found: ${t}`),e;let s=i.lines?.[0];if(!s)return console.warn(`Section ${t} has no lines`),e;if(r&&!rf(e,{queueRender:!o}))return e;let l=xe({state:e});r&&e.global.skipMode&&Ge({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let u=wt(a),d=u.read;r||at(e,{sectionId:d?.sectionId,lineId:d?.lineId}),a.rollback||ct(a,{compatibilityAnchor:!0}),u.read={sectionId:t,lineId:s.id},r?a.rollback=Ut({pointer:u.read}):so(e,{sectionId:t,lineId:s.id})}let{activeInteraction:c}=$r(e,a?.pointers?.read,{screenTransition:n});return kr(e,l,c),e},lp=({state:e},t)=>ma(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),ga=e=>(e.global.accountViewedRegistry=Ed(e.global.accountViewedRegistry),e.global.accountViewedRegistry),po=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(r=>({scope:r.scope,path:r.path,op:r.op,value:D(r.value)}))}})},ya=(e,t)=>{po(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(r=>({sectionId:r.sectionId,...r.lastLineId===void 0?{}:{lineId:r.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},up=(e,t,{sectionId:r,lineId:n})=>{if(!r||!n)return!1;let o=P(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===r);if(i){if(i.lastLineId===void 0)return!1;let s=ce({state:e},{sectionId:r});if(s?.lines){let l=s.lines.findIndex(c=>c.id===i.lastLineId),a=s.lines.findIndex(c=>c.id===n);if(l===-1||a>l)return i.lastLineId===n?!1:(i.lastLineId=n,!0)}else return i.lastLineId===n?!1:(i.lastLineId=n,!0);return!1}else return o.sections.push({sectionId:r,lastLineId:n}),!0},at=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;up(e,ga(e),t)&&ya(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},dp=({state:e},t)=>(at(e,t),e.global.pendingEffects.push({name:"render"}),e),fp=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=ga(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),ya(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},Yt=(e,t,r)=>{if(!P(t))throw new Error(`${e} payload must be an object`);Object.keys(t).forEach(n=>{if(!r.has(n))throw new Error(`${e} payload contains unsupported property "${n}"`)})},Ls=(e,t,r)=>{if(typeof r!="string"||r.length===0)throw new Error(`${e} requires a non-empty ${t}`)},Tr=(e,t)=>{let r=e.global.imageGalleryNavigation;r.groupId===t.groupId&&r.variantId===t.variantId&&r.pageIndex===t.pageIndex||(e.global.imageGalleryNavigation=t,e.global.pendingEffects.push({name:"render"}))},pp=({state:e},t)=>{let r="showImageGalleryVariant";Yt(r,t,Ad),Ls(r,"groupId",t.groupId),Object.prototype.hasOwnProperty.call(t,"variantId")&&Ls(r,"variantId",t.variantId);let n=e.projectData?.resources?.imageGallery;if(n===void 0)return e;let o=n.groups.findIndex(l=>l.id===t.groupId),i=n.groups[o];if(!i)return e;let s=t.variantId===void 0?i.variants[0]:i.variants.find(l=>l.id===t.variantId);return!s||Ft(e,s)||Tr(e,{groupId:i.id,variantId:s.id,pageIndex:Math.floor(o/n.pageSize)}),e},ba=(e,t,r,n)=>{Yt(n,t,to);let o=e.projectData?.resources?.imageGallery;if(o===void 0)return e;let i=e.global.imageGalleryNavigation;if(typeof i.groupId!="string"||typeof i.variantId!="string")return e;let s=o.groups.find(c=>c.id===i.groupId),l=s?.variants.findIndex(c=>c.id===i.variantId);if(!s||l===void 0||l<0)return e;let a=Qn(e,s.variants,l,r);return a&&Tr(e,{...i,variantId:a.id}),e},hp=({state:e},t)=>ba(e,t,-1,"moveToPreviousImageGalleryVariant"),mp=({state:e},t)=>ba(e,t,1,"moveToNextImageGalleryVariant"),gp=({state:e},t)=>{if(Yt("clearImageGallerySelection",t,to),e.projectData?.resources?.imageGallery===void 0)return e;let n=e.global.imageGalleryNavigation;return Tr(e,{groupId:null,variantId:null,pageIndex:n.pageIndex}),e},Ia=(e,t)=>{let r=e.projectData?.resources?.imageGallery;if(r===void 0)return e;let n=co(r);if(t>=n)return e;let o=e.global.imageGalleryNavigation,i=lo(r,o);return t===i||Tr(e,{groupId:null,variantId:null,pageIndex:t}),e},yp=({state:e},t)=>{if(Yt("moveToImageGalleryPage",t,wd),!Number.isInteger(t.pageIndex)||t.pageIndex<0)throw new Error("moveToImageGalleryPage requires a non-negative integer pageIndex");return Ia(e,t.pageIndex)},Aa=(e,t,r,n)=>{Yt(n,t,to);let o=e.projectData?.resources?.imageGallery;if(o===void 0)return e;let s=lo(o,e.global.imageGalleryNavigation)+r;return s<0?e:Ia(e,s)},bp=({state:e},t)=>Aa(e,t,1,"moveToNextImageGalleryPage"),Ip=({state:e},t)=>Aa(e,t,-1,"moveToPreviousImageGalleryPage"),wa=({state:e},t)=>{let r=Sd(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;r&&n?(e.global.nextLineConfig={manual:r,auto:n},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(r&&(e.global.nextLineConfig.manual=r),n&&(e.global.nextLineConfig.auto=n),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let a=e.global.nextLineConfig.auto?.enabled,c=xe({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"}),Re(e,"setNextLineConfig",t),e},Ap=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:n}=t,o=t?.savedAt,i=Bt(r),s=D(e.contexts);s?.forEach(c=>{wt(c),ea(c.rollback),Rd(c.rollback)});let l={contexts:s},a={formatVersion:Ts,slotId:Vs(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:l};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},wp=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=Bt(r),o=e.global.saveSlots[n];if(o){let i=Md(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=Cr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,It(e),At(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},Ep=({state:e},t)=>{let{projectData:r}=t;Ds(r),Rt(r),Ze(r?.resources?.variables??{}),e.projectData=r,e.global.imageGalleryNavigation=eo();let n=r?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=ur(r??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...dt(e.global.variables,n)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...dt(s.variables,n)})}),It(e),At(e),e.global.pendingEffects.push({name:"render"}),e},xp=({state:e},t)=>{let{sectionId:r,lineId:n}=t;if(!n)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=r||o.pointers.read?.sectionId;if(r&&!ce({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=ce({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===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let a=xe({state:e}),c=wt(o);c.read={sectionId:i,lineId:n};let{activeInteraction:u}=$r(e,c.read);return kr(e,a,u),e},vp=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return Lr({state:e}),e;let r=xe({state:e});if(r?.source===yt&&t?.bypassChoice!==!0||r?.source===Be&&t?._interactionSource!==Be)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=Ee({state:e})?.pointer,d=u?.sectionId,f=u?.lineId;d&&f&&at(e,{sectionId:d,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&!r&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Rr({state:e})}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&!r&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=Ee({state:e})?.pointer,o=n?.sectionId,i=ce({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],l=i?.lines||[],c=l.findIndex(u=>u.id===n?.lineId)+1;if(c<l.length){let u=l[c],d=!Me(e,"skipUnseenText");if(e.global.skipMode&&d&&!ao({state:e},{sectionId:o,lineId:u.id}))return Ge({state:e}),e;if(s&&!s.rollback&&ct(s,{compatibilityAnchor:!0}),s){let p=wt(s),h=p.read?.lineId;h&&o&&at(e,{sectionId:o,lineId:h}),p.read={sectionId:o,lineId:u.id}}so(e,{sectionId:o,lineId:u.id}),ro(e);let{activeInteraction:f}=$r(e,{sectionId:o,lineId:u.id});kr(e,r,f)}else e.global.autoMode&&zt({state:e}),e.global.skipMode&&Ge({state:e});return e},Cp=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=xe({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Rr({state:e})}});let r=Ee({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&at(e,{sectionId:n,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},Sp=({state:e},t)=>ma(e,{sectionId:t?.sectionId,screen:t?.screen}),_p=({state:e},t)=>{let r=t?._conditionalContinuation===!0;if(e.global.dialogueUIHidden&&!r)return Lr({state:e}),e;let n=xe({state:e});if(n?.source===yt&&t?.bypassChoice!==!0||n?.source===Be&&t?._interactionSource!==Be||n&&n.source!==yt&&n.source!==Be)return e;let o=Ee({state:e})?.pointer,i=o?.sectionId,s=ce({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=!Me(e,"skipUnseenText");if(e.global.skipMode&&f&&!ao({state:e},{sectionId:i,lineId:d.id})&&(Ge({state:e}),!r))return e;if(l&&!l.rollback&&ct(l,{compatibilityAnchor:!0}),l){let h=wt(l),g=h.read?.lineId;g&&i&&at(e,{sectionId:i,lineId:g}),h.read={sectionId:i,lineId:d.id}}so(e,{sectionId:i,lineId:d.id}),ro(e);let{activeInteraction:p}=$r(e,{sectionId:i,lineId:d.id});kr(e,n,p)}else e.global.autoMode&&zt({state:e}),e.global.skipMode&&Ge({state:e}),e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},ho=(e,t={})=>{let r=Gt({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},Op=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let r=e.projectData.resources?.variables?.[t.variableId],n=r?.scope,o=r?.type;if(Ce(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return kt(n,t.variableId),dr(o,"set",t.variableId),{variableConfig:r,scope:n}},Rp=(e,t)=>({id:e.id,key:e.key,valid:!0,values:D(t),fields:D(e.fields),fieldList:D(e.fieldList)}),$p=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ee({state:e})?.pointer,r=t?.sectionId,n=t?.lineId;r&&n&&at(e,{sectionId:r,lineId:n})},kp=({state:e},t={})=>{let r=ho(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=Ws(e,r.key),i=xr(t.value),s=r.fields[n],l=no(s,i);return o.values[n]=i,o.touched[n]=!0,l?o.errors[n]=l:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},Lp=({state:e},t={})=>{let r=ho(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=Ws(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([d,f])=>{let p=Object.prototype.hasOwnProperty.call(n.values,d)?n.values[d]:f.value,h=no(f,p);n.touched[d]=!0,h&&(i[d]=h),o[d]=Hs(f,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:D(i),form:{id:r.id,key:r.key,values:D(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let l=!1,a=[],c=[];Object.entries(r.fields).forEach(([d,f])=>{let{scope:p}=Op(e,f),h=p==="context"?s.variables:e.global.variables,g=o[d];h[f.variableId]=fr(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:D(h[f.variableId])})}),l&&Re(e,"updateVariable",{id:"submitForm",operations:c}),po(e,a);let u=Rp(r,o);return $p(e),delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},Tp=({state:e},t={})=>{let r=ho(e,t);return r?(delete e.global.formDrafts?.[r.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:r.id,key:r.key,values:D(r.values),fields:D(r.fields),fieldList:D(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},Np=({state:e},t)=>{let{id:r,operations:n=[]}=t;if(!r)throw new Error("updateVariable requires an id field");if(typeof r!="string"||!/^[a-zA-Z0-9]+$/.test(r))throw new Error(`updateVariable id must be alphanumeric, got: "${r}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],l=[];return n.forEach(({variableId:a,op:c,value:u,roundTo:d})=>{let f=e.projectData.resources?.variables?.[a],p=f?.scope,h=f?.type;if(Ce(f))throw new Error(`Cannot update computed variable: ${a}`);if(f?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);kt(p,a),dr(h,c,a),yn(h,c,u,a,{roundTo:d});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let I={variableId:a,op:c,value:u};d!==void 0&&(I.roundTo=d),l.push(I)}g[a]=fr(g[a],c,u,{roundTo:d}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:D(g[a])})}),i&&Re(e,"updateVariable",{id:r,operations:l}),po(e,s),e.global.pendingEffects.push({name:"render"}),e},Pp=e=>(t,r)=>e({state:t},r),Dp=e=>({variables:$t({variables:{...e.global?.variables??{},...Sr(e)?.variables??{}},runtime:rt(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:rt(e)}),Vp=e=>{if(!P(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")},jp=(e,t,r)=>{if(!P(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!P(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==r-1)throw new Error("conditional else branch must be the last branch")},Mp=(e,t)=>{Vp(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(jp(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!Ot(n.when,Dp(e)))){Object.entries(n.actions).forEach(([i,s])=>{Ea(e,i,s)});return}}},Fp={conditional:{replayLine:Mp},updateVariable:{recordSources:[oo],replayLine:ks,replayRecorded:ks,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Pp(wa)}},Nr=e=>Fp[e]??null,Up=e=>Nr(e)?.persistInSaveSlot===!0,Bp=(e,t)=>{let r=Nr(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},Gp=(e,t,r)=>{Nr(t)?.replayRecorded?.(e,r)},Ea=(e,t,r)=>{Nr(t)?.replayLine?.(e,r)},zp=e=>e?.returnable!==!1,xa=(e,t)=>{if(t>=0)return e.currentIndex+t;let r=Math.abs(t);for(let n=e.currentIndex-1;n>=0;n-=1)if(zp(e.timeline[n])&&(r-=1,r===0))return n;return-1},va=({state:e},t)=>{let{offset:r}=t;if(r===void 0||typeof r!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let n=e.contexts[e.contexts.length-1];if(!n)return null;let o=n.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=xa(o,r);if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},Ca=({state:e})=>va({state:e},{offset:-1})!==null,qp=({state:e},t)=>{let{offset:r=-1}=t;if(r>=0)throw new Error("rollbackByOffset requires a negative offset");let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let o=ct(n,{compatibilityAnchor:!n.rollback}),i=xa(o,r);return i<0||i>=o.timeline.length?e:ta(e,i)},Yp=({state:e},t)=>{let{sectionId:r,lineId:n}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=ct(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===r&&a.lineId===n);if(l===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return l===i.currentIndex?e:ta(e,l)},Sa=e=>{let t=pf(e);return ai(t,{selectPendingEffects:mf,selectSkipMode:ra,selectAutoMode:gf,selectIsChoiceVisible:ca,selectIsFormVisible:bf,selectActiveInteraction:xe,selectActiveForm:Gt,selectDialogueUIHidden:na,selectDialogueHistory:oa,selectConfirmDialog:yf,selectIsLineAccountViewed:ao,selectIsResourceAccountViewed:Af,selectImageGalleryConfig:wf,selectImageGallery:sa,selectNextLineConfig:Ef,selectSystemState:xf,selectAchievements:vf,selectAchievement:Cf,selectSaveSlotMap:la,selectSaveSlots:Lf,selectSaveSlot:Sf,selectRuntime:uo,selectRuntimeValue:_f,selectAllVariables:_r,selectCurrentPointer:Ee,selectSection:ce,selectCurrentLine:Or,selectPresentationState:ua,selectAutoForwardTimerDelay:Rr,selectPresentationChanges:Rf,selectSectionLineChanges:kf,selectSaveSlotPage:fo,selectCurrentPageSlots:Tf,selectRenderState:Pf,selectOverlayStack:hf,selectLineIdByOffset:va,selectCanRollback:Ca,selectRollbackCursor:of,startAutoMode:fa,stopAutoMode:zt,toggleAutoMode:Gf,startSkipMode:pa,stopSkipMode:Ge,toggleSkipMode:zf,showDialogueUI:Lr,hideDialogueUI:ha,toggleDialogueUI:qf,setDialogueTextSpeed:Yf,setAutoForwardDelay:Hf,setAutoForwardSpeed:Wf,setSkipUnseenText:Kf,setSkipTransitionsAndAnimations:Jf,setSoundVolume:Xf,setMusicVolume:Qf,setMuteAll:Zf,setSaveLoadPagination:ep,incrementSaveLoadPagination:tp,decrementSaveLoadPagination:rp,setMenuPage:np,setMenuEntryPoint:op,showConfirmDialog:Df,hideConfirmDialog:Vf,resetStoryAtSection:lp,clearPendingEffects:ip,appendPendingEffect:sp,completeAchievement:ap,setAchievementProgress:cp,beginRollbackActionBatch:lf,endRollbackActionBatch:uf,markRollbackCheckpointTransient:sf,markSavedRollbackCheckpointTransient:af,addViewedLine:dp,addViewedResource:fp,showImageGalleryVariant:pp,moveToPreviousImageGalleryVariant:hp,moveToNextImageGalleryVariant:mp,clearImageGallerySelection:gp,moveToImageGalleryPage:yp,moveToNextImageGalleryPage:bp,moveToPreviousImageGalleryPage:Ip,setNextLineConfig:wa,saveSlot:Ap,loadSlot:wp,updateProjectData:Ep,sectionTransition:Sp,jumpToLine:xp,nextLine:vp,markLineCompleted:Cp,rollbackToLine:Yp,rollbackByOffset:qp,pushOverlay:jf,popOverlay:Mf,replaceLastOverlay:Ff,clearOverlays:Uf,updateFormField:kp,submitForm:Lp,cancelForm:Tp,updateVariable:Np,nextLineFromSystem:_p},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var Hp="route-engine",Wp="projectPersistence";var Oa=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),ee=e=>Object.prototype.toString.call(e)==="[object Object]",_a="variables.",Kp=(e={})=>{let t=ee(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!ee(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lineId=="string"?{lineId:r.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!ee(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Jp=(e={})=>{let t=ee(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!ee(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lastLineId=="string"?{lastLineId:r.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!ee(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Xp=(e,t)=>{let r=Jp(e),n=Kp(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let l=o.find(a=>a.sectionId===s.sectionId);if(!l){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(l.lastLineId!==void 0){if(s.lineId===void 0){delete l.lastLineId;return}l.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},Ra=(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:{}}},Qp=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!ee(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(_a)?t.path.slice(_a.length):null;if(n!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(n.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${r}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:n}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${r}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${r}].`)})},Zp=(e,t)=>{let r={};return Qp(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=Xp(r.accountViewedRegistry??e.accountViewedRegistry,n.value);return}let o=n.scope==="device"?"globalDeviceVariables":"globalAccountVariables";r[o]={...e[o],...r[o],[n.variableId]:n.value}}),r},mo=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},eh=e=>{let t=mo(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},th=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},rh=({indexedDB:e,databaseName:t,objectStoreName:r})=>new Promise((n,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(r)||s.createObjectStore(r,{keyPath:"namespace"})},i.onsuccess=()=>{n(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),nh=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let a=n.transaction(t,"readonly").objectStore(t).get(r);a.onsuccess=()=>{o(a.result??null)},a.onerror=()=>{i(a.error??new Error(`Failed to read persisted namespace "${r}" from IndexedDB.`))}})},Ht=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),a=l.objectStore(t),c=a.get(r),u=!1,d=p=>{u||(u=!0,s(p))},f=()=>{u||(u=!0,i())};c.onerror=()=>{d(c.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},c.onsuccess=()=>{let p=Ra(c.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...Oa(),...p,...h},I=a.put(g);I.onerror=()=>{d(I.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},l.oncomplete=()=>{f()},l.onerror=()=>{d(l.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},l.onabort=()=>{d(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},oh=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let s=n.transaction(t,"readwrite"),a=s.objectStore(t).delete(r),c=!1,u=f=>{c||(c=!0,i(f))},d=()=>{c||(c=!0,o())};a.onerror=()=>{u(a.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{d()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},go=(e={})=>{let{indexedDB:t,databaseName:r=Hp,objectStoreName:n=Wp,namespace:o}=e,i=th(t),s=eh(o),l=rh({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let a=await nh({databasePromise:l,objectStoreName:n,namespace:s});return{...Oa(),...Ra(a)}},clear:async()=>oh({databasePromise:l,objectStoreName:n,namespace:s}),saveSlots:async a=>Ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{saveSlots:ee(a)?a:{}}}),saveGlobalDeviceVariables:async a=>Ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:ee(a)?a:{}}}),saveGlobalAccountVariables:async a=>Ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalAccountVariables:ee(a)?a:{}}}),saveGlobalRuntime:async a=>Ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalRuntime:ee(a)?a:{}}}),applyScopedDataUpdates:async a=>Ht({databasePromise:l,objectStoreName:n,namespace:s,patch:c=>Zp(c,a)})}},ih=go;var sh=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),ah=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),$a="conditional",Io=Symbol("conditionalAutoContinue"),ch=new Set(["sectionTransition","resetStoryAtSection"]),lh=new Set(["nextLine","nextLineFromSystem","resetStoryAtSection","sectionTransition"]),uh=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),yo="form",dh=new Set(["submitForm","cancelForm"]),fh="showImageGalleryVariant",Et=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Pr=e=>e?.type===Io,bo=(e,t)=>e?.sectionId===t?.sectionId&&e?.lineId===t?.lineId;function Ao(e){let t,r=0,n=null,o=0,i=!1,s=0,l=[],a=null,c=new Map,u=new Map,d=new Map,{handlePendingEffects:f}=e,p=(m=new Map,A=Date.now())=>new Map(Array.from(m.entries()).filter(([,E])=>A<E.expiresAt).map(([E,_])=>[E,{animation:structuredClone(_.animation),startedAt:_.startedAt,expiresAt:_.expiresAt}])),h=(m=new Map)=>Array.from(m.values()).map(A=>structuredClone(A.animation)),g=(m=Date.now())=>{c=new Map(Array.from(c.entries()).filter(([,A])=>m<A.expiresAt))},I=()=>{if(!(o>0||i)){i=!0;try{for(;t.selectPendingEffects().length>0;){let m=[...t.selectPendingEffects()];t.clearPendingEffects();try{f(m)}catch(A){throw t.clearPendingEffects(),m.forEach(E=>{t.appendPendingEffect(E)}),A}}}finally{i=!1}}},b=m=>{o+=1;let A=!1;try{let E=m();return A=!0,E}finally{o-=1,A&&I()}},w=({initialState:m,namespace:A})=>{t=Sa(m),r=0,n=mo(A),o=0,i=!1,s=0,l=[],a=null,c=new Map,u=new Map,d=new Map,t.appendPendingEffect({name:"handleLineActions"}),I()},S=()=>n,O=()=>t.selectPresentationState(),$=()=>t.selectPresentationChanges(),G=m=>t.selectSectionLineChanges(m),T=(m={})=>{r+=1;let A=Date.now();g(A);let E=u.size>0,_=p(c,A),k=E?p(u,A):new Map,K={...t.selectRenderState({activePersistentAnimations:h(_),restoredPersistentAnimations:h(k)}),id:`render-${r}`};return d.set(K.id,{builtAt:A,persistentAnimationSessions:new Map([...k.entries(),..._.entries()]),usedRestoredPersistentAnimationSessions:E}),K},x=(m={})=>T(m),q=(m={})=>T(m),Y=m=>{let A=typeof m?.id=="string"&&m.id.length>0?m.id:null,E=A?d.get(A):null;A&&d.delete(A);let _=new Map;Yi(m?.animations).forEach(k=>{let z=yr(k);if(!z)return;let K=E?.persistentAnimationSessions?.get(z)??c.get(z),ge=Math.max(0,Wi(k)),$e=K?.startedAt??E?.builtAt??Date.now();_.set(z,{animation:structuredClone(k),startedAt:$e,expiresAt:$e+ge})}),c=_,E?.usedRestoredPersistentAnimationSessions&&(u=new Map)},W=()=>t.selectSystemState(),B=()=>t.selectAchievements(),te=m=>t.selectAchievement(m),re=()=>t.selectSaveSlotMap(),de=m=>t.selectSaveSlot(m),Oe=m=>t.selectSaveSlotPage(m),ne=()=>t.selectImageGallery(),oe=()=>t.selectSkipMode(),le=()=>t.selectAutoMode(),ie=()=>t.selectRuntime(),Z=()=>t.selectIsChoiceVisible(),X=()=>t.selectIsFormVisible(),v=()=>t.selectActiveInteraction(),R=()=>t.selectPendingEffects().some(m=>m?.name==="handleLineActions"||m?.name==="render"),M=(m,A,E={})=>!Et(A)||m!=="nextLine"?A:E.bypassChoice===!0?{...A,bypassChoice:!0}:E.interactionSource===yo?{...A,_interactionSource:yo}:A,fe=(m={})=>({type:Io,payload:M("nextLine",{_conditionalContinuation:!0},m)}),me=(m,A)=>Pr(m)?{type:Io,payload:{...m.payload,...A.payload}}:A,F=m=>{m.savedCheckpointOccurrences.forEach(A=>{t.markSavedRollbackCheckpointTransient(A)}),m.savedCheckpointOccurrences=[]},qe=(m,A)=>{let E=a;return a=null,!E||!bo(E.pointer,m)||E.checkpointIndex!==A?.checkpointIndex||E.checkpointIdentity!==A?.checkpoint?[]:E.savedCheckpointOccurrences},Ye=m=>{m.markCurrentCheckpointTransient&&(t.markRollbackCheckpointTransient({checkpointIndex:m.rollbackCursor?.checkpointIndex,checkpointIdentity:m.rollbackCursor?.checkpoint,sectionId:m.pointer?.sectionId,lineId:m.pointer?.lineId}),F(m))},Ta=(m,A,E)=>lh.has(m)?m==="resetStoryAtSection"?E?.checkpoint!==A?.checkpoint:E?.checkpoint!==A?.checkpoint&&E?.checkpointIndex>A?.checkpointIndex:!1,Na=m=>{let A=l.at(-1);if(!A?.markCurrentCheckpointTransient)return;let E=t.selectSaveSlot({slotId:m?.slotId});E&&A.savedCheckpointOccurrences.push({slotId:m.slotId,saveSlotIdentity:E,checkpointIndex:A.rollbackCursor?.checkpointIndex,sectionId:A.pointer?.sectionId,lineId:A.pointer?.lineId})},Pa=(m,A,E)=>{let _=l.at(-1);if(!_)return;let k=t.selectCurrentPointer()?.pointer,z=Ta(m,A,E);if(bo(_.pointer,k)){let K=E?.checkpoint!==A?.checkpoint||E?.checkpointIndex!==A?.checkpointIndex;(z||K&&uh.has(m))&&(Ye(_),_.pointer=k,_.rollbackCursor=E,_.markCurrentCheckpointTransient=z,_.savedCheckpointOccurrences=[]);return}Ye(_),_.pointer=k,_.rollbackCursor=t.selectRollbackCursor?.()??null,_.markCurrentCheckpointTransient=z,_.savedCheckpointOccurrences=[]},Wt=(m,A)=>{if(!t[m])return;m==="updateProjectData"&&Da(A),ch.has(m)&&(s+=1),sh.has(m)&&(ah.has(m)?u=p(c):u=new Map,c=new Map);let E=t.selectRollbackCursor?.()??null,_=t[m](A),k=t.selectRollbackCursor?.()??null;return m==="saveSlot"&&Na(A),Pa(m,E,k),I(),_},Da=m=>{if(!Object.prototype.hasOwnProperty.call(m??{},"projectData"))throw new Error("updateProjectData requires projectData");Ze(m?.projectData?.resources?.variables??{}),Rt(m.projectData)},Va=(m,A,E)=>{let _=t.selectCurrentPointer()?.pointer;A!==_||E!==s||(t.appendPendingEffect({name:"clearAutoNextTimer"}),t.appendPendingEffect({name:"clearNextLineConfigTimer"}),Wt("nextLineFromSystem",m.payload))},ja=()=>({renderSequence:r,conditionalRoutingSequence:s,rollbackNavigationContexts:l.slice(),pendingRollbackLineEntrySaveHandoff:a,persistentAnimationSessions:new Map(c),restoredPersistentAnimationSessions:new Map(u),renderPersistentAnimationMetadata:new Map(d)}),Ma=m=>{r=m.renderSequence,s=m.conditionalRoutingSequence,l=m.rollbackNavigationContexts.slice(),a=m.pendingRollbackLineEntrySaveHandoff,c=new Map(m.persistentAnimationSessions),u=new Map(m.restoredPersistentAnimationSessions),d=new Map(m.renderPersistentAnimationMetadata)},Eo=(m,A={})=>b(()=>{let E=ja();try{return t[gn](()=>{let _,k=t.selectCurrentPointer()?.pointer??null,z=t.selectRollbackCursor?.()??null,K=s,ge={pointer:k,rollbackCursor:z,markCurrentCheckpointTransient:A.rollbackSource==="line",savedCheckpointOccurrences:A.savedCheckpointOccurrences?.slice()??[]};l.push(ge);try{t.beginRollbackActionBatch({source:A.rollbackSource});try{_=m()}finally{t.endRollbackActionBatch({})}Pr(_)&&Va(_,k,K)}finally{l.pop(),(!bo(k,ge.pointer)||z?.checkpoint!==ge.rollbackCursor?.checkpoint)&&ge.markCurrentCheckpointTransient&&ge.savedCheckpointOccurrences.length>0&&(a={pointer:ge.pointer,checkpointIndex:ge.rollbackCursor?.checkpointIndex,checkpointIdentity:ge.rollbackCursor?.checkpoint,savedCheckpointOccurrences:ge.savedCheckpointOccurrences})}})}catch(_){throw Ma(E),_}}),xo=(m,A,E,_={})=>{if(m===$a)return Eo(()=>{let k=Vr(E),z=wn({[m]:A},k);return vo(z[m],E,_)},_);Wt(m,A)},Fa=(m,A)=>{xo(m,A)},Vr=m=>{if(!m)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(m,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:A,...E}=m,_=t.selectAllVariables?t.selectAllVariables():void 0;return{...E,_event:A,variables:_,runtime:t.selectRuntime?t.selectRuntime():{}}},Ua=m=>{if(!Et(m))return{templatePayload:m,literalTargetIds:null};let A=t.selectImageGalleryConfig();if(!Array.isArray(A?.groups))return{templatePayload:m,literalTargetIds:null};let E=typeof m.groupId=="string"?A.groups.find(k=>k.id===m.groupId):void 0;if(!E)return{templatePayload:m,literalTargetIds:null};let _=typeof m.variantId=="string"&&E.variants.some(k=>k.id===m.variantId);return{templatePayload:{...m,groupId:null,..._?{variantId:null}:{}},literalTargetIds:{groupId:m.groupId,..._?{variantId:m.variantId}:{}}}},Ba=m=>{if(!Et(m))throw new Error("conditional action payload must be an object");if(!Array.isArray(m.branches))throw new Error("conditional action requires branches array");if(m.branches.length===0)throw new Error("conditional action requires at least one branch")},Ga=(m,A,E)=>{if(!Et(m))throw new Error(`conditional branch at index ${A} must be an object`);if(!Et(m.actions))throw new Error(`conditional branch at index ${A} requires actions object`);if(!Object.prototype.hasOwnProperty.call(m,"when")&&A!==E-1)throw new Error("conditional else branch must be the last branch")},vo=(m,A,E)=>{Ba(m);let _=fe(E);for(let k=0;k<m.branches.length;k+=1){let z=m.branches[k];Ga(z,k,m.branches.length);let K=Vr(A);if(Object.prototype.hasOwnProperty.call(z,"when")&&!Ot(z.when,K))continue;let $e=jr(z.actions,A,E);return Pr($e)?me(_,$e):_}return _},za=(m,A)=>({...m??{},_form:A}),qa=(m,A,E,_)=>{let k=Wt(m,A),z=k?.submitted===!0&&k.valid===!0,K=k?.cancelled===!0;if(!(!z&&!K)&&Et(A.actions))return jr(A.actions,za(E,k.form),{..._,interactionSource:yo})},Ya=(m,A,E,_)=>{let k=Vr(E),{templatePayload:z,literalTargetIds:K}=m===fh?Ua(A):{templatePayload:A,literalTargetIds:null},$e=wn({[m]:z},k)[m],So=K?{...$e,...K}:$e;if(m===$a)return vo(So,E,_);let _o=M(m,So,_);if(dh.has(m))return qa(m,_o,E,_);Wt(m,_o)},jr=(m,A,E)=>{let _;return Object.entries(m).forEach(([k,z])=>{let K=Ya(k,z,A,E);Pr(K)&&(_=me(_,K))}),_},Co=(m,A,E={})=>Eo(()=>jr(m,A,E),E),Ha=m=>{let A=t.selectCurrentPointer()?.pointer;if(m!==A||t.selectActiveInteraction())return;let E=t.selectNextLineConfig();E?.auto?.enabled&&E.auto.trigger==="fromStart"&&t.appendPendingEffect({name:"nextLineConfigTimer",payload:{delay:E.auto.delay}})};return{init:w,handleAction:xo,handleInternalAction:Fa,handleActions:Co,selectRenderState:x,prepareRenderState:q,commitRenderState:Y,selectPresentationState:O,selectPresentationChanges:$,selectSectionLineChanges:G,selectSystemState:W,selectAchievements:B,selectAchievement:te,selectSaveSlotMap:re,selectSaveSlot:de,selectSaveSlotPage:Oe,selectSaveSlots:re,selectImageGallery:ne,selectRuntime:ie,selectIsChoiceVisible:Z,selectIsFormVisible:X,selectActiveInteraction:v,selectHasPendingRenderWork:R,handleLineActions:()=>b(()=>{let m=t.selectCurrentPointer()?.pointer,A=t.selectRollbackCursor?.()??null,E=a,_=qe(m,A),k=t.selectCurrentLine(),z=!1;if(k?.actions){try{Co(k.actions,void 0,{rollbackSource:"line",savedCheckpointOccurrences:_})}catch(K){throw a=E,K}z=!0}return Ha(m),z}),getNamespace:S}}var wo=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},ph=80,La=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{if(e.selectHasPendingRenderWork?.())return;let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},hh=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&La({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},mh=({engine:e,ticker:t,autoTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let l=n.delay??1e3;r.getElapsed()>=l&&(t.remove(i),r.setCallback(null),r.setElapsed(0),Dr(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},gh=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},yh=({engine:e,ticker:t,skipTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let l=n?.delay??ph;r.getElapsed()>=l&&(r.setElapsed(0),Dr(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},bh=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Ih=({engine:e,ticker:t,nextLineConfigTimerState:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let l=n.delay??1e3;r.getElapsed()>=l&&(r.setElapsed(0),Dr(e,"nextLineFromSystem",{}),t.remove(i),r.getCallback()===i&&r.setCallback(null))};r.setCallback(i),t.add(i)},Ah=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},wh=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},Eh=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},xh=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},vh=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},Ch=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},ka={render:La,saveSlots:wh,saveGlobalDeviceVariables:Eh,saveGlobalAccountVariables:xh,saveGlobalRuntime:vh,applyScopedDataUpdates:Ch,handleLineActions:hh,startAutoNextTimer:mh,clearAutoNextTimer:gh,startSkipNextTimer:yh,clearSkipNextTimer:bh,nextLineConfigTimer:Ih,clearNextLineConfigTimer:Ah},Sh=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Dr=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},_h=(e=[])=>{let t=new Set,r=[];for(let n=e.length-1;n>=0;n-=1){let o=e[n];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!Sh.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},Oh=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let a=wo(),c=wo(),u=wo(),d=s??null,f=Promise.resolve(),p=null,h=null,g=!1,I=0,b=v=>{if(o){o(v);return}console.error("RouteEngine persistence write failed.",v)},w=()=>{if(d)return d;let v=e();return d=go({indexedDB:i,namespace:l??v?.getNamespace?.()}),d},S=v=>{f=f.catch(()=>{}).then(()=>{let R=w();return v(R)}).catch(R=>{b(R)})},O=v=>{let R=typeof v?.id=="string"&&v.id.length>0?v.id:null;I+=1,p=R,g=!1},$=()=>I,G=(v={})=>{if(v?.aborted===!0)return!1;let R=typeof v?.id=="string"&&v.id.length>0?v.id:null;return R?R!==p||R===h?!1:(h=R,!0):p!==null||g?!1:(g=!0,!0)},T=(v,R={})=>{if(v!=="renderComplete"||!G(R))return!1;let M=e();return Dr(M,"markLineCompleted",{}),!0},x=new Set(["updateFormField","submitForm","cancelForm"]),q=new Set(["updateVariable"]),Y=v=>typeof v?.selectActiveInteraction=="function"?v.selectActiveInteraction():typeof v?.selectIsChoiceVisible=="function"&&v.selectIsChoiceVisible()?{source:"choice"}:null,W=v=>v?._formKey??v?.formKey,B=(v,R)=>W(v)===R?.formKey,te=(v,R)=>!v||typeof v!="object"||Array.isArray(v)?!1:v._interactionSource===R?.source,re=(v,R)=>te(v,R)?R.source==="form"?B(v,R):!0:!1,de=(v,R)=>!v||typeof v!="object"||Array.isArray(v)||R?.source!=="form"?!1:B(v,R),Oe=(v={})=>Object.keys(v).some(R=>x.has(R)),ne=(v={},R)=>Object.entries(v).some(([M,fe])=>x.has(M)&&de(fe,R)),oe=(v={})=>Object.keys(v).length>0&&Object.keys(v).every(R=>q.has(R)),le=(v={},R)=>{let M=v?.actions;return R?.source==="form"?!M||typeof M!="object"||Array.isArray(M)?!1:ne(M,R)?!0:Oe(M)?!1:oe(M):re(v,R)?!0:!M||typeof M!="object"||Array.isArray(M)?!1:Object.values(M).some(fe=>re(fe,R))},ie=(v,R={})=>{if(!R?.actions)return!1;let M=Y(v);return!M||M.source==="choice"?!1:!le(R,M)},Z=({preprocessPayload:v,onEvent:R}={})=>async(M,fe={})=>{let me=e();if(ie(me,fe))return R?.(M,fe);let F=await v?.(M,fe)??fe;if(ie(me,F))return R?.(M,F);if(T(M,F),F?.actions){let qe=F?._event?{_event:F._event}:F?.event?{_event:F.event}:void 0,Ye;F?.bypassChoice===!0?Ye={bypassChoice:!0}:F?._interactionSource&&(Ye={interactionSource:F._interactionSource}),Ye?me.handleActions(F.actions,qe,Ye):me.handleActions(F.actions,qe)}return R?.(M,F)},X=v=>{let R=e(),M=_h(v),fe=M.some(F=>F.name==="handleLineActions");M.forEach(F=>{if(!ka[F.name]&&!n)throw new Error(`Unhandled pending effect "${F.name}".`)});let me={engine:R,routeGraphics:t,ticker:r,autoTimer:a,skipTimer:c,nextLineConfigTimerState:u,trackRenderDispatch:O,getRenderDispatchCount:$,enqueuePersistenceWrite:S};for(let F of M){if(fe&&F.name==="render")continue;let qe=ka[F.name];if(qe){qe(me,F.payload);continue}n(F,me)}};return X.handleRouteGraphicsEvent=T,X.createRouteGraphicsEventHandler=Z,X},Rh=Oh;var $h=(e,t={})=>{let{resources:r={}}=t;return Yn(e,r)};var cg=Ao;export{Cn as DEFAULT_VISUAL_LAYER,pt as RENDER_LAYER,ke as VISUAL_LAYER,Rh as createEffectsHandler,ih as createIndexedDbPersistence,cg as default,bn as formatDate,fl as resolveComputedVariables,$h as resolveLayoutReferences};
1
+ var Vc=Object.defineProperty;var jc=(e,n)=>{for(var t in n)Vc(e,t,{get:n[t],enumerable:!0})};var oi=Symbol.for("immer-nothing"),Zo=Symbol.for("immer-draftable"),ye=Symbol.for("immer-state");function Ee(e,...n){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var bn=Object.getPrototypeOf;function ie(e){return!!e&&!!e[ye]}function nn(e){return e?ii(e)||Array.isArray(e)||!!e[Zo]||!!e.constructor?.[Zo]||ht(e)||yt(e):!1}var Fc=Object.prototype.constructor.toString();function ii(e){if(!e||typeof e!="object")return!1;let n=bn(e);if(n===null)return!0;let t=Object.hasOwnProperty.call(n,"constructor")&&n.constructor;return t===Object?!0:typeof t=="function"&&Function.toString.call(t)===Fc}function ur(e){return ie(e)||Ee(15,e),e[ye].base_}function ft(e,n){gt(e)===0?Reflect.ownKeys(e).forEach(t=>{n(t,e[t],e)}):e.forEach((t,r)=>n(r,t,e))}function gt(e){let n=e[ye];return n?n.type_:Array.isArray(e)?1:ht(e)?2:yt(e)?3:0}function or(e,n){return gt(e)===2?e.has(n):Object.prototype.hasOwnProperty.call(e,n)}function si(e,n,t){let r=gt(e);r===2?e.set(n,t):r===3?e.add(t):e[n]=t}function Uc(e,n){return e===n?e!==0||1/e===1/n:e!==e&&n!==n}function ht(e){return e instanceof Map}function yt(e){return e instanceof Set}function en(e){return e.copy_||e.base_}function ir(e,n){if(ht(e))return new Map(e);if(yt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let t=ii(e);if(n===!0||n==="class_only"&&!t){let r=Object.getOwnPropertyDescriptors(e);delete r[ye];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(bn(e),r)}else{let r=bn(e);if(r!==null&&t)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function dr(e,n=!1){return bt(e)||ie(e)||!nn(e)||(gt(e)>1&&(e.set=e.add=e.clear=e.delete=Bc),Object.freeze(e),n&&Object.entries(e).forEach(([t,r])=>dr(r,!0))),e}function Bc(){Ee(2)}function bt(e){return Object.isFrozen(e)}var Gc={};function tn(e){let n=Gc[e];return n||Ee(0,e),n}var Ln;function ai(){return Ln}function zc(e,n){return{drafts_:[],parent_:e,immer_:n,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function ei(e,n){n&&(tn("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=n)}function sr(e){ar(e),e.drafts_.forEach(qc),e.drafts_=null}function ar(e){e===Ln&&(Ln=e.parent_)}function ni(e){return Ln=zc(Ln,e)}function qc(e){let n=e[ye];n.type_===0||n.type_===1?n.revoke_():n.revoked_=!0}function ti(e,n){n.unfinalizedDrafts_=n.drafts_.length;let t=n.drafts_[0];return e!==void 0&&e!==t?(t[ye].modified_&&(sr(n),Ee(4)),nn(e)&&(e=pt(n,e),n.parent_||mt(n,e)),n.patches_&&tn("Patches").generateReplacementPatches_(t[ye].base_,e,n.patches_,n.inversePatches_)):e=pt(n,t,[]),sr(n),n.patches_&&n.patchListener_(n.patches_,n.inversePatches_),e!==oi?e:void 0}function pt(e,n,t){if(bt(n))return n;let r=n[ye];if(!r)return ft(n,(o,i)=>ri(e,r,n,o,i,t)),n;if(r.scope_!==e)return n;if(!r.modified_)return mt(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),ft(i,(l,a)=>ri(e,r,o,l,a,t,s)),mt(e,o,!1),t&&e.patches_&&tn("Patches").generatePatches_(r,t,e.patches_,e.inversePatches_)}return r.copy_}function ri(e,n,t,r,o,i,s){if(ie(o)){let l=i&&n&&n.type_!==3&&!or(n.assigned_,r)?i.concat(r):void 0,a=pt(e,o,l);if(si(t,r,a),ie(a))e.canAutoFreeze_=!1;else return}else s&&t.add(o);if(nn(o)&&!bt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;pt(e,o),(!n||!n.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(t,r)&&mt(e,o)}}function mt(e,n,t=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&dr(n,t)}function Yc(e,n){let t=Array.isArray(e),r={type_:t?1:0,scope_:n?n.scope_:ai(),modified_:!1,finalized_:!1,assigned_:{},parent_:n,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=fr;t&&(o=[r],i=Pn);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var fr={get(e,n){if(n===ye)return e;let t=en(e);if(!or(t,n))return Hc(e,t,n);let r=t[n];return e.finalized_||!nn(r)?r:r===tr(e.base_,n)?(rr(e),e.copy_[n]=lr(r,e)):r},has(e,n){return n in en(e)},ownKeys(e){return Reflect.ownKeys(en(e))},set(e,n,t){let r=ci(en(e),n);if(r?.set)return r.set.call(e.draft_,t),!0;if(!e.modified_){let o=tr(en(e),n),i=o?.[ye];if(i&&i.base_===t)return e.copy_[n]=t,e.assigned_[n]=!1,!0;if(Uc(t,o)&&(t!==void 0||or(e.base_,n)))return!0;rr(e),cr(e)}return e.copy_[n]===t&&(t!==void 0||n in e.copy_)||Number.isNaN(t)&&Number.isNaN(e.copy_[n])||(e.copy_[n]=t,e.assigned_[n]=!0),!0},deleteProperty(e,n){return tr(e.base_,n)!==void 0||n in e.base_?(e.assigned_[n]=!1,rr(e),cr(e)):delete e.assigned_[n],e.copy_&&delete e.copy_[n],!0},getOwnPropertyDescriptor(e,n){let t=en(e),r=Reflect.getOwnPropertyDescriptor(t,n);return r&&{writable:!0,configurable:e.type_!==1||n!=="length",enumerable:r.enumerable,value:t[n]}},defineProperty(){Ee(11)},getPrototypeOf(e){return bn(e.base_)},setPrototypeOf(){Ee(12)}},Pn={};ft(fr,(e,n)=>{Pn[e]=function(){return arguments[0]=arguments[0][0],n.apply(this,arguments)}});Pn.deleteProperty=function(e,n){return Pn.set.call(this,e,n,void 0)};Pn.set=function(e,n,t){return fr.set.call(this,e[0],n,t,e[0])};function tr(e,n){let t=e[ye];return(t?en(t):e)[n]}function Hc(e,n,t){let r=ci(n,t);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function ci(e,n){if(!(n in e))return;let t=bn(e);for(;t;){let r=Object.getOwnPropertyDescriptor(t,n);if(r)return r;t=bn(t)}}function cr(e){e.modified_||(e.modified_=!0,e.parent_&&cr(e.parent_))}function rr(e){e.copy_||(e.copy_=ir(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Wc=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(n,t,r)=>{if(typeof n=="function"&&typeof t!="function"){let i=t;t=n;let s=this;return function(a=i,...c){return s.produce(a,u=>t.call(this,u,...c))}}typeof t!="function"&&Ee(6),r!==void 0&&typeof r!="function"&&Ee(7);let o;if(nn(n)){let i=ni(this),s=lr(n,void 0),l=!0;try{o=t(s),l=!1}finally{l?sr(i):ar(i)}return ei(i,r),ti(o,i)}else if(!n||typeof n!="object"){if(o=t(n),o===void 0&&(o=n),o===oi&&(o=void 0),this.autoFreeze_&&dr(o,!0),r){let i=[],s=[];tn("Patches").generateReplacementPatches_(n,o,i,s),r(i,s)}return o}else Ee(1,n)},this.produceWithPatches=(n,t)=>{if(typeof n=="function")return(s,...l)=>this.produceWithPatches(s,a=>n(a,...l));let r,o;return[this.produce(n,t,(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){nn(e)||Ee(8),ie(e)&&(e=Ue(e));let n=ni(this),t=lr(e,void 0);return t[ye].isManual_=!0,ar(n),t}finishDraft(e,n){let t=e&&e[ye];(!t||!t.isManual_)&&Ee(9);let{scope_:r}=t;return ei(r,n),ti(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,n){let t;for(t=n.length-1;t>=0;t--){let o=n[t];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}t>-1&&(n=n.slice(t+1));let r=tn("Patches").applyPatches_;return ie(e)?r(e,n):this.produce(e,o=>r(o,n))}};function lr(e,n){let t=ht(e)?tn("MapSet").proxyMap_(e,n):yt(e)?tn("MapSet").proxySet_(e,n):Yc(e,n);return(n?n.scope_:ai()).drafts_.push(t),t}function Ue(e){return ie(e)||Ee(10,e),li(e)}function li(e){if(!nn(e)||bt(e))return e;let n=e[ye],t;if(n){if(!n.modified_)return n.base_;n.finalized_=!0,t=ir(e,n.scope_.immer_.useStrictShallowCopy_)}else t=ir(e,!0);return ft(t,(r,o)=>{si(t,r,li(o))}),n&&(n.finalized_=!1),t}var we=new Wc,pr=we.produce,bh=we.produceWithPatches.bind(we),Ih=we.setAutoFreeze.bind(we),wh=we.setUseStrictShallowCopy.bind(we),Ah=we.applyPatches.bind(we),Eh=we.createDraft.bind(we),xh=we.finishDraft.bind(we);var y={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},M={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},In={NOT:0};var R=class extends Error{constructor(n){super(`Parse Error: ${n}`),this.name="JemplParseError"}},pe=class extends Error{constructor(n){super(`Render Error: ${n}`),this.name="JemplRenderError"}};var mr=e=>{if(!e||e.trim()==="")throw new R("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let t=e.includes("===")?"==":"!=";throw new R(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${t}'? (got: '${e}')`)}let n=["<",">","<=",">=","==","!="];for(let t of n)if(e.trim().endsWith(t))throw new R(`Incomplete comparison expression - missing right operand (got: '${e}')`)},ui=e=>{if(e.trim().endsWith(" in"))throw new R(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new R(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[n,t]=e.split(" in ");if(!t||t.trim()==="")throw new R(`Missing iterable expression after 'in' (got: '$for ${e}')`);let r=n.includes(",")?n.split(",").map(o=>o.trim()):[n.trim()];for(let o of r){if(!o)throw new R(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new R(`Invalid loop syntax (got: '$for ${e}')`)}};var di=(e,n,t=!1)=>{if(n===null)return new pe(`Cannot iterate over null value at '$for ${e}'`);if(n===void 0)return new pe(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof n;return t?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}'`)},fi=(e,n)=>{let t=n&&Object.keys(n).length>0?Object.keys(n).join(", "):"no custom functions provided";return new pe(`Unknown function '${e}' (${t})`)};var Kc=(e,n,t={})=>{let r={},o={};t&&typeof t=="object"&&(t.functions!==void 0||t.partials!==void 0?(r=t.functions||{},o=t.partials||{}):typeof t=="object"&&(r=t));let s=V(e,{functions:r,partials:o},n,{});return s===void 0?{}:s},V=(e,n,t,r)=>{let o=n.functions||n;if(e.var&&!e.type)return ee(e.var,t,r);if(e.type===y.LITERAL)return e.value;if(e.type===y.VARIABLE)return ee(e.path,t,r);if(e.type===y.INTERPOLATION)return Xc(e.parts,n,t,r);switch(e.type){case y.FUNCTION:return mi(e,n,t,r);case y.BINARY:return gi(e,n,t,r);case y.UNARY:return hi(e,n,t,r);case y.CONDITIONAL:return Zc(e,n,t,r);case y.LOOP:return ol(e,n,t,r);case y.OBJECT:return sl(e,n,t,r);case y.ARRAY:return al(e,n,t,r);case y.PARTIAL:return cl(e,n,t,r);case y.PATH_REFERENCE:return ll(e,n,t,r);default:throw new Error(`Unknown node type: ${e.type}`)}},pi=new Map,Jc=e=>{let n=[],t="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")t&&(n.push({type:"property",value:t}),t=""),r=!0;else if(i==="]"){if(r&&t){let s=t.trim();if(/^\d+$/.test(s))n.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let l=s.slice(1,-1);n.push({type:"property",value:l})}else n.push({type:"property",value:s});t=""}r=!1}else t+=i}return t&&n.push({type:"property",value:t}),n},ee=(e,n,t)=>{if(!e)return;if(e in t)return t[e];let r=pi.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=Jc(a.trim());r.push(...c)}pi.set(e,r)}let o=n;for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="property"&&s.value in t){o=t[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},Xc=(e,n,t,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=V(i,n,t,r);o.push(s!=null?String(s):"")}return o.join("")},mi=(e,n,t,r)=>{let o=n.functions||n,i=o[e.name];if(!i)throw fi(e.name,o);let s=e.args.map(l=>V(l,n,t,r));return i(...s)},Be=(e,n,t,r)=>{if(e.var&&!e.type)return ee(e.var,t,r);switch(e.type){case y.VARIABLE:return ee(e.path,t,r);case y.LITERAL:return e.value;case y.BINARY:return gi(e,n,t,r);case y.UNARY:return hi(e,n,t,r);case y.FUNCTION:return mi(e,n,t,r);default:return V(e,n,t,r)}},gi=(e,n,t,r)=>{if(e.op===M.AND||e.op===M.OR){let s=Be(e.left,n,t,r),l=Be(e.right,n,t,r);switch(e.op){case M.AND:return s&&l;case M.OR:return s||l}}let o=V(e.left,n,t,r),i=V(e.right,n,t,r);switch(e.op){case M.EQ:return o==i;case M.NEQ:return o!=i;case M.GT:return o>i;case M.LT:return o<i;case M.GTE:return o>=i;case M.LTE:return o<=i;case M.IN:return Array.isArray(i)?i.includes(o):!1;case M.ADD:if(typeof o!="number"||typeof i!="number")throw new pe(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case M.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}`)}},hi=(e,n,t,r)=>{let o=e.op===In.NOT?Be(e.operand,n,t,r):V(e.operand,n,t,r);if(e.op===In.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Qc=(e,n,t,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===y.VARIABLE)if(ee(o.path,t,r)){let s=e.bodies[0];if(s.type===y.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?V(a.parsedKey,n,t,r):a.key,u=a.value;if(u.type===y.LITERAL)l[c]=u.value;else if(u.type===y.VARIABLE)l[c]=ee(u.path,t,r);else if(u.type===y.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===y.VARIABLE){let p=ee(f.path,t,r);d.push(p!=null?String(p):"")}else{let p=V(f,n,t,r);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=V(u,n,t,r)}return l}}else{let s=e.bodies[1];if(s.type===y.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?V(a.parsedKey,n,t,r):a.key,u=a.value;if(u.type===y.LITERAL)l[c]=u.value;else if(u.type===y.VARIABLE)l[c]=ee(u.path,t,r);else if(u.type===y.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===y.VARIABLE){let p=ee(f.path,t,r);d.push(p!=null?String(p):"")}else{let p=V(f,n,t,r);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=V(u,n,t,r)}return l}}}return null},Zc=(e,n,t,r)=>{let o=Qc(e,n,t,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||Be(s,n,t,r))return V(e.bodies[i],n,t,r)}return yi},el=(e,n)=>{let t=e.body,r=e.itemVar;if(t.type===y.CONDITIONAL&&t.conditions.length===1&&t.conditions[0].type===y.VARIABLE){let o=t.conditions[0].path,i=t.bodies[0];if(o.startsWith(r+".")){let s=o.substring(r.length+1);if(i.type===y.OBJECT&&i.properties.length<=5){for(let a of i.properties)if(a.parsedKey)return null;let l=[];for(let a=0;a<n.length;a++){let c=n[a];if(c[s]){let u={};for(let d of i.properties){let f=d.key,p=d.value;if(p.type===y.LITERAL)u[f]=p.value;else if(p.type===y.VARIABLE){let g=p.path;if(g===r)u[f]=c;else if(g.startsWith(r+".")){let h=g.substring(r.length+1);u[f]=c[h]}else return null}else if(p.type===y.INTERPOLATION){let g=[],h=!0;for(let b of p.parts)if(typeof b=="string")g.push(b);else if(b.type===y.VARIABLE){let I=b.path;if(I===r)g.push(c!=null?String(c):"");else if(I.startsWith(r+".")){let E=I.substring(r.length+1),A=c[E];g.push(A!=null?String(A):"")}else{h=!1;break}}else{h=!1;break}if(!h)return null;u[f]=g.join("")}else return null}l.push(u)}}return l}}}return null},nl=(e,n)=>{let t=e.body,r=e.itemVar,o=el(e,n);if(o!==null)return o;if(t.type===y.OBJECT&&t.properties.length<=5&&!t.whenCondition){for(let l of t.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of t.properties){let a=l.key,c=l.value;if(c.type===y.LITERAL)i.push({key:a,type:"literal",value:c.value});else if(c.type===y.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===y.INTERPOLATION&&c.parts.length===1){let u=c.parts[0];if(u.type===y.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(n.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<n.length;a++){let c=n[a];l[a]={id:c.id,title:c.title!=null?String(c.title):"",completed:c.completed}}else for(let a=0;a<n.length;a++){let c=n[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},tl=(e,n,t,r,o)=>{let i=[],s=e.body;if(s.type===y.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 g=p.split("."),h=g[0];h in r.__paths__&&(p=r.__paths__[h],g.length>1&&(p+="."+g.slice(1).join(".")))}f.__paths__={...f.__paths__,[l]:`${p}[${c}]`,...a&&{[a]:c}};for(let g of s.properties){let h=g.parsedKey?V(g.parsedKey,n,t,f):g.key,b=g.value;if(b.type===y.LITERAL)d[h]=b.value;else if(b.type===y.VARIABLE){let I=b.path;if(I===l)d[h]=u;else if(I===a)d[h]=c;else if(I.startsWith(l+".")){let E=I.substring(l.length+1);!E.includes(".")&&!E.includes("[")?d[h]=u[E]:d[h]=ee(I,t,{...r,[l]:u,...a&&{[a]:c}})}else d[h]=ee(I,t,{...r,[l]:u,...a&&{[a]:c}})}else if(b.type===y.INTERPOLATION){let I=[];for(let E of b.parts)if(typeof E=="string")I.push(E);else if(E.type===y.VARIABLE){let A=E.path,$;if(A===l)$=u;else if(A===a)$=c;else if(A.startsWith(l+".")){let B=A.substring(l.length+1);!B.includes(".")&&!B.includes("[")?$=u[B]:$=ee(A,t,{...r,[l]:u,...a&&{[a]:c}})}else $=ee(A,t,{...r,[l]:u,...a&&{[a]:c}});I.push($!=null?String($):"")}else{let A={...r,[l]:u,...a&&{[a]:c}},$=V(E,n,t,A);I.push($!=null?String($):"")}d[h]=I.join("")}else{let I={...r,[l]:u,...a&&{[a]:c}};d[h]=V(b,n,t,I)}}i.push(d)}return i}return null},rl=(e,n,t)=>{let r=e.body;if(r.type===y.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===y.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===y.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===y.OBJECT&&s.properties.length===2){let l=s.properties[0],a=s.properties[1];if(l.key==="id"&&l.value.type===y.VARIABLE&&l.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===y.CONDITIONAL){let c=[];for(let u=0;u<n.length;u++){let d=n[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},ol=(e,n,t,r)=>{let o=V(e.iterable,n,t,r);if(!Array.isArray(o)){let c,u=!1;if(e.iterable.type===y.FUNCTION){u=!0;let f=e.iterable.args.map(p=>p.type===y.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===y.VARIABLE?p.path:p.type===y.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 di(d,o,u)}if(!e.indexVar){let c=rl(e,o,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=nl(e,o);if(c!==null)return c}let i=tl(e,n,t,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===y.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(c=>c.type===y.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=V(e.body,n,t,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},il=(e,n,t,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?V(o.parsedKey,n,t,r):o.key,s=o.value;if(s.type===y.OBJECT&&s.properties.length<=10&&!s.whenCondition){let l={},a={},c=!0;for(let u of s.properties){let d=u.parsedKey?V(u.parsedKey,n,t,r):u.key,f=u.value;if(f.type===y.LITERAL)a[d]=f.value;else if(f.type===y.VARIABLE)a[d]=ee(f.path,t,r);else if(f.type===y.INTERPOLATION){let p=[];for(let g of f.parts)if(typeof g=="string")p.push(g);else if(g.type===y.VARIABLE){let h=ee(g.path,t,r);p.push(h!=null?String(h):"")}else{c=!1;break}if(!c)break;a[d]=p.join("")}else if(f.type===y.OBJECT&&f.properties.length<=5){let p={};for(let g of f.properties){let h=g.key,b=g.value;if(b.type===y.LITERAL)p[h]=b.value;else if(b.type===y.VARIABLE)p[h]=ee(b.path,t,r);else if(b.type===y.INTERPOLATION){let I=[];for(let E of b.parts)if(typeof E=="string")I.push(E);else if(E.type===y.VARIABLE){let A=ee(E.path,t,r);I.push(A!=null?String(A):"")}else{c=!1;break}if(!c)break;p[h]=I.join("")}else{c=!1;break}}if(!c)break;a[d]=p}else{c=!1;break}}if(c)return l[i]=a,l}}return null},sl=(e,n,t,r)=>{let o=n.functions||n;if(e.whenCondition&&!Be(e.whenCondition,o,t,r))return;let i=il(e,n,t,r);if(i!==null)return i;if(e.fast){let c={};for(let u of e.properties){let d=u.parsedKey?V(u.parsedKey,n,t,r):u.key,f=u.value;if(f.type===y.LITERAL)c[d]=f.value;else if(f.type===y.VARIABLE)c[d]=ee(f.path,t,r);else if(f.type===y.INTERPOLATION){let p=[];for(let g of f.parts)if(typeof g=="string")p.push(g);else if(g.type===y.VARIABLE){let h=ee(g.path,t,r);p.push(h!=null?String(h):"")}else{let h=V(g,n,t,r);p.push(h!=null?String(h):"")}c[d]=p.join("")}else c[d]=V(f,n,t,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=V(c.value,n,t,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 V(c.value,n,t,r)}else{let u=c.value;if(u&&u.type===y.OBJECT&&u.properties){let d=u.properties.find(f=>f.key.startsWith("$for "));if(d){let f=V(d.value,n,t,r);f!==void 0&&(s[c.key]=f)}else{let f=V(c.value,n,t,r);f!==void 0&&(s[c.key]=f)}}else{let d=c.parsedKey?V(c.parsedKey,n,t,r):c.key,f=V(c.value,n,t,r);f!==void 0&&(s[d]=f)}}return s},yi={},al=(e,n,t,r)=>{let o=[];for(let i of e.items)if(i.type===y.LOOP){let s=V(i,n,t,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=V(i,n,t,r);s!==yi&&s!==void 0&&o.push(s)}return o},cl=(e,n,t,r)=>{let{name:o,data:i,whenCondition:s}=e,l=n.partials||{},a=n.functions||n;if(s&&!Be(s,a,t,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=t,f={...r,_partialStack:[...c,o]};if(r){d={...t};for(let p of Object.keys(r))p.startsWith("_")||(d[p]=r[p])}if(i){let p=V(i,n,t,r);d={...d,...p}}return V(u,n,d,f)},ll=(e,n,t,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 gr=Kc;var ul=/\$\{([^}]*)\}/g,dl=/#\{([^}]*)\}/g,Ii=(e,n={})=>{let t=e.match(/^(\w+)\((.*)\)$/);if(!t)return{isFunction:!1};let[,r,o]=t,i=fl(o,n);return{isFunction:!0,type:y.FUNCTION,name:r,args:i}},fl=(e,n={})=>e.trim()?pl(e).map(r=>ml(r.trim(),n)):[],pl=e=>{let n=[],t="",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,t+=l):o&&l===i&&a!=="\\"?(o=!1,i="",t+=l):!o&&l==="("?(r++,t+=l):!o&&l===")"?(r--,t+=l):!o&&l===","&&r===0?(n.push(t),t=""):t+=l}return t&&n.push(t),n},ml=(e,n={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:y.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:y.LITERAL,value:parseFloat(e)};if(e==="true")return{type:y.LITERAL,value:!0};if(e==="false")return{type:y.LITERAL,value:!1};if(e==="null")return{type:y.LITERAL,value:null};let t=Ii(e,n);if(t.isFunction)return{type:t.type,name:t.name,args:t.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=rn(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 re(r,n)}catch{return{type:y.VARIABLE,path:r}}return{type:y.VARIABLE,path:r}},wi=/^\w+\(.*\)$/,gl=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,hl=e=>{if(!(!e||e.trim()===""||wi.test(e))&&gl.test(e))throw e.includes("?")&&e.includes(":")?new R(`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 R(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new R(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},bi=e=>{let n=e.trim();if(wi.test(n))throw new R(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(n.includes("["))throw new R(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(n))throw new R(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(n))throw new R(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(n.includes("?")&&n.includes(":"))throw new R(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:y.PATH_REFERENCE,path:n}},Nn=(e,n={})=>{let t=e.trim();hl(t);let r=Ii(t,n);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};if(t.includes("[")&&!/[\s+\-*/%|&?:]/.test(t)){let o=0;for(let i of t)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:y.VARIABLE,path:t}},hr=(e,n={})=>{let t=e,r=[];(e.includes("\\${")||e.includes("\\#{"))&&(t=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),t=t.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),t=t.replace(/\\(\$\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${r.length}__`;return r.push(u),d}),t=t.replace(/\\(#\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${r.length}__`;return r.push(u),d}),t=t.replace(/\\DOUBLE_ESC_VAR/g,"\\"),t=t.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...t.matchAll(ul)],i=[...t.matchAll(dl)],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=t;for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);return{type:y.LITERAL,value:c}}if(s.length===1&&s[0].match[0]===t&&r.length===0){let{match:c,type:u}=s[0];try{return u==="variable"?Nn(c[1],n):bi(c[1])}catch(d){if(d.message==="Invalid array index syntax")return{type:y.LITERAL,value:t};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 g=t.substring(a,p);for(let h=0;h<r.length;h++)g=g.replace(`__ESCAPED_${h}__`,r[h]);g&&l.push(g)}try{let g;u==="variable"?g=Nn(f.trim(),n):g=bi(f.trim()),l.push(g)}catch(g){if(g.message==="Invalid array index syntax")l.push(d);else throw g}a=p+d.length}if(a<t.length){let c=t.substring(a);for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);c&&l.push(c)}return{type:y.INTERPOLATION,parts:l}};var Ir=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),xi=e=>Object.keys(e),ue=e=>e.join("."),Ge=(e,n,t)=>{let r=xi(e).filter(o=>!n.has(o));if(r.length>0)throw new R(`Unexpected key '${r[0]}' in condition JSON at '${ue(t)}'`)},ze=(e,n)=>typeof e=="string"?hr(e,n):typeof e=="object"&&e!==null?Array.isArray(e)?bl(e,n):Il(e,n):{type:y.LITERAL,value:e},yl=e=>{let{$each:n,...t}=e;if(typeof n!="string")throw new R("$each value must be a non-empty string");let r=n.trim();if(r==="")throw new R("$each value must be a non-empty string");if(Object.keys(t).length===0)throw new R("Empty $each body not allowed");if(t.$partial!==void 0)throw new R("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:t}},bl=(e,n)=>{let t=[],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=yl(i),c=Object.keys(a);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let u=Ei(c[0],a[c[0]],n,!0);t.push(u),r=!0;continue}}catch(a){throw a instanceof R?a:new R(a.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let a=Ei(l[0],i[l[0]],n);t.push(a),r=!0;continue}}let s=ze(i,n);t.push(s),(s.type===y.FUNCTION||s.type===y.CONDITIONAL||s.type===y.LOOP||s.type===y.PARTIAL||s.type===y.OBJECT&&!s.fast||s.type===y.ARRAY&&!s.fast)&&(r=!0)}return{type:y.ARRAY,items:t,fast:!r}},Il=(e,n)=>{let t=[],r=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new R("$partial value must be a string");if(e.$partial.trim()==="")throw new R("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],c=[];for(let[I]of i)for(let E of a)if(I===E||I.startsWith(E+" ")||I.startsWith(E+"#")){c.push(E);break}if(c.length>0)throw new R(`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={},g=!1;for(let[I,E]of Object.entries(f)){let A=I;(I.startsWith("\\$")||I.startsWith("$$"))&&(A=I.slice(1)),p[A]=E,g=!0}let h=null;if(g&&(h=ze(p,n),h.type===y.OBJECT)){let I=!1;for(let E of h.properties)if(E.value.type===y.VARIABLE||E.value.type===y.INTERPOLATION||E.value.type===y.FUNCTION||E.value.type===y.CONDITIONAL||E.value.type===y.OBJECT&&!E.value.fast||E.value.type===y.ARRAY&&!E.value.fast){I=!0;break}I&&(h.fast=!1)}let b={type:y.PARTIAL,name:u,data:h};return d!==void 0&&(b.whenCondition=Ai(d,n)),b}for(let[a,c]of i)if(a==="$when"){if(o!==null)throw new R("Multiple '$when' directives on the same object are not allowed");if(c==null)throw new R("Missing condition expression after '$when'");o=Ai(c,n),r=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new R("'$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 R("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let u=wl(i,s,n);t.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 R(`$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 R(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new R("Missing condition expression after '$if'");{let u=ze(c,n);(u.type===y.FUNCTION||u.type===y.CONDITIONAL||u.type===y.PARTIAL||u.type===y.OBJECT&&!u.fast||u.type===y.ARRAY&&!u.fast)&&(r=!0);let d=hr(a,n),f={key:a,value:u};(d.type!==y.LITERAL||d.value!==a)&&(f.parsedKey=d),t.push(f),s++}}}let l={type:y.OBJECT,properties:t,fast:!r};return o&&(l.whenCondition=o),l},wl=(e,n,t={})=>{let r=[],o=[],i=n,[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 R(`Invalid conditional syntax: ${s}`)}else c=s.substring(4),c.endsWith(":")&&(c=c.slice(0,-1).trim());mr(c);let u=re(c,t);for(r.push(u),o.push(ze(l,t)),i++;i<e.length;){let[d,f]=e[i],p=!1,g;if(a?d.startsWith(`$elif#${a} `)?(g=d.substring(`$elif#${a} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),p=!0):(d===`$else#${a}`||d===`$else#${a}:`)&&(p=!0,g=null):d.startsWith("$elif ")?(g=d.substring(6),g.endsWith(":")&&(g=g.slice(0,-1).trim()),p=!0):(d==="$else"||d==="$else:")&&(p=!0,g=null),p){if(g===null)r.push(null);else{mr(g);let h=re(g,t);r.push(h)}if(o.push(ze(f,t)),i++,g===null)break}else break}return{node:{type:y.CONDITIONAL,conditions:r,bodies:o,id:a},nextIndex:i}},yr={eq:M.EQ,neq:M.NEQ,gt:M.GT,gte:M.GTE,lt:M.LT,lte:M.LTE,in:M.IN,add:M.ADD,sub:M.SUBTRACT},br={all:M.AND,any:M.OR},Al=new Set(["var","literal","call","not",...Object.keys(yr),...Object.keys(br)]),El=(e,n,t)=>{if(!Array.isArray(e))throw new R(`Condition JSON operator '${n}' at '${ue(t)}' requires an array`);if(e.length!==2)throw new R(`Condition JSON operator '${n}' at '${ue(t)}' requires exactly 2 operands`);return e},xl=(e,n,t,r,o)=>{if(!Array.isArray(e))throw new R(`Condition JSON operator '${n}' at '${ue(o)}' requires an array`);if(e.length===0)throw new R(`Condition JSON operator '${n}' at '${ue(o)}' requires at least 1 condition`);return e.map((s,l)=>be(s,r,[...o,l])).reduce((s,l)=>({type:y.BINARY,op:t,left:s,right:l}))},vl=(e,n,t)=>{let r,o;if(typeof e.call=="string")r=e.call,o=e.args??[],Ge(e,new Set(["call","args"]),t);else if(Ir(e.call))r=e.call.name,o=e.call.args??[],Ge(e,new Set(["call"]),t),Ge(e.call,new Set(["name","args"]),[...t,"call"]);else throw new R(`Condition JSON call at '${ue(t)}' requires a function name`);if(typeof r!="string"||r.trim()==="")throw new R(`Condition JSON call at '${ue(t)}' requires a non-empty function name`);if(!/^\w+$/.test(r))throw new R(`Invalid condition JSON function name '${r}' at '${ue(t)}'`);if(!Array.isArray(o))throw new R(`Condition JSON call '${r}' at '${ue(t)}' requires args to be an array`);return{type:y.FUNCTION,name:r,args:o.map((i,s)=>be(i,n,[...t,"args",s]))}},be=(e,n={},t=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:y.LITERAL,value:e};if(Array.isArray(e))throw new R(`Condition JSON array at '${ue(t)}' must be wrapped in an operator or { literal: [...] }`);if(!Ir(e))throw new R(`Invalid condition JSON value at '${ue(t)}'`);let r=xi(e);if(r.length===0)throw new R(`Condition JSON object at '${ue(t)}' must contain an operator`);let o=r.filter(s=>Al.has(s));if(o.length===0)throw new R(`Unknown condition JSON operator '${r[0]}' at '${ue(t)}'`);if(o.length>1)throw new R(`Condition JSON at '${ue(t)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(Ge(e,new Set(["var"]),t),typeof e.var!="string"||e.var.trim()==="")throw new R(`Condition JSON var at '${ue(t)}' requires a non-empty path`);return{type:y.VARIABLE,path:e.var}}if(i==="literal")return Ge(e,new Set(["literal"]),t),{type:y.LITERAL,value:e.literal};if(i==="call")return vl(e,n,t);if(i==="not")return Ge(e,new Set(["not"]),t),{type:y.UNARY,op:In.NOT,operand:be(e.not,n,[...t,"not"])};if(i in br)return Ge(e,new Set([i]),t),xl(e[i],i,br[i],n,[...t,i]);if(i in yr){Ge(e,new Set([i]),t);let s=El(e[i],i,[...t,i]);return{type:y.BINARY,op:yr[i],left:be(s[0],n,[...t,i,0]),right:be(s[1],n,[...t,i,1])}}throw new R(`Unknown condition JSON operator '${i}' at '${ue(t)}'`)},Ai=(e,n={})=>{if(e==null)throw new R("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new R("Empty condition expression after '$when'");return re(e,n)}return Ir(e)||Array.isArray(e)?be(e,n):{type:y.LITERAL,value:e}},re=(e,n={})=>{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 re(c,n)}let t=rn(e,"||");if(t!==-1)return{type:y.BINARY,op:M.OR,left:re(e.substring(0,t).trim(),n),right:re(e.substring(t+2).trim(),n)};let r=rn(e,"&&");if(r!==-1)return{type:y.BINARY,op:M.AND,left:re(e.substring(0,r).trim(),n),right:re(e.substring(r+2).trim(),n)};let o=[{op:">=",type:M.GTE},{op:"<=",type:M.LTE},{op:"==",type:M.EQ},{op:"!=",type:M.NEQ},{op:">",type:M.GT},{op:"<",type:M.LT},{op:" in ",type:M.IN}];for(let{op:c,type:u}of o){let d=rn(e,c);if(d!==-1)return{type:y.BINARY,op:u,left:re(e.substring(0,d).trim(),n),right:re(e.substring(d+c.length).trim(),n)}}let i=-1,s=null,l=[{op:" + ",type:M.ADD},{op:" - ",type:M.SUBTRACT}];for(let{op:c,type:u}of l){let d=0;for(;d<e.length;){let f=rn(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:y.BINARY,op:s.type,left:re(e.substring(0,i).trim(),n),right:re(e.substring(i+s.op.length).trim(),n)};let a=[" * "," / "," % "];for(let c of a)if(rn(e,c)!==-1)throw new R(`Arithmetic operations are not allowed in conditionals: "${c}"`);return e.startsWith("!")?{type:y.UNARY,op:In.NOT,operand:re(e.substring(1).trim(),n)}:vi(e,n)},rn=(e,n)=>{let t=0,r=0;for(;r<=e.length-n.length;){if(e[r]==="(")t++;else if(e[r]===")")t--;else if(t===0&&e.substring(r,r+n.length)===n)return r;r++}return-1},Sl=e=>{if(e=e.trim(),e==="true")return{type:y.LITERAL,value:!0};if(e==="false")return{type:y.LITERAL,value:!1};if(e==="null")return{type:y.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:y.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:y.LITERAL,value:""};if(e==="{}")return{type:y.LITERAL,value:{}};if(e==="[]")return{type:y.LITERAL,value:[]};let n=Number(e);return!isNaN(n)&&isFinite(n)?{type:y.LITERAL,value:n}:{type:y.VARIABLE,path:e}},vi=(e,n)=>{let t=e.trim();if(t.match(/^(\w+)\((.*)\)$/))return Nn(t,n);let o=Sl(t);if(o.type===y.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(t))return{type:y.VARIABLE,path:t};try{return Nn(t,n)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Rl=(e,n=!1)=>{let t=n?"$each":"$for";try{ui(e)}catch(r){if(r instanceof R&&n){let o=r.message.replace(/\$for/g,"$each");throw new R(o.replace("Parse Error: ",""))}throw r}},Ei=(e,n,t,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let b=r?"$each":"$for";throw new R(`Invalid loop syntax (got: '${e.replace("$for",b)}')`)}let s=i[1],l=i[2].trim();Rl(l,r);let a=l.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let b=r?"$each":"$for";throw new R(`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(I=>I.trim());if(b.length!==2)throw new R(`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 R(`Reserved variable name: ${d}`);if(f&&p.includes(f))throw new R(`Reserved variable name: ${f}`);let g=vi(u,t),h=ze(n,t);return{type:y.LOOP,itemVar:d,indexVar:f,iterable:g,body:h,flatten:s!=="nested"}};var Cl=(e,n={})=>{let{functions:t={}}=n;return ze(e,t)},It=Cl;var Dn={};jc(Dn,{now:()=>_l});var _l=()=>Date.now();var kl=(e,n,t={})=>{let{functions:r={},partials:o={}}=t,i={...Dn,...r},s=It(e,{functions:i}),l={};for(let[a,c]of Object.entries(o))l[a]=It(c,{functions:i});return gr(s,n,{functions:i,partials:l})},on=kl;var Ol=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",$l=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Tl=(e,n)=>{if(Ol(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new R("Empty condition expression");return re(e,n)}return be(e,n)},Ll=(e,n={},t={})=>{let r=$l(t),o={...Dn,...r},i=Tl(e,o);return!!Be(i,{functions:o,partials:{}},n,{})},wr=Ll;var kr=Symbol("runStoreTransaction"),vr="__routeEngineConditionComparison",wt=(e,n)=>typeof e=="number"&&typeof n=="number"&&Number.isFinite(e)&&Number.isFinite(n)||typeof e=="string"&&typeof n=="string",qe=Object.freeze({eq:(e,n)=>e===n,neq:(e,n)=>e!==n,gt:(e,n)=>wt(e,n)&&e>n,gte:(e,n)=>wt(e,n)&&e>=n,lt:(e,n)=>wt(e,n)&&e<n,lte:(e,n)=>wt(e,n)&&e<=n}),$i=Object.freeze(Object.fromEntries(Object.keys(qe).map(e=>[e,`${vr}${e}`]))),Pl=Object.freeze(Object.fromEntries(Object.entries($i).map(([e,n])=>[n,qe[e]]))),Si=(e,n)=>Object.prototype.hasOwnProperty.call(e??{},n),Nl=e=>{if(typeof e?.call=="string")return e.call;if(e?.call!==null&&typeof e?.call=="object"&&!Array.isArray(e.call))return e.call.name},At=e=>{if(Array.isArray(e))return e.map(At);if(e===null||typeof e!="object"||Si(e,"literal")||Si(e,"var"))return e;if(Nl(e)?.startsWith(vr))throw new Error(`Condition function names beginning with "${vr}" are reserved`);let t=Object.entries(e);if(t.length===1){let[[r,o]]=t,i=$i[r];if(i)return{call:i,args:o.map(At)}}return Object.fromEntries(t.map(([r,o])=>[r,At(o)]))},Vn=(e,n={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return be(e),wr(At(e),n,{functions:Pl})},Dl=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Ti=(e,n,t={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:l=c=>c}=t;for(let[c,u]of Object.entries(n))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...d)=>u(s(r),...d):i[c]=(...d)=>{let f;return r=pr(r,g=>{let h=u(l(g),...d);f=h!==void 0&&!ie(h)?h:void 0}),f});let a=c=>{if(typeof c!="function")throw new Error("Store transaction requires a callback");let u=r;try{return c()}catch(d){throw r=u,d}};return{...o,...i,[kr]:a}},St=(e,n)=>t=>{let r=e(),o=Array.isArray(t)?t:[t];return pr(r,i=>{o.forEach(s=>{n.forEach(l=>{l(i,s)})})})};var Ml=(e,n)=>{if(e.default!==void 0)return e.default;let t=["number","boolean","string","object"];if(!t.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${n}. Expected one of: ${t.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},P=(e,n)=>Object.prototype.hasOwnProperty.call(e??{},n),Sr=(e,n,t)=>{Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0})},ne=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Vl=new Set(["pageSize","groups"]),jl=new Set(["id","variants"]),Fl=new Set(["id","imageId"]),Ul=new Set(["pageSize","tracks"]),Bl=new Set(["id","soundId","title","artist","album","description","coverImageId"]),Gl=new Set(["pageSize","replays"]),zl=new Set(["id","title","thumbnailImageId","startSectionId","initialVariables"]),sn=(e,n,t)=>{Object.keys(e).forEach(r=>{if(!n.has(r))throw new Error(`${t} contains unsupported property "${r}"`)})},wn=(e,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} must be a non-empty string`)},jn=(e={})=>{let n=e?.resources?.imageGallery;if(n===void 0)return;if(!ne(n))throw new Error("resources.imageGallery must be an object");if(sn(n,Vl,"resources.imageGallery"),!Number.isInteger(n.pageSize)||n.pageSize<1)throw new Error("resources.imageGallery.pageSize must be an integer greater than or equal to 1");if(!Array.isArray(n.groups))throw new Error("resources.imageGallery.groups must be an array");let t=new Set;for(let[r,o]of n.groups.entries()){let i=`resources.imageGallery.groups[${r}]`;if(!ne(o))throw new Error(`${i} must be an object`);if(sn(o,jl,i),wn(o.id,`${i}.id`),t.has(o.id))throw new Error(`Duplicate image gallery group id "${o.id}"`);if(t.add(o.id),!Array.isArray(o.variants)||o.variants.length===0)throw new Error(`${i}.variants must be a non-empty array`);let s=new Set;for(let[l,a]of o.variants.entries()){let c=`${i}.variants[${l}]`;if(!ne(a))throw new Error(`${c} must be an object`);if(sn(a,Fl,c),wn(a.id,`${c}.id`),wn(a.imageId,`${c}.imageId`),s.has(a.id))throw new Error(`Duplicate image gallery variant id "${a.id}" in group "${o.id}"`);if(s.add(a.id),!P(e?.resources?.images,a.imageId))throw new Error(`Image gallery variant "${o.id}.${a.id}" references unknown image "${a.imageId}"`)}}},Fn=(e={})=>{let n=e?.resources?.musicRoom;if(n===void 0)return;if(!ne(n))throw new Error("resources.musicRoom must be an object");if(sn(n,Ul,"resources.musicRoom"),!Number.isInteger(n.pageSize)||n.pageSize<1)throw new Error("resources.musicRoom.pageSize must be an integer greater than or equal to 1");if(!Array.isArray(n.tracks))throw new Error("resources.musicRoom.tracks must be an array");let t=new Set;for(let[r,o]of n.tracks.entries()){let i=`resources.musicRoom.tracks[${r}]`;if(!ne(o))throw new Error(`${i} must be an object`);sn(o,Bl,i);for(let a of["id","soundId","title"])wn(o[a],`${i}.${a}`);for(let a of["artist","album","description","coverImageId"])o[a]!==void 0&&wn(o[a],`${i}.${a}`);if(t.has(o.id))throw new Error(`Duplicate music room track id "${o.id}"`);t.add(o.id);let s=e?.resources?.sounds?.[o.soundId];if(!P(e?.resources?.sounds,o.soundId))throw new Error(`Music room track "${o.id}" references unknown sound "${o.soundId}"`);if(!ne(s))throw new Error(`Music room track "${o.id}" references invalid sound "${o.soundId}"`);if(s.playbackRate!==void 0&&(typeof s.playbackRate!="number"||!Number.isFinite(s.playbackRate)||s.playbackRate<=0))throw new Error(`Music room sound "${o.soundId}" playbackRate must be a finite number greater than 0`);let l=s.startAt??0;if(typeof l!="number"||!Number.isFinite(l)||l<0)throw new Error(`Music room sound "${o.soundId}" startAt must be a finite non-negative number`);if(s.endAt!==void 0&&s.endAt!==null&&(typeof s.endAt!="number"||!Number.isFinite(s.endAt)||s.endAt<=l))throw new Error(`Music room sound "${o.soundId}" endAt must be a finite number greater than startAt`);if(o.coverImageId!==void 0&&!P(e?.resources?.images,o.coverImageId))throw new Error(`Music room track "${o.id}" references unknown cover image "${o.coverImageId}"`)}},ql=(e,n,t)=>{let r=Array.isArray(t)?"array":typeof t;switch(n.type){case"number":if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Scene replay initial variable "${e}" expected type number, got ${r}`);return;case"boolean":if(typeof t!="boolean")throw new Error(`Scene replay initial variable "${e}" expected type boolean, got ${r}`);return;case"string":if(typeof t!="string")throw new Error(`Scene replay initial variable "${e}" expected type string, got ${r}`);return;case"object":if(t===null||typeof t!="object")throw new Error(`Scene replay initial variable "${e}" expected type object, got ${r}`);return;default:throw new Error(`Scene replay initial variable "${e}" has invalid variable type "${n.type}"`)}},Un=(e={})=>{let n=e?.resources?.sceneReplay;if(n===void 0)return;if(!ne(n))throw new Error("resources.sceneReplay must be an object");if(sn(n,Gl,"resources.sceneReplay"),!Number.isInteger(n.pageSize)||n.pageSize<1)throw new Error("resources.sceneReplay.pageSize must be an integer greater than or equal to 1");if(!Array.isArray(n.replays))throw new Error("resources.sceneReplay.replays must be an array");let t=new Map;Object.values(e?.story?.scenes??{}).forEach(o=>{Object.entries(o?.sections??{}).forEach(([i,s])=>{t.set(i,s)})});let r=new Set;for(let[o,i]of n.replays.entries()){let s=`resources.sceneReplay.replays[${o}]`;if(!ne(i))throw new Error(`${s} must be an object`);sn(i,zl,s);for(let a of["id","title","thumbnailImageId","startSectionId"])wn(i[a],`${s}.${a}`);if(r.has(i.id))throw new Error(`Duplicate scene replay id "${i.id}"`);if(r.add(i.id),!P(e?.resources?.images,i.thumbnailImageId))throw new Error(`Scene replay "${i.id}" references unknown thumbnail image "${i.thumbnailImageId}"`);if(!t.has(i.startSectionId))throw new Error(`Scene replay "${i.id}" references unknown start section "${i.startSectionId}"`);let l=t.get(i.startSectionId);if(l.initialLineId!==void 0&&!l.lines?.some(a=>a.id===l.initialLineId))throw new Error(`Scene replay "${i.id}" start section "${i.startSectionId}" references unknown initial line "${l.initialLineId}"`);if(i.initialVariables!==void 0){if(!ne(i.initialVariables))throw new Error(`${s}.initialVariables must be an object`);for(let[a,c]of Object.entries(i.initialVariables)){let u=e?.resources?.variables?.[a];if(!u)throw new Error(`Scene replay "${i.id}" initialVariables references unknown variable "${a}"`);if(Se(u))throw new Error(`Scene replay "${i.id}" cannot initialize computed variable "${a}"`);if(u.readonly===!0)throw new Error(`Scene replay "${i.id}" cannot initialize readonly variable "${a}"`);if(u.scope!=="context")throw new Error(`Scene replay "${i.id}" can only initialize context variable "${a}"`);ql(a,u,c)}}}},Li=e=>{let n=ie(e)?Ue(e):e;return structuredClone(n)},Yl=({characterId:e,resourceCharacter:n,variables:t={}}={})=>{if(!P(n,"nameVariableId"))return;let r=n.nameVariableId,o=t?.[r];if(typeof o!="string")throw new Error(`Character "${e}" nameVariableId "${r}" must resolve to a string variable`);return o},Rt=({characterId:e,character:n,characterName:t,characters:r={},variables:o={}}={})=>{let i=e?r?.[e]:void 0;if(n?.name!==void 0)return n.name;if(t!==void 0)return t;let s=Yl({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},Se=e=>P(e,"computed"),An=(e={},n={})=>Object.fromEntries(Object.entries(e??{}).filter(([t])=>!Se(n[t]))),ve=(e,n)=>new Error(`${n} has invalid path: ${JSON.stringify(e)}`),Hl=(e,n,t)=>{if(e[0]==='"')try{return JSON.parse(e)}catch{throw ve(n,t)}let o="";for(let i=1;i<e.length-1;i+=1){let s=e[i];if(s!=="\\"){if(s.charCodeAt(0)<32)throw ve(n,t);o+=s;continue}if(i+=1,i>=e.length-1)throw ve(n,t);let l=e[i];if(l==="u"){let c=e.slice(i+1,i+5);if(c.length!==4||!/^[0-9a-fA-F]{4}$/.test(c))throw ve(n,t);o+=String.fromCharCode(Number.parseInt(c,16)),i+=4;continue}let a={"\\":"\\",'"':'"',"'":"'","/":"/",n:`
2
+ `,r:"\r",t:" ",b:"\b",f:"\f"};if(!P(a,l))throw ve(n,t);o+=a[l]}return o},Pi=(e,n="Computed expression var")=>{if(typeof e!="string"||e.length===0||e.trim()!==e)throw ve(e,n);let t=[],r=0,o=()=>{let s=r;for(;r<e.length&&e[r]!=="."&&e[r]!=="["&&e[r]!=="]";)r+=1;let l=e.slice(s,r);if(l.length===0||l.trim()!==l||/\s/.test(l))throw ve(e,n);t.push(l)},i=()=>{for(r+=1;r<e.length&&/\s/.test(e[r]);)r+=1;let s=e[r];if(/\d/.test(s??"")){let u=r;for(;r<e.length&&/\d/.test(e[r]);)r+=1;let d=e.slice(u,r);for(;r<e.length&&/\s/.test(e[r]);)r+=1;if(e[r]!=="]"||d.length>1&&d.startsWith("0"))throw ve(e,n);r+=1,t.push(d);return}if(s!=='"'&&s!=="'")throw ve(e,n);let l=s,a=r;r+=1;let c=!1;for(;r<e.length;){let u=e[r];if(c)c=!1;else if(u==="\\")c=!0;else if(u===l){let d=e.slice(a,r+1);for(r+=1;r<e.length&&/\s/.test(e[r]);)r+=1;if(e[r]!=="]")throw ve(e,n);r+=1,t.push(Hl(d,e,n));return}r+=1}if(c||r>=e.length)throw ve(e,n)};for(o();r<e.length;){if(e[r]==="."){r+=1,o();continue}if(e[r]==="["){i();continue}throw ve(e,n)}return t},Ar=(e,n)=>{let t=e;for(let r of n){if(t==null||!P(t,r))return;t=t[r]}return t},Ni=(e,n={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let t=Pi(e),[r,o,...i]=t;if(r==="variables"){if(!o)return n.variables;let s=typeof n.resolveVariable=="function"?n.resolveVariable(o):n.variables?.[o];return Ar(s,i)}return r==="runtime"?Ar(n.runtime,t.slice(1)):Ar(n,t)},Di=(e,n,t)=>{if(!Array.isArray(n))throw new Error(`Computed expression operator "${e}" requires an array`);if(t!==void 0&&n.length!==t)throw new Error(`Computed expression operator "${e}" requires ${t} operand(s)`)},Rr=(e,n)=>{if(!Array.isArray(n))throw new Error(`Computed expression operator "${e}" requires an array`);if(n.length===0)throw new Error(`Computed expression operator "${e}" requires at least one operand`)},Wl=(e,n)=>{if(typeof n!="number"||!Number.isFinite(n))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},_e=(e,n,t,r)=>(Di(e,n,r),n.map(o=>vt(o,t))),xe=(e,n,t,r)=>{let o=_e(e,n,t,r);return o.forEach(i=>Wl(e,i)),o},Kl=(e,n,t)=>{switch(e){case"var":return Ni(n,t);case"add":{let[r,o]=xe(e,n,t,2);return r+o}case"sub":{let[r,o]=xe(e,n,t,2);return r-o}case"mul":{let[r,o]=xe(e,n,t,2);return r*o}case"div":{let[r,o]=xe(e,n,t,2);return r/o}case"mod":{let[r,o]=xe(e,n,t,2);return r%o}case"neg":{let[r]=xe(e,n,t,1);return-r}case"round":{let[r]=xe(e,n,t,1);return Math.round(r)}case"floor":{let[r]=xe(e,n,t,1);return Math.floor(r)}case"ceil":{let[r]=xe(e,n,t,1);return Math.ceil(r)}case"min":{let[r,o]=xe(e,n,t,2);return Math.min(r,o)}case"max":{let[r,o]=xe(e,n,t,2);return Math.max(r,o)}case"clamp":{let[r,o,i]=xe(e,n,t,3);return Math.min(i,Math.max(o,r))}case"eq":{let[r,o]=_e(e,n,t,2);return qe.eq(r,o)}case"neq":{let[r,o]=_e(e,n,t,2);return qe.neq(r,o)}case"gt":{let[r,o]=_e(e,n,t,2);return qe.gt(r,o)}case"gte":{let[r,o]=_e(e,n,t,2);return qe.gte(r,o)}case"lt":{let[r,o]=_e(e,n,t,2);return qe.lt(r,o)}case"lte":{let[r,o]=_e(e,n,t,2);return qe.lte(r,o)}case"in":{let[r,o]=_e(e,n,t,2);return Array.isArray(o)?o.includes(r):!1}case"and":case"all":return Rr(e,n),n.every(r=>!!vt(r,t));case"or":case"any":return Rr(e,n),n.some(r=>!!vt(r,t));case"not":{let[r]=_e(e,n,t,1);return!r}case"length":{let[r]=_e(e,n,t,1);return typeof r=="string"||Array.isArray(r)?r.length:ne(r)?Object.keys(r).length:0}case"includes":{let[r,o]=_e(e,n,t,2);return typeof r=="string"?typeof o=="string"&&r.includes(o):Array.isArray(r)?r.includes(o):!1}case"literal":return Li(n);default:throw new Error(`Unknown computed expression operator: ${e}`)}},vt=(e,n={})=>{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 t=Object.entries(e);if(t.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[r,o]]=t;return Kl(r,o,n)},Cr=(e,n)=>{if(e===null||typeof e!="object"||P(e,"literal"))return e;if(P(e,"var"))return{literal:Ni(e.var,n)};if(P(e,"call"))throw new Error("Function calls are not supported in computed-variable conditions");return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Array.isArray(r)?r.map(o=>Cr(o,n)):Cr(r,n)]))},Jl=(e,n={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return be(e),Vn(Cr(e,n))},Mi=(e,n)=>{if(!ne(e))throw new Error(`${n} must be an object`);let t=P(e,"expr"),r=P(e,"value");if(t===r)throw new Error(`${n} must contain exactly one of expr or value`)},Er=(e,n,t)=>(Mi(e,n),P(e,"value")?Li(e.value):vt(e.expr,t)),Xl=(e,n={},t="unknown")=>{if(!ne(e))throw new Error(`Computed variable "${t}" computed must be an object`);let r=P(e,"expr"),o=P(e,"value");if(P(e,"branches")){if(r||o)throw new Error(`Computed variable "${t}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${t}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${t}" branches must not be empty`);if(!ne(e.default))throw new Error(`Computed variable "${t}" requires default`);for(let s=0;s<e.branches.length;s+=1){let l=e.branches[s];if(!ne(l))throw new Error(`Computed variable "${t}" branch ${s} must be an object`);if(!P(l,"when"))throw new Error(`Computed variable "${t}" branch ${s} requires when`);if(Jl(l.when,n))return Er(l,`Computed variable "${t}" branch ${s}`,n)}return Er(e.default,`Computed variable "${t}" default`,n)}if(r===o)throw new Error(`Computed variable "${t}" must contain exactly one of expr, value, or branches`);return Er(e,`Computed variable "${t}"`,n)},Vi=(e,n,t)=>{switch(n){case"number":if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(t)?"array":typeof t}`);return;case"boolean":if(typeof t!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(t)?"array":typeof t}`);return;case"string":if(typeof t!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(t)?"array":typeof t}`);return;case"object":if(t===null||typeof t!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof t}`);return;default:throw new Error(`Invalid variable type: ${n} for computed variable ${e}`)}},Ql=Object.freeze({add:2,sub:2,mul:2,div:2,mod:2,neg:1,round:1,floor:1,ceil:1,min:2,max:2,clamp:3,eq:2,neq:2,gt:2,gte:2,lt:2,lte:2,in:2,not:1,length:1,includes:2}),Zl=new Set(["and","or","all","any"]),eu=new Set(["add","sub","mul","div","mod","neg","round","floor","ceil","min","max","clamp","length"]),nu=new Set(["add","sub","mul","div","mod","neg","round","floor","ceil","min","max","clamp"]),tu=new Set(["eq","neq","gt","gte","lt","lte","in","and","or","all","any","not","includes"]),ru=new Set(["all","any","eq","neq","gt","gte","lt","lte","in","add","sub"]),ji=new WeakMap,Ri=e=>e===null?"null":Array.isArray(e)?"object":typeof e,Et=(e,n,t)=>{for(let r of Object.keys(e))if(!n.has(r))throw new Error(`${t} contains unsupported property "${r}"`)},ou=(e,n,t,r)=>{if(t!==void 0&&t!==n)throw new Error(`Computed variable "${e}" ${r} expected type ${n}, got ${t}`)},Fi=(e,{variableId:n,variableConfigs:t,dependencies:r,path:o})=>{let i=`Computed variable "${n}" ${o} var`,[s,l,...a]=Pi(e,i);if(s!=="variables"&&s!=="runtime")throw new Error(`${i} must reference variables.* or runtime.*, got ${JSON.stringify(e)}`);if(!l)throw new Error(`${i} must reference a concrete ${s} member, got ${JSON.stringify(e)}`);if(s==="runtime")return;if(!P(t,l))throw new Error(`Computed variable "${n}" ${o} references unknown variable "${l}"`);let c=t[l];return Se(c)&&r.add(l),a.length===0?c?.type:void 0},Ui=(e,{variableId:n,variableConfigs:t,dependencies:r,path:o})=>{if(e===null||typeof e!="object"){if(typeof e=="number"&&!Number.isFinite(e))throw new Error(`Computed variable "${n}" ${o} must use finite numeric literals`);return Ri(e)}if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let i=Object.entries(e);if(i.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[s,l]]=i;if(s==="var"){if(typeof l!="string"||l.trim()==="")throw new Error("Computed expression var requires a non-empty string path");return Fi(l,{variableId:n,variableConfigs:t,dependencies:r,path:o})}if(s==="literal"){if(typeof l=="number"&&!Number.isFinite(l))throw new Error(`Computed variable "${n}" ${o} must use finite numeric literals`);return Ri(l)}let a=Ql[s];if(a===void 0&&!Zl.has(s))throw new Error(`Unknown computed expression operator: ${s}`);a===void 0?Rr(s,l):Di(s,l,a);let c=l.map((u,d)=>Ui(u,{variableId:n,variableConfigs:t,dependencies:r,path:`${o}.${s}[${d}]`}));if(nu.has(s)&&c.forEach(u=>{if(u!==void 0&&u!=="number")throw new Error(`Computed expression operator "${s}" requires numeric operands`)}),eu.has(s))return"number";if(tu.has(s))return"boolean"},iu=(e,{variableId:n,variableConfigs:t,dependencies:r,path:o})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");try{be(e)}catch(s){throw new Error(`Computed variable "${n}" ${o} is invalid: ${s.message}`,{cause:s})}let i=(s,l)=>{if(s===null||typeof s!="object"||P(s,"literal"))return;if(P(s,"var")){Fi(s.var,{variableId:n,variableConfigs:t,dependencies:r,path:l});return}if(P(s,"call"))throw new Error(`Computed variable "${n}" ${l} function calls are not supported`);if(P(s,"not")){i(s.not,`${l}.not`);return}let a=Object.keys(s).find(c=>ru.has(c));s[a].forEach((c,u)=>{i(c,`${l}.${a}[${u}]`)})};i(e,o)},xr=(e,{variableId:n,variableConfig:t,variableConfigs:r,dependencies:o,path:i,allowedKeys:s=new Set(["expr","value"])})=>{if(Mi(e,`Computed variable "${n}" ${i}`),Et(e,s,i),P(e,"value")){Vi(n,t.type,e.value);return}let l=Ui(e.expr,{variableId:n,variableConfigs:r,dependencies:o,path:`${i}.expr`});ou(n,t.type,l,`${i}.expr`)},su=(e,n,t)=>{let r=n.computed;if(!ne(r))throw new Error(`Computed variable "${e}" computed must be an object`);let o=new Set,i=P(r,"expr"),s=P(r,"value");if(P(r,"branches")){if(Et(r,new Set(["branches","default"]),`Computed variable "${e}" computed`),i||s)throw new Error(`Computed variable "${e}" cannot combine branches with expr or value`);if(!Array.isArray(r.branches))throw new Error(`Computed variable "${e}" branches must be an array`);if(r.branches.length===0)throw new Error(`Computed variable "${e}" branches must not be empty`);if(!ne(r.default))throw new Error(`Computed variable "${e}" requires default`);return r.branches.forEach((a,c)=>{if(!ne(a))throw new Error(`Computed variable "${e}" branch ${c} must be an object`);if(Et(a,new Set(["when","expr","value"]),`Computed variable "${e}" branch ${c}`),!P(a,"when"))throw new Error(`Computed variable "${e}" branch ${c} requires when`);iu(a.when,{variableId:e,variableConfigs:t,dependencies:o,path:`computed.branches[${c}].when`}),xr(a,{variableId:e,variableConfig:n,variableConfigs:t,dependencies:o,path:`computed.branches[${c}]`,allowedKeys:new Set(["when","expr","value"])})}),xr(r.default,{variableId:e,variableConfig:n,variableConfigs:t,dependencies:o,path:"computed.default"}),o}if(Et(r,new Set(["expr","value"]),`Computed variable "${e}" computed`),i===s)throw new Error(`Computed variable "${e}" must contain exactly one of expr, value, or branches`);return xr(r,{variableId:e,variableConfig:n,variableConfigs:t,dependencies:o,path:"computed"}),o},an=(e={})=>{if(!ne(e))throw new Error("Variable configs must be an object");if(P(e,"__proto__"))throw new Error('Variable id "__proto__" is reserved');if(P(e,""))throw new Error("Variable ids must not be empty");let n=new Map;Object.entries(e).forEach(([i,s])=>{if(Se(s)){if(!ne(s))throw new Error(`Computed variable "${i}" must be an object`);if(!P(s,"type"))throw new Error(`Computed variable "${i}" requires type`);if(!P(s,"scope"))throw new Error(`Computed variable "${i}" requires scope`);if(P(s,"default"))throw new Error(`Computed variable "${i}" must not declare a top-level default`);if(Gn(s.scope,i),!["number","boolean","string","object"].includes(s.type))throw new Error(`Invalid variable type: ${s.type} for computed variable ${i}`);n.set(i,su(i,s,e))}});let t=new Set,r=[];n.forEach((i,s)=>{if(t.has(s))return;let l=[{variableId:s,dependencies:[...n.get(s)??[]],nextDependencyIndex:0}],a=new Map([[s,0]]);for(;l.length>0;){let c=l.at(-1);if(c.nextDependencyIndex>=c.dependencies.length){l.pop(),a.delete(c.variableId),t.add(c.variableId),r.push(c.variableId);continue}let u=c.dependencies[c.nextDependencyIndex];if(c.nextDependencyIndex+=1,t.has(u))continue;let d=a.get(u);if(d!==void 0){let f=[...l.slice(d).map(({variableId:p})=>p),u].join(" -> ");throw new Error(`Computed variable cycle detected: ${f}`)}a.set(u,l.length),l.push({variableId:u,dependencies:[...n.get(u)??[]],nextDependencyIndex:0})}});let o=Object.freeze({evaluationOrder:Object.freeze(r)});return ji.set(e,o),o},Bn=({variables:e={},runtime:n={},variableConfigs:t={},eager:r=!0}={})=>{let{evaluationOrder:o}=ji.get(t)??an(t),i=An(e,t),s=Object.entries(t).filter(([,b])=>Se(b)).map(([b])=>b),l=Object.create(null),a=[],c=new Map(o.map((b,I)=>[b,I])),u=-1,d=!1,f=b=>{if(P(l,b))return l[b];let I=t[b];if(!Se(I))return P(i,b)?i[b]:void 0;let E=a.indexOf(b);if(E>=0){let A=[...a.slice(E),b].join(" -> ");throw new Error(`Computed variable cycle detected: ${A}`)}a.push(b);try{let A=Xl(I.computed,h,b);return Vi(b,I.type,A),Sr(l,b,A),A}finally{a.pop()}},p=b=>{if(P(l,b))return l[b];let I=t[b];if(!Se(I))return P(i,b)?i[b]:void 0;let E=c.get(b);if(r&&!d&&E!==void 0&&E>u){d=!0;try{for(let A=u+1;A<=E;A+=1)f(o[A]),u=A}finally{d=!1}return l[b]}return f(b)},g=new Proxy({},{get:(b,I)=>{if(typeof I=="string")return p(I)},has:(b,I)=>typeof I=="string"&&(P(i,I)||s.includes(I)),ownKeys:()=>[...new Set([...Object.keys(i),...s])],getOwnPropertyDescriptor:(b,I)=>{if(!(typeof I!="string"||!P(i,I)&&!s.includes(I)))return{enumerable:!0,configurable:!0}}}),h={variables:g,runtime:n,resolveVariable:p};return r?(s.forEach(b=>{p(b)}),{...i,...l}):g},au=({variables:e={},runtime:n={},variableConfigs:t,projectData:r}={})=>{let o=t??r?.resources?.variables??{};return an(o),Bn({variables:e,runtime:n,variableConfigs:o,eager:!0})},Ct=e=>{let n={},t={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{if(Se(o))return;let i=Ml(o,r);o.scope==="context"?Sr(n,r,i):Sr(t,r,i)}),{contextVariableDefaultValues:n,globalVariablesDefaultValues:t}):{contextVariableDefaultValues:n,globalVariablesDefaultValues:t}},Gn=(e,n)=>{let t=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${n}`);if(!t.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${n}. Expected one of: ${t.join(", ")}`)},_t=(e,n,t)=>{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 ${t}`);if(!Object.values(r).flat().includes(n))throw new Error(`Unknown operation: ${n}`);if(!o.includes(n))throw new Error(`Operation "${n}" is not valid for variable "${t}" of type "${e}". Valid operations: ${o.join(", ")}`)},cu=2,Ci=12,Bi=(e=cu)=>{if(!Number.isInteger(e)||e<0||e>Ci)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${Ci}.`);return e},lu=(e,n)=>{let t=10**n;return Math.round((e+Number.EPSILON)*t)/t},xt=e=>typeof e=="number"&&Number.isFinite(e),Or=(e,n,t,r,o={})=>{if(e==="number"){if(n==="set"&&!xt(t))throw new Error(`Operation "set" requires value to be a number for variable "${r}".`);if(n==="multiply"&&!xt(t))throw new Error(`Operation "multiply" requires value to be a number for variable "${r}".`);if(n==="divide"&&!xt(t))throw new Error(`Operation "divide" requires value to be a number for variable "${r}".`);if(n==="divide"){if(t===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${r}".`);Bi(o.roundTo)}}},kt=(e,n,t,r={})=>{let o=(s,l,a)=>{let c=s??l;if(!xt(c))throw new Error(`Operation "${n}" requires ${a} to be a number.`);return c},i=s=>{let l=o(s,void 0,"value");if(l===0)throw new Error(`Operation "${n}" requires value to be a non-zero number.`);return l};switch(n){case"set":return t;case"multiply":return o(e,1,"current value")*o(t,void 0,"value");case"divide":return lu(o(e,0,"current value")/i(t),Bi(r.roundTo));case"increment":return o(e,0,"current value")+o(t,1,"value");case"decrement":return o(e,0,"current value")-o(t,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${n}`)}};var $r=(e,n="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let t=new Date(e),r=s=>String(s).padStart(2,"0"),o=String(t.getFullYear()),i={DD:r(t.getDate()),MM:r(t.getMonth()+1),MMM:Dl[t.getMonth()],YYYY:o,YY:o.slice(-2),HH:r(t.getHours()),mm:r(t.getMinutes()),ss:r(t.getSeconds())};return n.replace(/YYYY|MMM|YY|MM|DD|HH|mm|ss/g,s=>i[s])},uu=(e,n)=>{let t=i=>i?.ui,r=t(e),o=t(n);return JSON.stringify(r)===JSON.stringify(o)?null:r&&!o?{changeType:"delete",data:e}:o&&!r?{changeType:"add",data:n}:o&&r?{changeType:"update",data:n}:null},Mn=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,du=(e,n)=>{let t=e?.character?.sprite,r=n?.character?.sprite,o=Mn(t)?t:void 0,i=Mn(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},_i=e=>{if(e?.resourceId===void 0)return;let n={resourceId:e.resourceId};e.transformId!==void 0&&(n.transformId=e.transformId);for(let t of["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"])e[t]!==void 0&&(n[t]=e[t]);for(let t of["animationName","animationSpeed","loop"])e[t]!==void 0&&(n[t]=e[t]);return n},ki=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},Oi=(e,n)=>n&&!e?{changeType:"add",data:n}:e&&!n?{changeType:"delete",data:e}:e&&n&&JSON.stringify(e)!==JSON.stringify(n)?{changeType:"update",data:n}:null,fu=(e,n)=>{let t={},r=Oi(_i(e),_i(n)),o=Oi(ki(e),ki(n));return r&&(t.resource=r),o&&(t.color=o),Object.keys(t).length>0?t:null},Tr=(e={},n={})=>{let t={},r=["sfx","voice"],o=a=>{let c=e[a],u=n[a];u&&!c?t[a]={changeType:"add",data:u}:c&&!u?r.includes(a)||(t[a]={changeType:"delete",data:c}):c&&u&&JSON.stringify(c)!==JSON.stringify(u)&&(t[a]={changeType:"update",data:u})},i=fu(e.background,n.background);i&&(t.background=i),o("screen"),o("bgm"),o("voice");let s=uu(e.dialogue,n.dialogue);s&&(t.dialogue=s);let l=du(e.dialogue,n.dialogue);return l&&(t.dialogueSprite=l),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),t},Lr=(e={})=>{let n=structuredClone(e);n.background&&(n.background.animations?.playback?.continuity!=="persistent"&&delete n.background.animations,!n.background.resourceId&&!n.background.colorId&&delete n.background);let t=o=>{n[o]&&(delete n[o].animations,Object.keys(n[o]).length===0&&delete n[o])};t("layout"),t("choice"),t("form"),t("screen"),n.dialogue?.ui&&(delete n.dialogue.ui.animations,Object.keys(n.dialogue.ui).length===0&&delete n.dialogue.ui,Object.keys(n.dialogue).length===0&&delete n.dialogue),n.dialogue?.character?.sprite&&(delete n.dialogue.character.sprite.animations,Object.keys(n.dialogue.character.sprite).length===0&&delete n.dialogue.character.sprite,Object.keys(n.dialogue.character).length===0&&delete n.dialogue.character,Object.keys(n.dialogue).length===0&&delete n.dialogue);let r=(o,i)=>{let s=n[o]?.items;Array.isArray(s)&&(n[o].items=s.map(l=>{let a={...l};return delete a.animations,i(a)?a:null}).filter(Boolean),n[o].items.length===0&&delete n[o])};return r("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),r("visual",o=>o.resourceId||o.transformId),n},pu=(e,n)=>{if(!e||!n)return;let t=e;for(let r of n.split(".")){if(t==null||!(r in Object(t)))return;t=t[r]}return t},mu=(e,n)=>{if(typeof e!="string")return e;if(e==="_event"){if(n==null)throw new Error('Action template binding "_event" requires event context "_event".');return n}if(!e.startsWith("_event."))return e;if(n==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let t=e.slice(7),r=pu(n,t);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},gu={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"])},hu=(e,n)=>{let t=e[e.length-1];return t?gu[t]?.has(n)===!0:!1},_r=(e,n,t=[])=>Array.isArray(e)?e.map(r=>_r(r,n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,hu(t,r)?o:_r(o,n,[...t,r])])):typeof e=="string"?e==="_event"||e.startsWith("_event.")?mu(e,n._event):on(e,n):e,Pr=(e,n)=>{if(!n)return e;if(Object.prototype.hasOwnProperty.call(n,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');return _r(e,n)};var K=e=>structuredClone(ie(e)?Ue(e):e),U=(e,n)=>Object.prototype.hasOwnProperty.call(e,n),Gi=e=>e?.animations?.playback?.continuity==="persistent",j=(e,n)=>U(e??{},n)&&e[n]!==void 0,zn=(e,n)=>e?!n(e)&&e.animations?{animationsOnly:!0,state:{animations:K(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},yu=e=>j(e,"opacity")||j(e,"blur"),Ki=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Ji=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Nr=["animationName","animationSpeed","loop"],bu=e=>Ki.some(n=>j(e,n)),Xi=e=>e?.text&&j(e.text,"content")&&j(e.text,"textStyleId"),Qi=e=>j(e,"text"),Iu=(e,n)=>e.resourceId?!0:Xi(e)?!n?.text:!1,wu=(e,n)=>{let t={...K(e),...n};return n.text&&e.text&&(t.text={...K(e.text),...K(n.text)}),t},Au=(e,n)=>{if(Qi(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!Xi(e)&&!n?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},zi=e=>Ji.some(n=>j(e,n)),qi=e=>Nr.some(n=>j(e,n)),Eu=(e,n,{hasAuthoredTransformId:t=!1}={})=>{if(!n)return e;for(let r of Ji)!t&&!j(e,r)&&j(n,r)&&(e[r]=n[r]),U(e,r)&&e[r]===void 0&&delete e[r];return e},Zi=(e,n,t)=>{let r=e[t];return r?.id===n?.id?r:e.find(o=>o.id===n?.id)},xu=(e,n)=>{if(!n)return e;for(let t of Ki)!j(e,t)&&j(n,t)&&(e[t]=n[t]),U(e,t)&&e[t]===void 0&&delete e[t];return e},vu=(e,n)=>(n&&(!j(e,"opacity")&&j(n,"opacity")&&(e.opacity=n.opacity),!j(e,"blur")&&j(n,"blur")&&(e.blur=K(n.blur)),U(e,"opacity")&&e.opacity===void 0&&delete e.opacity,U(e,"blur")&&e.blur===void 0&&delete e.blur),e),es=(e,n,t=[],{hasPatchFn:r=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,l)=>{let a=Zi(t,s,l),c=n(s,a),u=yu(s),d=bu(s),f=r(s),p=U(s,"animations"),g=K(s);return!c&&(u||d||f)&&a&&(g=o?o(a,g):{...K(a),...g},p||delete g.animations),vu(xu(g,a),a)}).filter(s=>n(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},Su=e=>{if(e){if(e.character&&U(e.character,"name"))return e.character.name;if(U(e,"characterName"))return e.characterName}},ns=e=>!!e?.character&&U(e.character,"sprite"),Ru=e=>{let n={},t=!1,r=Su(e);return r!==void 0&&(n.name=r,t=!0),ns(e)&&(n.sprite=K(e.character.sprite),t=!0),t?n:void 0},Yi=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Hi=({dialogueState:e,dialogueAction:n,persistCharacter:t})=>U(n,"persistSprite")?n.persistSprite===!0:U(e,"persistSprite")?e.persistSprite===!0:t&&!U(n,"characterId"),Wi=({previousCharacter:e,characterFields:n,hasCharacterId:t,persistCharacter:r,persistSprite:o,hasExplicitPersistSprite:i,isAppendingAdvDialogueContent:s})=>{let l={},a=e??{},c=n??{},u=s&&!t,d=u&&!i;return U(c,"name")?l.name=c.name:(r&&!t||u)&&U(a,"name")&&(l.name=K(a.name)),U(c,"sprite")?l.sprite=K(c.sprite):(o||d)&&U(a,"sprite")&&(l.sprite=K(a.sprite)),Object.keys(l).length>0?l:void 0},Cu=({dialogueState:e,content:n,append:t=!1})=>{if(!t||!Array.isArray(n)){e.content=n,delete e.initialRevealedContent;return}let r=Array.isArray(e.content)?e.content:[];r.length>0?e.initialRevealedContent=r.map(o=>K(o)):delete e.initialRevealedContent,e.content=[...r,...n]},_u=()=>({}),ku=(e,n)=>{if(!n.screen)return;let t=j(n.screen,"opacity"),r=j(n.screen,"blur"),o=U(n.screen,"animations");if(!t&&!r){o||delete e.screen;return}let i=e.screen,s={};if(t?s.opacity=n.screen.opacity:j(i,"opacity")&&(s.opacity=i.opacity),r?s.blur=K(n.screen.blur):j(i,"blur")&&(s.blur=K(i.blur)),U(s,"opacity")&&s.opacity===void 0&&delete s.opacity,U(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},Ou=(e,n)=>{if(n.background){let t=j(n.background,"resourceId"),r=j(n.background,"colorId"),o=j(n.background,"opacity"),i=j(n.background,"blur"),s=j(n.background,"transformId"),l=zi(n.background),a=qi(n.background),{animationsOnly:c,state:u}=zn(n.background,p=>j(p,"resourceId")||j(p,"colorId")||j(p,"opacity")||j(p,"blur")||j(p,"transformId")||zi(p)||qi(p));if(c){e.background=e.background?{...K(e.background),...u}:u;return}if(!t&&!r&&!o&&!i&&!s&&!l&&!a){delete e.background;return}let d=e.background,f=K(n.background);if(!t&&d?.resourceId){f.resourceId=d.resourceId,!U(f,"transformId")&&d.transformId&&(f.transformId=d.transformId);for(let p of Nr)!j(f,p)&&j(d,p)&&(f[p]=d[p])}Eu(f,d,{hasAuthoredTransformId:s}),!r&&d?.colorId&&(f.colorId=d.colorId),!o&&j(d,"opacity")&&(f.opacity=d.opacity),!i&&j(d,"blur")&&(f.blur=K(d.blur)),U(f,"resourceId")&&f.resourceId===void 0&&delete f.resourceId,U(f,"colorId")&&f.colorId===void 0&&delete f.colorId,U(f,"animations")&&f.animations===void 0&&delete f.animations,U(f,"transformId")&&f.transformId===void 0&&delete f.transformId,U(f,"opacity")&&f.opacity===void 0&&delete f.opacity,U(f,"blur")&&f.blur===void 0&&delete f.blur;for(let p of Nr)U(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&&!U(f,"animations")&&Gi(d)&&(f.animations=K(d.animations)),e.background=f}else e.background?.animations&&!Gi(e.background)&&(e.background.animations={})},$u=(e,n)=>{if(!n.dialogue){if(e.dialogue&&(Yi(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=Hi({dialogueState:e.dialogue,dialogueAction:{},persistCharacter:u});u||delete e.dialogue.characterId,e.dialogue.character=Wi({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 t=e.dialogue.mode;if(n.dialogue.ui){let{animationsOnly:u,state:d}=zn(n.dialogue.ui,f=>!!f.resourceId);u?e.dialogue.ui={...e.dialogue.ui,...d}:e.dialogue.ui={...n.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});n.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),n.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let r=n.dialogue.append===!0&&t!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(n.dialogue.content);n.dialogue.content!==void 0&&Cu({dialogueState:e.dialogue,content:n.dialogue.content,append:r}),U(n.dialogue,"textSpeed")?e.dialogue.textSpeed=n.dialogue.textSpeed:delete e.dialogue.textSpeed;let o=U(n.dialogue,"persistCharacter")?n.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=Hi({dialogueState:e.dialogue,dialogueAction:n.dialogue,persistCharacter:o});U(n.dialogue,"persistSprite")&&(e.dialogue.persistSprite=i);let s=U(n.dialogue,"characterId"),l=Ru(n.dialogue),a=ns(n.dialogue);s?n.dialogue.characterId?e.dialogue.characterId=n.dialogue.characterId:delete e.dialogue.characterId:!o&&!r&&delete e.dialogue.characterId;let c=Wi({previousCharacter:e.dialogue.character,characterFields:l,hasCharacterId:s,persistCharacter:o,persistSprite:i,hasExplicitPersistSprite:U(n.dialogue,"persistSprite"),isAppendingAdvDialogueContent:r});if(c?e.dialogue.character=c:delete e.dialogue.character,a||Yi(e.dialogue),n.dialogue.clear){delete e.dialogue;return}if(n.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&n.dialogue.content!==void 0){let u={content:n.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.textSpeed!==void 0&&(u.textSpeed=e.dialogue.textSpeed),e.dialogue.character&&(u.character=K(e.dialogue.character)),e.dialogue.lines.push(u)}},Tu=(e,n)=>{if(n.sfx){let t=Array.isArray(n.sfx.items)&&n.sfx.items.length>0,r=Array.isArray(n.sfx.channels)&&n.sfx.channels.length>0;if(!t&&!r){delete e.sfx;return}e.sfx=K(n.sfx)}else e.sfx&&delete e.sfx},Lu=(e,n)=>{if(n.bgm){let t=Array.isArray(n.bgm.sounds);if(!n.bgm.resourceId&&!t||t&&n.bgm.sounds.length===0){e.bgm=void 0;return}e.bgm=K(n.bgm),n.bgm.resourceId&&(e.bgm.loop=n.bgm.loop??!0)}},Pu=(e,n)=>{if(n.visual){let t=e.visual?.items||[];n.visual.items?.forEach((i,s)=>{Au(i,Zi(t,i,s))});let{hasValidItems:r,processedItems:o}=es(n.visual.items,Iu,t,{hasPatchFn:Qi,mergeItemFn:wu});r?e.visual={items:o}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(t=>t.animations?{...t,animations:{}}:t))},Nu=(e,n)=>{if(!n.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:t,processedItems:r}=es(n.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);t?e.character={items:r}:delete e.character},Du=(e,n)=>{n.animation?e.animation=n.animation:e.animation&&delete e.animation},Mu=(e,n)=>{if(n.layout){let{animationsOnly:t,state:r}=zn(n.layout,o=>!!o.resourceId);if(t){e.layout=r;return}if(!n.layout.resourceId){delete e.layout;return}e.layout=n.layout}else e.layout&&delete e.layout},Vu=(e,n)=>{if(n.choice){let{animationsOnly:t,state:r}=zn(n.choice,o=>!!o.resourceId);if(t){e.choice={...e.choice,...r};return}if(!n.choice.resourceId){delete e.choice;return}e.choice=n.choice}else e.choice&&delete e.choice},ju=(e,n)=>{if(n.form){let{animationsOnly:t,state:r}=zn(n.form,o=>!!o.resourceId);if(t){e.form={...e.form,...r};return}if(!n.form.resourceId){delete e.form;return}e.form=K(n.form)}else e.form&&delete e.form},Fu=(e,n)=>{if(n.control){if(!n.control.resourceId){delete e.control;return}e.control=n.control}},Uu=(e,n)=>{if(n.voice){let t=Array.isArray(n.voice.sounds);if(!n.voice.resourceId&&!t||t&&n.voice.sounds.length===0){delete e.voice;return}e.voice=K(n.voice)}else e.voice&&delete e.voice},Bu=(e,n)=>{n.cleanAll&&Object.keys(e).forEach(t=>{delete e[t]})},cn=e=>St(_u,[Bu,ku,Ou,Tu,Lu,Pu,$u,Nu,Du,Mu,Vu,ju,Fu,Uu])(e);var En=(e,n)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let t=on(e,n);return t&&typeof t=="object"?e:t};var Gu=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"}}),ln=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}),qn=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),ts=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"}),Dr=Object.freeze(["dialogueTextSpeed","autoForwardDelay","autoForwardSpeed","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Mr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),zu=(e,n)=>{if(n.startsWith("global.")){let t=n.slice(7);return e?.global?.[t]}if(n.startsWith("context.runtime.")){let t=n.slice(16),r=Array.isArray(e?.contexts)?e.contexts:[];return r[r.length-1]?.runtime?.[t]}},un=e=>Object.fromEntries(Object.entries(Gu).map(([n,t])=>{let r=zu(e,t.source),o=r!==void 0?r:ln[n]??qn[n];return[n,o]})),Ye=(e,n)=>un(e)[n],rs=(e={})=>Object.fromEntries(Dr.map(n=>[n,e[n]??ln[n]]));var xn=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}),Ne=Object.freeze({BEHIND_BACKGROUND:xn.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:xn.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:xn.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:xn.VISUAL_BEHIND_CHOICE,FOREGROUND:xn.VISUAL_FOREGROUND}),Vr=Ne.BEHIND_DIALOGUE,jr=Object.freeze(Object.values(Ne).sort((e,n)=>e-n));var qu={__arrayOrEmpty:e=>Array.isArray(e)?e:[],objectValues:e=>Object.entries(e).map(([n,t])=>({id:n,...t})),formatDate:$r},Yu=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+?)(?::)?$/,Yn=e=>Array.isArray(e)?e.map(n=>{if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).length!==1)return Yn(n);let[t]=Object.keys(n),r=Yu.exec(t);if(!r)return Yn(n);let[,o,i,s]=r,l=`$for ${o}${i?`, ${i}`:""} in __arrayOrEmpty(${s.trim()})`,a=Array.isArray(n[t])?n[t]:[];return{[l]:Yn(a)}}):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).map(([n,t])=>[n,Yn(t)])),Me=(e,n)=>{let t={functions:qu};return on(Yn(e),n,t)},to=({animationType:e,animationId:n,animationPath:t})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${t}] Animation "${n}" has unsupported type "${e}". Use "update" or "transition".`)},Hu=({id:e,targetId:n,animation:t,playback:r,animationPath:o="animation"})=>{let i=structuredClone(t);if(to({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=n,r!==void 0){let s=Xu(r,`${o}.playback`);if(s!==void 0){let l=s.loop===!0?Is(i):null;if(s.loop===!0&&i.type!=="update")throw new Error(`[${o}.playback] playback.loop is only supported for type "update".`);if(s.loop===!0&&i.complete!==void 0)throw new Error(`[${o}.playback] animation.complete is not allowed when playback.loop is true because a loop never completes.`);if(s.loop===!0&&(!Number.isFinite(l)||l<=0))throw new Error(`[${o}.playback] playback.loop requires an animation with a finite duration greater than 0.`);i.playback=s}}return i},Wu=(e,{animationId:n="animation",animationPath:t="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return to({animationType:e.type,animationId:n,animationPath:t}),e.type},Ku=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Ju=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Xu=(e,n="animation.playback")=>{if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`[${n}] playback must be an object.`);if(e.continuity!==void 0&&e.continuity!=="render"&&e.continuity!=="persistent")throw new Error(`[${n}] 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(`[${n}] playback.speed must be a finite number greater than 0.`);if(e.loop!==void 0&&typeof e.loop!="boolean")throw new Error(`[${n}] playback.loop must be a boolean.`);let t={};return e.continuity!==void 0&&(t.continuity=e.continuity),e.speed!==void 0&&e.speed!==1&&(t.speed=e.speed),e.loop===!0&&(t.loop=!0),Object.keys(t).length>0?t:void 0},Qu=e=>{let n=e?.playback?.speed;return typeof n=="number"&&Number.isFinite(n)&&n>0?n:1},dn=(e,n)=>Object.prototype.hasOwnProperty.call(e,n),hs=e=>e?.playback?.continuity==="persistent",Hr=e=>Array.isArray(e)?e.map(Hr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((n,t)=>(n[t]=Hr(e[t]),n),{}),Lt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let n=structuredClone(e);return n.playback&&(delete n.playback.continuity,n.playback.speed===1&&delete n.playback.speed,Object.keys(n.playback).length===0&&delete n.playback),JSON.stringify(Hr(n))},ys=(e=[])=>e.filter(n=>hs(n)).map(n=>structuredClone(n)),bs=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((n,t)=>{let r=typeof t?.duration=="number"&&Number.isFinite(t.duration)?t.duration:0;return n+r},0):0,Fr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((n,t)=>Math.max(n,bs(t)),0),Is=e=>Math.max(Fr(e?.tween),Fr(e?.prev?.tween),Fr(e?.next?.tween),bs(e?.mask?.progress)),ws=e=>!e||typeof e!="object"||Array.isArray(e)?0:e.playback?.loop===!0?Number.POSITIVE_INFINITY:Is(e)/Qu(e),Zu=e=>e.some(n=>n?.playback?.loop===!0),os=({animationInstances:e,activePersistentAnimations:n})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(n)||n.length===0)return!1;let t=new Set(n.map(Lt).filter(Boolean));return e.some(r=>{if(!hs(r))return!1;let o=Lt(r);return o?t.has(o):!1})},ke=({animationInstances:e,isLineCompleted:n,skipTransitionsAndAnimations:t,activePersistentAnimations:r,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||t?!1:Zu(e)||i&&!n||os({animationInstances:e,activePersistentAnimations:r})?!0:i?!1:os({animationInstances:e,activePersistentAnimations:o}),ed=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(n=>e[n]!==void 0),nd=(e,n)=>{if(ed(e))throw new Error(`[${n}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},td=({resources:e,animationId:n,playback:t,instanceId:r,targetId:o,animationPath:i="animation"})=>{if(!n||!o)return!1;let s=e?.animations?.[n];return s?Hu({id:r,targetId:o,animation:s,playback:t,animationPath:i}):null},rd=(e,{defaultTargetId:n,defaultId:t,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return to({animationType:o.type,animationId:o.id??t,animationPath:r}),o.id??=t,o.targetId??=n,o},ro=({animations:e,transitions:n,defaultTargetId:t,idPrefix:r,animationPathPrefix:o=r})=>{n.forEach((i,s)=>{e.push(rd(i,{defaultTargetId:t,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Wr=(e,n)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(t=>t===null||typeof t!="object"||Array.isArray(t)))throw new Error(`${n} must be an array of objects`);return e},od=({content:e,path:n,variables:t})=>Wr(e,n).reduce((r,o)=>{let i=En(o.text,{variables:t});return r+`${i??""}`.length},0),is=(e=[])=>{let n=new Map;for(let t of e)t?.id&&n.set(t.id,(n.get(t.id)??0)+1);return new Set(Array.from(n.entries()).filter(([,t])=>t>1).map(([t])=>t))},Ot=(e,n=0,t=new Set)=>{if(!t.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}-${n}-${r.join("-")}`},Hn=(e,n)=>{if(!n.transformId)throw new Error(`Visual item "${n.id}" requires transformId`);let t=e.transforms?.[n.transformId];if(!t)throw new Error(`Transform "${n.transformId}" not found for visual item "${n.id}"`);return t},id=(e,n={})=>{if(!n?.transformId)return;let t=e.transforms?.[n.transformId];if(!t)throw new Error(`Transform "${n.transformId}" not found for background`);return t},sd=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],ad=(e={})=>sd.some(n=>dn(e,n)),As=(e={},n)=>{if(n){if(e.images?.[n])return"sprite";if(e.videos?.[n])return"video";if(e.spritesheets?.[n])return"spritesheet-animation";if(e.layouts?.[n])return"container"}},Tt=({resourceId:e,kind:n})=>{if(e)return n?`bg-cg-background-${n}`:`bg-cg-${e}`},cd=(e={})=>e.textStyles||{},ld=(e={})=>e.images||{},ud=.5,dd=(e={},n,t)=>{if(n){if(!e.animations?.[n])throw new Error(`Animation '${n}' not found in spritesheet resource '${t}'`);return n}return Object.keys(e.animations??{})[0]},Es=({id:e,resourceId:n,spritesheet:t,animationName:r,animationSpeed:o,loop:i,transform:s={}}={})=>{let l=dd(t,r,n),a=l?t.animations?.[l]:void 0;if(!a){console.warn(`Spritesheet animation not found: ${n}`);return}return{id:e,type:"spritesheet-animation",...s,width:t.width,height:t.height,src:t.fileId,atlas:t.jsonData,playback:{frames:a.frames,animationSpeed:o??a.animationSpeed??ud,loop:i??a.loop??!0}}},xs=({id:e,item:n,resources:t={}}={})=>{let r=t.images?.[n.resourceId];if(r)return{type:"sprite",id:e,src:r.fileId,width:r.width,height:r.height,x:0,y:0};let o=t.spritesheets?.[n.resourceId];if(o)return Es({id:e,resourceId:n.resourceId,spritesheet:o,animationName:n.animationName,animationSpeed:n.animationSpeed,loop:n.loop,transform:{x:0,y:0}});console.warn(`Character sprite resource not found: ${n.resourceId}`)},fd=(e={})=>e.colors||{},pd=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Kn=(e,n)=>e==="root"?`${n}`:`${e}.${n}`,Rn=(e,n,t)=>{if(typeof e!="string"||e.length===0)throw new Error(`${t} at "${n}" must resolve to a non-empty string`)},Ur=(e,n,t)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${n} for text style "${t}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${n} for text style "${t}" must be a number between 0 and 1`);return e},Br=(e,n,t,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.${n} for text style "${t}" must be ${i}`)}return e},Dt=(e,n)=>{if(typeof e!="string"||!pd.test(e))throw new Error(`${n} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(t=>t.repeat(2)).join("")}`:e},ss=(e,n,t)=>{let r=Dt(e,t);if(n===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}, ${n})`},md=(e={},n)=>{let t=cd(e)?.[n];if(!t)throw new Error(`Text style "${n}" not found`);let o=(Array.isArray(t.fontId)?t.fontId:[t.fontId]).map(a=>{let c=e.fonts?.[a];if(!c)throw new Error(`Font "${a}" not found for text style "${n}"`);return c.fileId}),i=e.colors?.[t.colorId];if(!i)throw new Error(`Color "${t.colorId}" not found for text style "${n}"`);let s=Ur(t.colorAlpha,"colorAlpha",n),l={fontFamily:Array.isArray(t.fontId)?o.join(", "):o[0],fontSize:t.fontSize??16,fontWeight:t.fontWeight??"400",fontStyle:t.fontStyle??"normal",lineHeight:t.lineHeight??1.2,fill:ss(i.hex,s,`Color "${t.colorId}" for text style "${n}"`)};if(t.align!==void 0&&(l.align=t.align),t.wordWrap!==void 0&&(l.wordWrap=t.wordWrap),t.breakWords!==void 0&&(l.breakWords=t.breakWords),t.wordWrapWidth!==void 0&&(l.wordWrapWidth=t.wordWrapWidth),t.strokeColorId){let a=e.colors?.[t.strokeColorId];if(!a)throw new Error(`Stroke color "${t.strokeColorId}" not found for text style "${n}"`);let c=Ur(t.strokeAlpha,"strokeAlpha",n);l.strokeColor=ss(a.hex,c,`Stroke color "${t.strokeColorId}" for text style "${n}"`)}else if(t.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${n}" requires strokeColorId`);if(t.strokeWidth!==void 0&&(l.strokeWidth=t.strokeWidth),t.shadow!==void 0){let a=e.colors?.[t.shadow.colorId];if(!a)throw new Error(`Shadow color "${t.shadow.colorId}" not found for text style "${n}"`);l.shadow={color:Dt(a.hex,`Shadow color "${t.shadow.colorId}" for text style "${n}"`),alpha:Ur(t.shadow.alpha,"shadow.alpha",n),blur:Br(t.shadow.blur,"blur",n,0,{minimum:0}),offsetX:Br(t.shadow.offsetX,"offsetX",n,2),offsetY:Br(t.shadow.offsetY,"offsetY",n,2)}}return l},Kr=(e,n={},t="root")=>{if(Array.isArray(e))return e.map((o,i)=>Kr(o,n,`${t}[${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 "${t}". Use textStyleId instead`);let r={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(r[o]=Kr(i,n,Kn(t,o)));return e.textStyleId!==void 0&&(Rn(e.textStyleId,t,"textStyleId"),r.textStyle=md(n,e.textStyleId)),r},oo=(e={},n)=>{let t=fd(e)?.[n];if(!t)throw new Error(`Color "${n}" not found`);return Dt(t.hex,`Color "${n}"`)},vs=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Gr=(e,n,t)=>{let r=e?.[n];if(!(!r||typeof r!="object"||Array.isArray(r))&&Object.prototype.hasOwnProperty.call(r,"fill"))throw new Error(`Inline ${n}.fill is not allowed in rect layout elements at "${t}". Use ${vs(`${n}.fill`)} instead`)},gd=(e,n={},t="root")=>{if(Array.isArray(e))return e.map((o,i)=>Jn(o,n,`${t}[${i}]`));if(!e||typeof e!="object")return e;let r={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(r[o]=Jn(i,n,Kn(t,o)));return e.colorId!==void 0&&(Rn(e.colorId,t,"colorId"),r.fill=oo(n,e.colorId)),r},Jn=(e,n={},t="root")=>{if(Array.isArray(e))return e.map((o,i)=>Jn(o,n,`${t}[${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 "${t}". Use ${vs("fill")} instead`);Gr(e,"hover",t),Gr(e,"click",t),Gr(e,"rightClick",t)}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]=gd(i,n,Kn(t,o));continue}r[o]=Jn(i,n,Kn(t,o))}return e.type==="rect"&&e.colorId!==void 0&&(Rn(e.colorId,t,"colorId"),r.fill=oo(n,e.colorId)),r},zr=(e={},n)=>{let t=ld(e)?.[n];return t||null},Ss=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",as=(e,n,t,r)=>{let o=e?.[n];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,r))throw new Error(`Inline ${n}.${r} is not allowed in sprite layout elements at "${t}". Use ${Ss(`${n}.${r}`)} instead`)},cs=(e,n,t)=>{let r=e[n];e[n]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:t}},Jr=(e,n={},t="root")=>{if(Array.isArray(e))return e.map((o,i)=>Jr(o,n,`${t}[${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 "${t}". Use ${Ss(o)} instead`);as(e,"hover",t,"src"),as(e,"click",t,"src")}let r={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(r[o]=Jr(i,n,Kn(t,o)));if(e.type==="sprite"&&e.imageId!==void 0){Rn(e.imageId,t,"imageId");let o=zr(n,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&&(Rn(e.hoverImageId,t,"hoverImageId"),cs(r,"hover",zr(n,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(Rn(e.clickImageId,t,"clickImageId"),cs(r,"click",zr(n,e.clickImageId)?.fileId??e.clickImageId)),r},io=(e,n={},t="root")=>Jr(Jn(Kr(e,n,t),n,t),n,t),Ve=io,fn=(e=[])=>e.find(n=>n.id==="story"),hd="#000000",Xr="bg-cg-background-color",yd=({resources:e={},background:n={},screen:t})=>n?.colorId===void 0?Dt(t?.backgroundColor??hd,"screen.backgroundColor"):oo(e,n.colorId),Rs=(e={})=>{if(dn(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},bd=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},ls=(e={},{includeDefaultAlpha:n=!1}={})=>{let t=Rs(e),r=bd(e),o={};return(n||t!==void 0)&&(o.alpha=t??1),r&&(o.blur=r),o},Id=(e={})=>{if(dn(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},wd=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Cs=(e={})=>{let n=Id(e),t=wd(e),r={};return n!==void 0&&(r.alpha=n),t&&(r.blur=t),r},Sn=(e={})=>Cs(e),De=(e={},n={})=>{let t={x:n.x??e.x,y:n.y??e.y,anchorX:n.anchorX??e.anchorX,anchorY:n.anchorY??e.anchorY,rotation:n.rotation??e.rotation,scaleX:n.scaleX??e.scaleX,scaleY:n.scaleY??e.scaleY},r=n.originX??e.originX,o=n.originY??e.originY;return r!==void 0&&(t.originX=r),o!==void 0&&(t.originY=o),t},Ad=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],so=(e={})=>e.text&&dn(e.text,"content")&&dn(e.text,"textStyleId"),us=(e={})=>{if(e.resourceId)return e.resourceId;if(so(e))return"text"},ds=(e,n={})=>typeof e=="string"?n.images?.[e]?.fileId??e:!e||typeof e!="object"||Array.isArray(e)?e:e.imageId?n.images?.[e.imageId]?.fileId??e.imageId:Array.isArray(e.items)?{...e,items:e.items.map(t=>{if(typeof t=="string")return n.images?.[t]?.fileId??t;if(!t||typeof t!="object"||Array.isArray(t))return t;if(t.imageId){let{imageId:r,...o}=t;return{...o,src:n.images?.[r]?.fileId??r}}return typeof t.src=="string"?{...t,src:n.images?.[t.src]?.fileId??t.src}:t})}:e,Ed=({item:e,particle:n,resources:t})=>{let r=Hn(t,e),o=structuredClone(n),i=o.modules?.appearance?.texture;i!==void 0&&(o.modules.appearance.texture=ds(i,t)),o.texture!==void 0&&(o.texture=ds(o.texture,t));let s={id:`visual-${e.id}`,type:"container",children:[{...o,id:`visual-${e.id}-particles`,type:"particles",x:0,y:0}],...De(r,e)};return Object.assign(s,Sn(e)),s},xd=e=>{if(e.text){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!so(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let n of Ad)if(dn(e.text,n))throw new Error(`Visual item "${e.id}" text.${n} is reserved for the visual item`)}},vd=({resources:e,background:n,screen:t={width:1920,height:1080},includeOpacity:r=!1})=>{let o={id:Xr,type:"rect",x:0,y:0,width:t?.width??1920,height:t?.height??1080,fill:yd({resources:e,background:n,screen:t})};if(r){let i=Rs(n);i!==void 0&&(o.alpha=i)}return o},Sd=(e={},n)=>n?!!(e.images?.[n]||e.videos?.[n]||e.spritesheets?.[n]||e.layouts?.[n]):!1,fs=({resources:e={},resourceId:n,colorId:t})=>{let r=As(e,n);return n&&(r||t===void 0)?{resourceId:n,targetId:Tt({resourceId:n,kind:r})}:t!==void 0?{resourceId:Xr,targetId:Xr}:{resourceId:void 0,targetId:void 0}},_s=100,He=_s,Rd="channel:bgm",Cd="channel:music-room",_d="music-room:player",kd="channel:voice",Od="default",$d=e=>String(e).replaceAll("%","%25").replaceAll(":","%3A"),Wn=(...e)=>e.map($d).join(":"),Pt=(e,n,t)=>{let r=new Set;e.forEach(({id:o})=>{if(r.has(o)){let i=t?` in ${t}`:"";throw new Error(`Duplicate ${n} id "${o}"${i}.`)}r.add(o)})},Td=(e,n)=>e*n/_s,ks=(e={},n)=>e?.[n]??ln[n],Mt=(e={},n,t=He)=>Td(t,ks(e,n)),Vt=({id:e,volume:n,muted:t,pan:r,loop:o,playback:i,interruption:s,children:l,runtime:a})=>{let c={id:e,type:"audio-channel",volume:n,muted:!!a?.muteAll||(t??!1),pan:r??0,children:l};return o!==void 0&&(c.loop=o),i!==void 0&&(c.playback=structuredClone(i)),s!==void 0&&(c.interruption=s),c},$t=(e,n,t,r)=>e[t]!==void 0?e[t]:n[t]!==void 0?n[t]:r,Ld=["muted","pan","playbackRate","startAt","endAt"],jt=({id:e,sound:n,resource:t,defaultLoop:r=!1})=>{let o={id:e,type:"sound",src:t.fileId,loop:$t(n,t,"loop",r),volume:$t(n,t,"volume",He),startDelayMs:$t(n,t,"startDelayMs",0)};Ld.forEach(s=>{let l=$t(n,t,s,void 0);l!==void 0&&(o[s]=l)}),n.playback!==void 0&&(o.playback=structuredClone(n.playback));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},Re=({variables:e,imageGallery:n,musicRoom:t,sceneReplay:r,runtime:o,saveSlots:i=[],dialogueState:s,includeInactiveAdvDialogue:l=!1,isLineCompleted:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,confirmDialog:g,form:h,historyDialogue:b=[],characters:I={},dialogueUIHidden:E,skipOnlyViewedLines:A,skipTransitionsAndAnimations:$}={})=>{let B={dialogueTextSpeed:o?.dialogueTextSpeed??50,autoForwardDelay:o?.autoForwardDelay??1e3,autoForwardSpeed:o?.autoForwardSpeed??1,skipUnseenText:o?.skipUnseenText??!1,skipTransitionsAndAnimations:o?.skipTransitionsAndAnimations??!1,soundVolume:o?.soundVolume??50,musicVolume:o?.musicVolume??50,muteAll:o?.muteAll??!1,saveLoadPagination:o?.saveLoadPagination??1,menuPage:o?.menuPage??"",menuEntryPoint:o?.menuEntryPoint??"",autoMode:o?.autoMode??c??!1,skipMode:o?.skipMode??u??!1,dialogueUIHidden:o?.dialogueUIHidden??E??!1,isLineCompleted:o?.isLineCompleted??a??!1},L=Vd({dialogueState:s,includeInactiveAdvDialogue:l,characters:I,variables:e,runtime:B}),T={variables:e,imageGallery:n,musicRoom:t,sceneReplay:r,runtime:B,saveSlots:i,isChoiceVisible:d,isFormVisible:f,canRollback:p,confirmDialog:g,form:h,historyDialogue:b,characters:I};return L&&(T.dialogue=L,T.dialogueLines=L.lines),T},ps=100,Nt=(e,n)=>{if(Array.isArray(e))return e.map(r=>Nt(r,n));if(!e||typeof e!="object")return e;let t={...e};return Object.keys(t).forEach(r=>{t[r]=Nt(t[r],n)}),t.type==="text-revealing"?n(t):t},Pd=e=>Nt(e,n=>({...n,revealEffect:"none"})),Nd=e=>Nt(e,n=>{let t=Number(n.speed??n.displaySpeed),r=Number.isFinite(t)?Math.max(t,ps):ps;return{...n,speed:r,...Object.prototype.hasOwnProperty.call(n,"displaySpeed")?{displaySpeed:r}:{}}}),We=(e,{isLineCompleted:n=!1,skipMode:t=!1,skipTransitionsAndAnimations:r=!1}={})=>n||r?Pd(e):t?Nd(e):e,Os=({id:e,screen:n={width:1920,height:1080}})=>({id:e,type:"rect",fill:"transparent",width:n.width,height:n.height,x:0,y:0,click:{payload:{actions:{}}}}),Qr=e=>{if(Array.isArray(e))return e.map(Qr);if(!e||typeof e!="object")return e;let n={};for(let[i,s]of Object.entries(e))n[i]=Qr(s);let t=n.click?.payload;if(!t||typeof t!="object"||Array.isArray(t))return n;let r=t.actions,o=r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"nextLine")?{...r.nextLine,bypassChoice:!0}:void 0;return{...n,click:{...n.click,payload:{...t,bypassChoice:!0,...o?{actions:{...r,nextLine:o}}:{}}}}},Dd=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),ms="submit",qr=(e,n,t={})=>{let r=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},o=r.actions&&typeof r.actions=="object"?r.actions:{},i=t.replaceActions===!0?n:{...o,...n};return{...e||{},payload:{...r,actions:i}}},Zr=(e,n,t={})=>{if(Array.isArray(e))return e.map(c=>Zr(c,n,t));if(!e||typeof e!="object")return e;let r=typeof e.type=="string",o=r&&e.formRole===ms,i=r&&t.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},l={};for(let[c,u]of Object.entries(e))l[c]=Zr(u,n,c==="children"?s:{});let a=l;if(a.type==="input"&&typeof a.field=="string"){let c=n?.fields?.[a.field];if(c){let u={updateFormField:{formKey:n.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:qr(a.change,u),submit:qr(a.submit,n.submitActions)}}}return a.formRole===ms||i?{...a,click:qr(a.click,n.submitActions,{replaceActions:!0})}:a},eo=(e,n)=>{if(Array.isArray(e))return e.map(r=>eo(r,n));if(!e||typeof e!="object")return e;let t={};for(let[r,o]of Object.entries(e))t[r]=eo(o,n);for(let r of Dd){let o=t[r]?.payload;!o||typeof o!="object"||Array.isArray(o)||(t[r]={...t[r],payload:{...o,_interactionSource:"form"}})}return t},no=({characterId:e,character:n,characterName:t,characters:r={},variables:o={}}={})=>{let i=e?r?.[e]:void 0,s=Rt({characterId:e,character:n,characterName:t,characters:r,variables:o});return{...i||{},...n||{},name:s}},$s=(e=[],n={},t={})=>e.map(r=>{let o=no({characterId:r.characterId,character:r.character,characterName:r.characterName,characters:n,variables:t}),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}}),Md=e=>!(!e||e.mode==="adv"&&e.content===void 0),Vd=({dialogueState:e,includeInactiveAdvDialogue:n=!1,characters:t={},variables:r,runtime:o}={})=>{if(!n&&!Md(e))return;let i=e.content===void 0?[{text:""}]:Wr(e.content,"dialogue.content"),s=e.content===void 0?0:od({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:r}),l=o?.dialogueTextSpeed??ln.dialogueTextSpeed,a=e.textSpeed??l,c=(e.lines||[]).map((d,f)=>{let p=Wr(d.content,`dialogue.lines[${f}].content`),g=no({characterId:d.characterId,character:d.character,characterName:d.characterName,characters:t,variables:r});return{...d,textSpeed:d.textSpeed??l,content:p.map(h=>({...h,text:En(h.text,{variables:r})})),character:g,characterName:g.name}}),u=no({characterId:e.characterId,character:e.character,characters:t,variables:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,persistSprite:e.persistSprite,character:u,textSpeed:a,content:i.map(d=>({...d,text:En(d.text,{variables:r})})),initialRevealedCharacters:s,lines:c}},Ts=({container:e,resources:n,templateData:t,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=Me(e,t);return Ve(We(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),n)},Yr=(e,n={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(n),gs=({renderStateKeyboard:e,keyboard:n,phase:t})=>{!n||typeof n!="object"||Array.isArray(n)||Object.entries(n).forEach(([r,o])=>{let i=e[r]??{},s=t==="keydown"?o?.keydown:o?.keyup;if(t==="keydown"&&s&&typeof s=="object"){e[r]={...i,keydown:{payload:Yr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[r].keyup={payload:Yr(o.keyup)});return}e[r]={...i,[t]:{payload:Yr(o)}}})},jd=(e={},n={})=>{let t={};return gs({renderStateKeyboard:t,keyboard:e,phase:"keydown"}),gs({renderStateKeyboard:t,keyboard:n,phase:"keyup"}),Object.keys(t).length>0?t:void 0},je=({animationsDef:e,resources:n,previousResourceId:t,currentResourceId:r,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l})=>{if(!e)return[];let a=[],c=({instanceId:I,targetId:E})=>{let A=td({resources:n,animationId:p,playback:g,instanceId:I,targetId:E,animationPath:s});A&&a.push(A)},u=t!=null&&t!==!1,d=r!=null&&r!==!1,f=o&&i&&o===i;nd(e,s);let p=Ku(e),g=Ju(e),h=n?.animations?.[p],b=Wu(h,{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 I=`${l}-animation-transition`,E=g?.continuity==="persistent"?I:`${l}-animation-in`;if(u&&d&&f)return c({instanceId:I,targetId:i}),a;u&&c({instanceId:`${l}-animation-out`,targetId:o}),d&&c({instanceId:E,targetId:i})}return a},Fd=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Ud=(e,{presentationState:n,previousPresentationState:t,currentLineActions:r,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:a,imageGallery:c,musicRoom:u,sceneReplay:d,runtime:f,activePersistentAnimations:p,restoredPersistentAnimations:g,autoMode:h,skipMode:b,isChoiceVisible:I,isFormVisible:E,canRollback:A,form:$,saveSlots:B=[]})=>{let{elements:L,animations:T}=e;if(n.background){let z=r===void 0?!0:dn(r?.background??{},"animations"),G=L.find(fe=>fe.id==="story");if(!G)return e;let S=id(o,n.background),q=S||ad(n.background),W=t?.background?.resourceId,me=t?.background?.colorId,Y=n.background.resourceId??(n.background.animations?W:void 0),ae=n.background.colorId??(n.background.animations?me:void 0),oe=Sd(o,Y),ge={...n.background,colorId:ae};if((ae!==void 0||oe)&&G.children.push(vd({resources:o,background:ge,screen:i,includeOpacity:!oe})),Y){let{images:fe={},videos:le={},spritesheets:x={}}=o,C=As(o,Y),O;if(C==="sprite"?O=fe[Y]:C==="video"?O=le[Y]:C==="spritesheet-animation"&&(O=x[Y]),O){let Q=C==="video",Ie=C==="spritesheet-animation",H={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...S},Te={...ls(n.background,{includeDefaultAlpha:!0}),...De(H,n.background)},he;Ie?he=Es({id:Tt({resourceId:Y,kind:C}),resourceId:Y,spritesheet:O,animationName:n.background.animationName,animationSpeed:n.background.animationSpeed,loop:n.background.loop,transform:Te}):he={id:Tt({resourceId:Y,kind:C}),type:Q?"video":"sprite",src:O.fileId,width:O.width,height:O.height,...Te},Q&&(he.loop=n.background.loop??!1,he.volume=O.volume??50),he&&G.children.push(he)}}if(Y){let{layouts:fe={}}=o,le=fe[Y];if(le){let x={id:Tt({resourceId:Y,kind:"container"}),type:"container",children:le.elements,...ls(n.background)};q&&Object.assign(x,De({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...S},n.background));let C=Me(x,Re({variables:a,imageGallery:c,musicRoom:u,sceneReplay:d,runtime:f,saveSlots:B,dialogueState:n.dialogue,isLineCompleted:s,autoMode:h,skipMode:b,isChoiceVisible:I,isFormVisible:E,canRollback:A,form:$,characters:o.characters||{},skipTransitionsAndAnimations:l}));G.children.push(Ve(We(C,{isLineCompleted:s,skipMode:b,skipTransitionsAndAnimations:l}),o))}}let $e=fs({resources:o,resourceId:W,colorId:me}),ce=fs({resources:o,resourceId:Y,colorId:ae}),te=je({animationsDef:n.background.animations,resources:o,previousResourceId:$e.resourceId,currentResourceId:ce.resourceId,previousTargetId:$e.targetId,currentTargetId:ce.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});ke({animationInstances:te,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:p,restoredPersistentAnimations:g,isAuthoredOnCurrentLine:z})&&T.push(...te)}return e},Bd=(e,{presentationState:n,previousPresentationState:t,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:a}=e;if(n.character&&r){let c=l.find(g=>g.id==="story");if(!c)return e;let u=n.character.items||[],d=t?.character?.items||[],f=is(u),p=is(d);for(let g=0;g<u.length;g++){let h=u[g],{transformId:b,sprites:I}=h,E=d.find(q=>q.id===h.id),A=d.findIndex(q=>q.id===h.id),$=E?.sprites&&E.sprites.length>0,B=I&&I.length>0,L=A>=0?Ot(E,A,p):void 0,T=je({animationsDef:h.animations,resources:r,previousResourceId:L,currentResourceId:B?Ot(h,g,f):void 0,previousTargetId:L,currentTargetId:B?Ot(h,g,f):void 0,animationPath:`character.items[${g}].animations`,idPrefix:"character"});if(h.animations&&!I&&!b&&$&&ke({animationInstances:T,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...T);continue}if(h.animations&&!I&&!b)continue;if(!I||I.length===0||!b){console.warn("Character item missing sprites or transformId:",h);continue}let z=Ot(h,g,f),G=r.transforms[b];if(!G){console.warn("Transform not found:",b);continue}let S={type:"container",id:z,...De(G,h),...Sn(h),children:[]};for(let q of I){let W=xs({id:`${z}-${q.id}`,item:q,resources:r});W&&S.children.push(W)}c.children.push(S),ke({animationInstances:T,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...T)}}return e},Ls=(e,n)=>{if(!jr.includes(e))throw new Error(`${n} must be one of: ${jr.join(", ")}.`)},Gd=(e,n)=>{let t=!!e.resourceId||so(e),r=e.layer??(t?void 0:n?.layer)??Vr;return Ls(r,`Visual item "${e.id}" layer`),r},zd=(e,{presentationState:n,previousPresentationState:t,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,imageGallery:l,musicRoom:a,sceneReplay:c,runtime:u,activePersistentAnimations:d,autoMode:f,skipMode:p,isChoiceVisible:g,isFormVisible:h,canRollback:b,form:I,saveSlots:E=[],visualLayer:A})=>{let{elements:$,animations:B}=e;if(n.visual&&r){let L=$.find(S=>S.id==="story");if(!L)return e;let T=n.visual.items,z=t?.visual?.items||[],G=Re({variables:s,imageGallery:l,musicRoom:a,sceneReplay:c,runtime:u,saveSlots:E,dialogueState:n.dialogue,isLineCompleted:o,autoMode:f,skipMode:p,isChoiceVisible:g,isFormVisible:h,canRollback:b,form:I,characters:r.characters||{},skipTransitionsAndAnimations:i});A!==void 0&&Ls(A,"visualLayer");for(let S of T){let q=z.find(oe=>oe.id===S.id),W=Gd(S,q);if(A!==void 0&&W!==A)continue;if(xd(S),S.text){let oe=Hn(r,S),ge={...structuredClone(S.text),id:`visual-${S.id}`,type:"text",...De(oe,S)};Object.assign(ge,Sn(S)),L.children.push(Ve(Me(ge,G),r))}if(S.resourceId){let{images:oe={},videos:ge={},spritesheets:$e={}}=r,ce=$e[S.resourceId];if(ce){let te=Hn(r,S),fe=S.animationName;if(fe){let le=ce.animations?.[fe];if(!le)throw new Error(`Animation '${fe}' not found in spritesheet resource '${S.resourceId}'`);let x=Sn(S),C={id:`visual-${S.id}`,type:"spritesheet-animation",...De(te,S),width:S.width??ce.width,height:S.height??ce.height,alpha:x.alpha??S.alpha??1,src:ce.fileId,atlas:ce.jsonData,playback:{frames:le.frames,animationSpeed:S.animationSpeed??le.animationSpeed??.5,loop:S.loop??le.loop??!0}};x.blur&&(C.blur=x.blur),L.children.push(structuredClone(C))}}else{let te=oe[S.resourceId]||ge[S.resourceId];if(te){let fe=ge[S.resourceId]!==void 0,le=Hn(r,S),x={id:`visual-${S.id}`,type:fe?"video":"sprite",src:te.fileId,width:te.width,height:te.height,...De(le,S)};Object.assign(x,Sn(S)),fe&&(x.loop=te.loop??!1,x.volume=te.volume??50),L.children.push(x)}}}if(S.resourceId){let oe=r.particles?.[S.resourceId];oe&&L.children.push(Ed({item:S,particle:oe,resources:r}))}if(S.resourceId){let{layouts:oe={}}=r,ge=oe[S.resourceId];if(ge){let $e=Hn(r,S),ce={id:`visual-${S.id}`,type:"container",children:structuredClone(ge.elements),...De($e,S)};Object.assign(ce,Sn(S));let te=Me(ce,G);L.children.push(Ve(We(te,{isLineCompleted:o,skipMode:p,skipTransitionsAndAnimations:i}),r))}}let me=us(q),Y=us(S),ae=je({animationsDef:S.animations,resources:r,previousResourceId:me,currentResourceId:Y,previousTargetId:me?`visual-${S.id}`:void 0,currentTargetId:Y?`visual-${S.id}`:void 0,animationPath:`visual.items[${S.id}].animations`,idPrefix:S.id});ke({animationInstances:ae,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:d})&&B.push(...ae)}}return e},vn="dialogue-character-sprite",qd=(e,{presentationState:n,previousPresentationState:t,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=fn(e.elements);if(!a)return e;let c=n.dialogue?.character?.sprite,u=t?.dialogue?.character?.sprite,d=Mn(c),f=Mn(u),p=je({animationsDef:c?.animations,resources:r,previousResourceId:f?vn:void 0,currentResourceId:d?vn:void 0,previousTargetId:f?vn:void 0,currentTargetId:d?vn:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!d)return c?.animations&&f&&ke({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e;let g=r.transforms?.[c.transformId];if(!g)return console.warn("Transform not found:",c.transformId),e;let h={type:"container",id:vn,...De(g),children:[]};for(let b of c.items){let I=xs({id:`${vn}-${b.id}`,item:b,resources:r});I&&h.children.push(I)}return a.children.push(h),ke({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e},Yd=(e,{presentationState:n,previousPresentationState:t,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,skipOnlyViewedLines:d,isLineCompleted:f,skipTransitionsAndAnimations:p,variables:g,imageGallery:h,musicRoom:b,sceneReplay:I,runtime:E,activePersistentAnimations:A,saveSlots:$=[]})=>{let{elements:B,animations:L}=e;if(!n.dialogue||o)return e;let T=B.find(G=>G.id==="story");if(!T)return e;if(n.dialogue.ui&&n.dialogue.ui.resourceId){let{layouts:G={}}=r,S=G[n.dialogue.ui.resourceId];if(S){let q={elements:S.elements},W=Re({variables:g,imageGallery:h,musicRoom:b,sceneReplay:I,runtime:E,saveSlots:$,dialogueState:n.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}),me=Me(q,W),Y=Ve(We(me?.elements,{isLineCompleted:f,skipMode:s,skipTransitionsAndAnimations:p}),r);if(Array.isArray(Y))for(let ae of Y)T.children.push(ae);else Y&&T.children.push(Y)}}qd(e,{presentationState:n,previousPresentationState:t,resources:r,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:A});let z=je({animationsDef:n.dialogue.ui?.animations,resources:r,previousResourceId:t?.dialogue?.ui?.resourceId,currentResourceId:n.dialogue.ui?.resourceId,previousTargetId:t?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:n.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return ke({animationInstances:z,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:A})&&L.push(...z),e},Hd=(e,{presentationState:n,previousPresentationState:t,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,imageGallery:a,musicRoom:c,sceneReplay:u,runtime:d,autoMode:f,skipMode:p,isChoiceVisible:g,isFormVisible:h,canRollback:b,form:I,activePersistentAnimations:E,saveSlots:A=[]})=>{let{elements:$,animations:B}=e;if(n.choice&&r){let L=fn($);if(!L)return e;let T=r?.layouts[n.choice.resourceId];if(T&&T.elements){let G={elements:T.elements},S=Me(G,{...Re({variables:l,imageGallery:a,musicRoom:c,sceneReplay:u,runtime:d,saveSlots:A,dialogueState:n.dialogue,isLineCompleted:i,autoMode:f,skipMode:p,isChoiceVisible:g??!!n.choice,isFormVisible:h,canRollback:b,form:I,characters:r.characters||{},skipTransitionsAndAnimations:s}),choice:{items:n.choice?.items??[]}}),q=Qr(Ve(We(S?.elements,{isLineCompleted:i,skipMode:p,skipTransitionsAndAnimations:s}),r));if(Array.isArray(q))for(let W of q)L.children.push(W);else q&&L.children.push(q)}let z=je({animationsDef:n.choice.animations,resources:r,previousResourceId:t?.choice?.resourceId,currentResourceId:n.choice.resourceId,previousTargetId:t?.choice?.resourceId?"choice-container":void 0,currentTargetId:n.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});ke({animationInstances:z,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:E})&&B.push(...z)}return e},Wd=(e,{presentationState:n,previousPresentationState:t,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,imageGallery:a,musicRoom:c,sceneReplay:u,runtime:d,autoMode:f,skipMode:p,isChoiceVisible:g,isFormVisible:h,canRollback:b,activePersistentAnimations:I,saveSlots:E=[],form:A})=>{let{elements:$,animations:B}=e;if(!A?.resourceId||!r)return e;let L=fn($);if(!L)return e;let T=r?.layouts?.[A.resourceId];if(!T)return console.warn(`Form layout not found: ${A.resourceId}`),e;let z={id:"form-container",type:"container",x:0,y:0,children:T.elements||[]},G={...Re({variables:l,imageGallery:a,musicRoom:c,sceneReplay:u,runtime:d,saveSlots:E,dialogueState:n.dialogue,isLineCompleted:i,autoMode:f,skipMode:p,isChoiceVisible:g,isFormVisible:h,canRollback:b,characters:r.characters||{},skipTransitionsAndAnimations:s,form:A}),form:A},S=Me(z,G),q=eo(Ve(We(Zr(S,A),{isLineCompleted:i,skipMode:p,skipTransitionsAndAnimations:s}),r),A);q&&L.children.push(q);let W=je({animationsDef:A.animations,resources:r,previousResourceId:t?.form?.resourceId,currentResourceId:A.resourceId,previousTargetId:t?.form?.resourceId?"form-container":void 0,currentTargetId:A.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return ke({animationInstances:W,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:I})&&B.push(...W),e},Kd=(e,{presentationState:n,resources:t={},variables:r,imageGallery:o,musicRoom:i,sceneReplay:s,runtime:l,isLineCompleted:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:g,saveSlots:h=[],skipTransitionsAndAnimations:b})=>{if(!n.control?.resourceId)return e;let I=t.controls?.[n.control.resourceId];if(!I)return e;let E=jd(I.keyboard,I.keyup);if(E&&Object.keys(E).length>0&&(e.global.keyboard=E),!Array.isArray(I.elements)||I.elements.length===0)return e;let A=fn(e.elements);if(!A)return e;let $={id:`control-${n.control.resourceId}`,type:"container",x:0,y:0,children:I.elements};return A.children.push(Ts({container:$,resources:t,templateData:Re({variables:r,imageGallery:o,musicRoom:i,sceneReplay:s,runtime:l,saveSlots:h,dialogueState:n.dialogue,isLineCompleted:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:g,characters:t.characters||{},skipTransitionsAndAnimations:b}),isLineCompleted:a,skipMode:u,skipTransitionsAndAnimations:b})),e},Jd=(e,{presentationState:n,resources:t,runtime:r,variables:o,musicRoomPlayer:i})=>{let{elements:s,audio:l}=e;if(n.bgm&&t){if(!fn(s))return e;let c=n.bgm,u=!Array.isArray(c.sounds),d=u?c.resourceId?[{id:"default",resourceId:c.resourceId,loop:c.loop??!0,volume:c.volume,startDelayMs:c.startDelayMs??0}]:[]:c.sounds,f=!u&&c.loop===!0,p=[];if(u||Pt(d,"BGM sound"),f){let h=d.find(b=>b.loop===!0);if(h)throw new Error(`BGM sound "${h.id}" cannot loop inside a looping BGM channel.`)}if(d.forEach(h=>{let b=t.sounds?.[h.resourceId];if(!b)return;let I=f?{...h,loop:h.loop??!1}:h;p.push(jt({id:Wn("bgm",u?"default":h.id),sound:I,resource:b,defaultLoop:!f}))}),p.length===0)return e;let g=Re({variables:o,runtime:r}).runtime;l.push(Vt({id:Rd,volume:Mt(g,"musicVolume",u?He:c.volume??He),muted:c.muted,pan:c.pan,loop:u?void 0:c.loop,playback:i?.bgmPlayback,interruption:c.interruption,children:p,runtime:g}))}return e},Xd=(e,{resources:n={},runtime:t,variables:r,musicRoomPlayer:o})=>{let i=n.musicRoom;if(!i||!o?.trackId||!o.playback)return e;let s=i.tracks.find(u=>u.id===o.trackId),l=s?n.sounds?.[s.soundId]:void 0;if(!s||!l)return e;let a=Re({variables:r,runtime:t}).runtime,c=jt({id:_d,sound:{loop:!1,startDelayMs:0,playback:o.playback},resource:l});return e.audio.push(Vt({id:Cd,volume:Mt(a,"musicVolume",He),children:[c],runtime:a})),e},Qd=(e,{presentationState:n,resources:t,runtime:r})=>{let{audio:o}=e;if(n.sfx&&t){let i=n.sfx,s=!Array.isArray(i.channels),l=s?[{id:Od,sounds:i.items??[]}]:i.channels;s||Pt(l,"SFX channel"),l.forEach(a=>{let c=!s&&a.loop===!0,u=[];if(s||Pt(a.sounds,"SFX sound",`SFX channel "${a.id}"`),c){let d=a.sounds.find(f=>f.loop===!0);if(d)throw new Error(`SFX sound "${d.id}" cannot loop inside looping SFX channel "${a.id}".`)}a.sounds.forEach((d,f)=>{let p=t.sounds?.[d.resourceId];if(!p)return;let g=c?{...d,loop:d.loop??!1}:d;u.push(jt({id:s?Wn("sfx","default",f,d.id):Wn("sfx",a.id,d.id),sound:g,resource:p,defaultLoop:c?!1:void 0}))}),u.length!==0&&o.push(Vt({id:Wn("channel","sfx",a.id),volume:Mt(r,"soundVolume",a.volume??He),muted:a.muted,pan:a.pan,loop:s?void 0:a.loop,interruption:s?void 0:a.interruption,children:u,runtime:r}))})}return e},Zd=(e,n,t)=>{if(!(!n||!t))return e?.voices?.[n]?.[t]},ef=(e,{presentationState:n,resources:t,currentSceneId:r,runtime:o,variables:i})=>{let{audio:s}=e;if(!n?.voice)return e;let l=n.voice,a=!Array.isArray(l.sounds),c=a?l.resourceId?[{id:"default",resourceId:l.resourceId,loop:l.loop??!1,volume:He,startDelayMs:l.startDelayMs??0}]:[]:l.sounds,u=!a&&l.loop===!0,d=[];if(a||Pt(c,"Voice sound"),u){let p=c.find(g=>g.loop===!0);if(p)throw new Error(`Voice sound "${p.id}" cannot loop inside a looping Voice channel.`)}if(c.forEach(p=>{let g=Zd(t,r,p.resourceId);if(!g)return;let h=u?{...p,loop:p.loop??!1}:p;d.push(jt({id:Wn("voice",r,a?"default":p.id),sound:h,resource:g,defaultLoop:u?!1:void 0}))}),d.length===0)return e;let f=Re({variables:i,runtime:o}).runtime;return s.push(Vt({id:kd,volume:a?l.volume??ks(f,"soundVolume"):Mt(f,"soundVolume",l.volume??He),muted:l.muted,pan:l.pan,loop:a?void 0:l.loop,interruption:l.interruption,children:d,runtime:f})),e},nf=(e,{presentationState:n,previousPresentationState:t,resources:r={},variables:o,imageGallery:i,musicRoom:s,sceneReplay:l,runtime:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:g,saveSlots:h=[],isLineCompleted:b,skipTransitionsAndAnimations:I,activePersistentAnimations:E})=>{let{elements:A,animations:$}=e;if(n.layout){let z=fn(A);if(!z)return e;let G=r.layouts[n.layout.resourceId];if(!G)return e;Array.isArray(G.transitions)&&!b&&!I&&ro({animations:$,transitions:G.transitions,defaultTargetId:`layout-${n.layout.resourceId}`,idPrefix:`layout-${n.layout.resourceId}`,animationPathPrefix:"layout"});let S={id:`layout-${n.layout.resourceId}`,type:"container",x:0,y:0,children:G.elements||[]};z.children.push(Ts({container:S,resources:r,templateData:Re({variables:o,imageGallery:i,musicRoom:s,sceneReplay:l,runtime:a,saveSlots:h,dialogueState:n.dialogue,isLineCompleted:b,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:g,characters:r.characters||{},skipTransitionsAndAnimations:I}),isLineCompleted:b,skipMode:u,skipTransitionsAndAnimations:I}))}let B=t?.layout?.resourceId,L=n.layout?.resourceId,T=je({animationsDef:n.layout?.animations,resources:r,previousResourceId:B,currentResourceId:L,previousTargetId:B?`layout-${B}`:void 0,currentTargetId:L?`layout-${L}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return ke({animationInstances:T,isLineCompleted:b,skipTransitionsAndAnimations:I,activePersistentAnimations:E})&&$.push(...T),e},tf=(e,{currentLineActions:n,previousPresentationState:t,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=n?.screen?.animations;if(!a)return e;let c=t!=null,u=je({animationsDef:a,resources:r,previousResourceId:c?"story":void 0,currentResourceId:"story",previousTargetId:c?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return ke({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...u),e},rf=(e,{presentationState:n})=>{let t=fn(e.elements);return!t||!n?.screen||Object.assign(t,Cs(n.screen)),e},of=(e,{presentationState:n,resources:t={},variables:r,imageGallery:o,musicRoom:i,sceneReplay:s,runtime:l,autoMode:a,skipMode:c,isChoiceVisible:u,isFormVisible:d,canRollback:f,form:p,overlayStack:g=[],dialogueHistory:h=[],saveSlots:b=[],screen:I,isLineCompleted:E,skipTransitionsAndAnimations:A})=>{let{elements:$,animations:B}=e;return g&&g.length>0&&g.forEach((L,T)=>{let z=t.layouts[L.resourceId];if(!z){console.warn(`Overlay layout not found: ${L.resourceId}`);return}Array.isArray(z.transitions)&&(A||ro({animations:B,transitions:z.transitions,defaultTargetId:`overlayStack-${T}`,idPrefix:`overlayStack-${T}`,animationPathPrefix:`overlayStack[${T}]`}));let G={id:`overlayStack-${T}`,type:"container",x:0,y:0,children:[Os({id:`overlayStack-${T}-blocker`,screen:I}),...z.elements||[]]},S=$s(h,t.characters,r),q=Re({variables:r,imageGallery:o,musicRoom:i,sceneReplay:s,runtime:l,saveSlots:b,dialogueState:n?.dialogue,isLineCompleted:E,autoMode:a,skipMode:c,isChoiceVisible:u,isFormVisible:d,canRollback:f,form:p,historyDialogue:S,characters:t.characters||{},skipTransitionsAndAnimations:A}),W=Me(G,q),[me,...Y]=W.children||[],ae=Ve(We({...W,children:Y},{isLineCompleted:E,skipMode:c,skipTransitionsAndAnimations:A}),t);$.push({...ae,children:me?[me,...ae.children||[]]:ae.children})}),e},sf=(e,{presentationState:n,resources:t={},variables:r,imageGallery:o,musicRoom:i,sceneReplay:s,runtime:l,saveSlots:a=[],autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:g,confirmDialog:h,dialogueHistory:b=[],screen:I,isLineCompleted:E,skipTransitionsAndAnimations:A})=>{let{elements:$,animations:B}=e;if(!h?.resourceId)return e;let L=t.layouts?.[h.resourceId];if(!L)return console.warn(`ConfirmDialog layout not found: ${h.resourceId}`),e;Array.isArray(L.transitions)&&!A&&ro({animations:B,transitions:L.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let T={id:"confirmDialog",type:"container",x:0,y:0,children:[Os({id:"confirmDialog-blocker",screen:I}),...L.elements||[]]},z=$s(b,t.characters,r),G=Me(T,Re({variables:r,imageGallery:o,musicRoom:i,sceneReplay:s,runtime:l,saveSlots:a,dialogueState:n?.dialogue,isLineCompleted:E,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:g,confirmDialog:h,historyDialogue:z,characters:t.characters||{},skipTransitionsAndAnimations:A})),[S,...q]=G.children||[],W=Ve(We({...G,children:q},{isLineCompleted:E,skipMode:u,skipTransitionsAndAnimations:A}),t);return $.push({...W,children:S?[S,...W.children||[]]:W.children}),e},Xn=e=>(n,t)=>zd(n,{...t,visualLayer:e}),af=Xn(Ne.BEHIND_BACKGROUND),cf=Xn(Ne.BEHIND_CHARACTER),lf=Xn(Ne.BEHIND_DIALOGUE),uf=Xn(Ne.BEHIND_CHOICE),df=Xn(Ne.FOREGROUND),Ps=e=>St(Fd,[Kd,af,Ud,cf,Bd,lf,Yd,uf,Hd,Wd,nf,df,rf,tf,Jd,Xd,Qd,ef,of,sf])(e);function Ns(e,n=""){let t=[],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(),t.push([a,s,n?parseInt(n[i++],36):0])}return t}function Ds(e,n,t){let r=0,o=n.length-1;for(;r<=o;){let i=r+o>>>1,s=t[i];if(e<n[i])o=i-1;else if(e>s>>>5)r=i+1;else return s&31}return 0}var Ms="090001000h1v5g2903000hl2v6jh16ng1s210111110o35aa10u2k1g10l6600152113h2010u1q1r5aq3890o13181214r22k3158q2n1000v100h1k20000001207030001160721k171001h1j11610332010010321210090411021c1c02100o301201412230u1130b100h1j116111420120411001100k11l10051001h1j11611142011000321210072411021d0g10r3000000132120090o200200g1j11f2012031213711271t1001o301001000001121371b1f0c101h1l2011001031212000080a1t1001m40400102101600i11t301006c7i601008b6p41r10101041h3d0004115a1j290p3q223000511010100g1501010302003172030c0010016000e0i6v50n40n5tl12ir33s12t11u11cj30100060700010a90t220000l71i20m7203010241000502rd101004k300000006101027050920g3t22bk1300616g209030207u18c1000t10003010501b2o20000102000004g37070101o921c000640602001mcv3rg20000001o16d0c0m1fg6g2h30m10q55f1vm11c0ma0p1a42nc0ne1a090q3314902021204020112030318250105bb1201110i1021i15101131502141b15120511011k1155132040202510201010603060a1f02040104210b1g3290e0e0kn11vs12j11j3040pp12t80g6v1vmo7319g21g51gh103040n11010040j51i3f01q1h1d0m27p1a0000cs13200523j200010301010100v140018a4q2501010101c08000i1f12601011g3012215110u1a0001015000pcq181000100011000iji5fvc0u91g5bhg20ie0l94lo6002115303121s12240la1tj23h44tj11t45m4ah33q700000l3ep2021a200t220301012040a0i320j2040007f00100r20c100g3208000011531000s520201036020t900207l1101n311000000321210090a12634b910201l22001051020120011020000e1i520701020000n10h5001050000010000010001re0010323010001r11i520701000001q6000000107l600000230004gg12080001lc62027111n1000411230000000000t820321030030r10090n205001380800501020n2050c0001mc00002000000nc006150000i5l1100600010001q753011160000i441111000000rl11019100000c1h201043102n10ltk1f006eoss2b0202gs94r36si2033ku101m373h50b1rqs4113sli1t22m1uh2435070726u13k92rr7m34h380e0m141egl561g1261114k60ga6nn10t33sv13uf1jf0207150qt16t66pr60n23k6bf1f0e1l29g71c1e029j1n30p11ea0k1028139m16rb2v621122i52213040tf1u3b51n17127c0232041d120819052c28220104060306l5g3l4572g130152cqdl2c3o37a5o27u11c32d9m2cu2191obo57eh9gg1tv3",Vs="262122424333333393233393339333333333393393bf3b3b3b3b3f3f3bffff33b3bb33ff3f33b3b3333333bffff3b33bb33f33bffff33b3bb33ff3f33b3bbb333b3ff33b333f33b3b3b3b3333b3bf33b3bb39333b33b33b3b3b333b333333b3b33333f3b33b3ffb3f3fff3f3b33f35dc33333f3b3b3b33323333b3bb3b33b3fb3b3333b33333bff3b3f33bfb3b3ff3b3b3b3b3b333b333b3323e22442344444444444444444444444444444444444444444444444444444444444444444444444444444443333333333b3b3bb33333b353bff3b3b3b3f3ff3b3b333bfff3f33333fb3bb3fb3b3bb33232333f333fff333333333b3b3333bb3b39393f3b3fbf33bb3b393b3b3b3333b33b33b3bbb33b33ffff3b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b3fffff3bb39b9b3b33b3bf3f3b33f3b3f93b33b3b3bb33b33b3b3b3333393b3b3b33b39bffb3b332333b333dd3b3333233332333333333333333333333333333444444444444a4444444444444344444444444444444444444444444444444444444444",js="0001000000010010000000100000000000000000000000000001000000010014000100000001001000010101100101100000000000000000000100000001111000010000000110101001110111111111000100000021001000010000000100100001000000011010000100000001111000013000000100140001000000010010";var Fs=65535,ao=40960,Ft=126976,Gs=new Uint8Array(12288),zs=new Uint8Array(3072),qs=new Uint8Array(2816),Ys,Hs;{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},n=new Uint32Array(320),t=new Uint32Array(320),r=0;for(let[o,i,s]of Ns(Ms,Vs))e(Gs,0,o,i,s),e(zs,ao,o,i,s),e(qs,Ft,o,i,s),i>=65040&&!(o>=Ft&&i<=129791)&&(n[r]=o,t[r++]=i<<5|s);Ys=n.slice(0,r),Hs=t.slice(0,r)}function Us(e){return e<12288?Gs[e]:e<ao?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?zs[e-ao]: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>=Ft&&e<129792?qs[e-Ft]:e>=917504?e>921599?0:e>=917536&&e<917632||e>=917760&&e<918e3?3:2:Ds(e,Ys,Hs)}var Ws=Uint8Array.from(js,Number);function ff(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 Bs(e,n,t){switch(n){case 3:return e&24?t===8204?e&6:(e&24)===16||ff(t)?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*Ks(e){let n=e.length;if(n===0)return;let t=e.codePointAt(0),r=t>Fs?2:1,o=Us(t),i=50200>>o&1?Bs(0,o,t):0,s=0,l=t,a=o;for(;r<n;){t=e.codePointAt(r);let c=t>Fs?2:1,u=Us(t),d=Ws[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)?Bs(i,u,t):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=t,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*Js(e){for(let n of Ks(e))yield n.segment}{let e=Ks("_");Ws._keep=[e,e.next()]}var Xs=1e3,pf=1,mf=60,gf=3,hf=.5,yf=2e4,bf=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,If=/^\s+$/u,Qs,wf=e=>{let n=`${e??""}`.normalize("NFC"),t=globalThis.Intl?.Segmenter;return typeof t!="function"?Array.from(Js(n)):(Qs??=new t(void 0,{granularity:"grapheme"}),Array.from(Qs.segment(n),({segment:r})=>r))},Af=e=>wf(e).reduce((n,t)=>If.test(t)?n+hf:bf.test(t)?n+gf:n+1,0),Zs=({text:e="",baseDelay:n=Xs,speed:t=pf}={})=>{let r=Number.isFinite(n)?Math.max(0,n):Xs,o=Number.isFinite(t)&&t>0?t:1,i=Af(e)*mf/o,s=Math.max(r,yf);return Math.min(r+i,s)};var Ut={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},sa=1,fo=1,_n="choice",Ke="form",et=()=>({manual:{...Ut.manual},auto:{...Ut.auto},applyMode:Ut.applyMode}),po=()=>({groupId:null,variantId:null,pageIndex:0}),Ef="music-room:player",xf=new Set(["asset-unavailable","decode-failed","invalid-segment","invalid-position","playback-failed"]),zt=({bgmPlayback:e={commandId:0,operation:"resume"}}={})=>({trackId:null,pageIndex:0,status:"stopped",readiness:"idle",positionMs:0,durationMs:null,playback:null,seekFallback:null,bgmPlayback:e}),mo=new Set,vf=new Set(["groupId","variantId"]),Sf=new Set(["pageIndex"]),kn=new Set,Rf=new Set(["trackId"]),Cf=new Set(["positionMs"]),_f=new Set(["pageIndex"]),go=new Set,kf=new Set(["replayId"]),Of=new Set(["pageIndex"]),ho=()=>({pageIndex:0}),yo=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let t=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...et()},t&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},k=e=>{let n=ie(e)?Ue(e):e;return structuredClone(n)},N=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),qt=e=>{let n=e.global.audioCommandId;if(!Number.isSafeInteger(n)||n<0)throw new Error("Internal audio command counter is invalid");if(n===Number.MAX_SAFE_INTEGER)throw new Error("Audio command counter is exhausted");return e.global.audioCommandId=n+1,e.global.audioCommandId},aa=e=>{let n=e.global.sceneReplayEntryId;if(!Number.isSafeInteger(n)||n<0)throw new Error("Internal scene replay entry counter is invalid");if(n===Number.MAX_SAFE_INTEGER)throw new Error("Scene replay entry counter is exhausted");return e.global.sceneReplayEntryId=n+1,e.global.sceneReplayEntryId},nt=(e,n,t)=>({commandId:qt(e),operation:n,...t===void 0?{}:{positionMs:t}}),bo=e=>{if(!Object.prototype.hasOwnProperty.call(e.global??{},"musicRoomPlayer"))return;let n=e.global.musicRoomPlayer,t=n.bgmPlayback;n.trackId!==null&&(t={commandId:qt(e),operation:"resume"}),e.global.musicRoomPlayer=zt({bgmPlayback:t})},ca=(e,n)=>{if(typeof n!="string"||n.length===0)throw new Error("Achievement action requires a non-empty resourceId");let t=e.projectData.resources?.achievements?.[n];if(!t)throw new Error(`Achievement resource "${n}" not found`);if(t.type!=="boolean"&&t.type!=="number")throw new Error(`Achievement resource "${n}" has invalid type "${t.type}"`);return t},tt=e=>String(e),la=()=>({sections:[],resources:[]}),$f=e=>N(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):la(),Tf=e=>Array.isArray(e)?e.map(n=>n?.text??"").join(""):"",Lf=({sectionId:e,lineId:n,content:t,dialogueState:r,characterName:o})=>({sectionId:e,lineId:n,content:t,text:Tf(t),characterId:r.characterId,character:{...r.character||{},name:o},characterName:o}),Pf=()=>({resourceId:void 0}),Nf=e=>{if(!N(e))return e;let n={...e};return Object.prototype.hasOwnProperty.call(n,"requireComplete")&&!Object.prototype.hasOwnProperty.call(n,"requireLineCompleted")&&(n.requireLineCompleted=n.requireComplete),delete n.requireComplete,n},hn=(e,n)=>{let t=e?.story?.scenes??{};for(let[r,o]of Object.entries(t))if(o?.sections?.[n])return{sceneId:r,section:o.sections[n]};return{sceneId:void 0,section:void 0}},ua=e=>{let n=e?.story?.scenes??{},t=new Map;for(let[r,o]of Object.entries(n)){let i=o?.sections??{};for(let s of Object.keys(i)){let l=t.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${r}". Section IDs must be globally unique.`);t.set(s,r)}}},da=e=>{if(typeof e=="number"||typeof e!="string")return e;let n=Number(e);return Number.isFinite(n)?n:e},fa=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==sa)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Df=(e,n={})=>{let t;try{t=fa(n.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...n,formatVersion:t,slotId:da(n.slotId??n.slotKey??e),savedAt:typeof n.savedAt=="number"?n.savedAt:n.date};return delete r.slotKey,delete r.date,r},Mf=(e={})=>Object.fromEntries(Object.entries(e).map(([n,t])=>[n,Df(n,t)])),pa=e=>{if(!Array.isArray(e))return;let n=e.filter(({type:t})=>xg(t));return n.length>0?n:void 0},Vf=e=>{!N(e)||!Array.isArray(e.timeline)||(e.returnabilityVersion=fo,e.timeline.forEach(n=>{if(!N(n))return;typeof n.returnable!="boolean"&&delete n.returnable;let t=pa(n.executedActions);if(t){n.executedActions=t;return}delete n.executedActions}))},ea=(e,n,t,r="viewedRegistry")=>{let o=n==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!N(e))throw new Error(`Malformed ${r}.${n}[${t}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${r}.${n}[${t}] entry: missing ${o}.`);if(n==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${r}.sections[${t}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},jf=(e,n="viewedRegistry")=>{if(e===void 0)return la();if(!N(e))throw new Error(`Malformed ${n}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${n}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${n}.resources.`);let t=e.sections??[],r=e.resources??[];return{sections:Object.values(Object.fromEntries(t.map((o,i)=>{let s=ea(o,"sections",i,n);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(r.map((o,i)=>{let s=ea(o,"resources",i,n);return[s.resourceId,s]})))}},ma=(e,n,t)=>{if(!N(e))throw new Error(`Malformed save slot ${t}.`);let{sectionId:r,lineId:o}=e;if(typeof r!="string"||r.length===0)throw new Error(`Malformed save slot ${t}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${t}: missing lineId.`);let{sceneId:i,section:s}=hn(n,r);if(!s)throw new Error(`Malformed save slot ${t}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(a=>a.id===o))throw new Error(`Malformed save slot ${t}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},ga=(e,n)=>e?.sectionId===n?.sectionId&&e?.lineId===n?.lineId,Ff=(e,n)=>{let{section:t}=hn(e,n?.sectionId);return t?.lines?.find(r=>r.id===n?.lineId)},Uf=(e,n)=>{let{section:t}=hn(e,n?.sectionId),r=t?.lines?.findIndex(i=>i.id===n?.lineId);if(typeof r!="number"||r<0)return null;let o=t.lines[r+1];return o?{sectionId:n.sectionId,lineId:o.id}:null},ha=(e,n,t)=>{if(typeof n?.sectionId!="string")return!1;let{section:r}=hn(e,n.sectionId);return ga({sectionId:n.sectionId,lineId:r?.lines?.[0]?.id},t)},Bf=new Set(["jumpToLine","rollbackByOffset","rollbackToLine","sectionTransition","resetStoryAtSection"]),Cn={always:"always",maybe:"maybe",never:"never"},Gf=e=>{if(!Object.prototype.hasOwnProperty.call(e??{},"when"))return Cn.always;let n=e.when,t;if(n===null||typeof n=="boolean"||typeof n=="number")t=n;else if(N(n)&&Object.keys(n).length===1&&Object.prototype.hasOwnProperty.call(n,"literal"))t=n.literal;else return Cn.maybe;return t?Cn.always:Cn.never},ya=(e,n)=>{if(!Array.isArray(e?.branches))return!1;for(let t of e.branches){let r=Gf(t);if(r!==Cn.never){if(n(t))return!0;if(r===Cn.always)return!1}}return!1},ba=e=>ya(e,n=>Object.entries(n?.actions??{}).some(([t,r])=>t==="conditional"?ba(r):Bf.has(t))),Ia=(e,n,t)=>ya(n,r=>Object.entries(r?.actions??{}).some(([o,i])=>o==="sectionTransition"?ha(e,i,t):o==="conditional"?Ia(e,i,t):!1)),zf=(e,n,t)=>{if(!n)return!0;let r=Ff(t,e)?.actions;if(!N(r))return!0;if(ha(t,r.sectionTransition,n))return!1;let o=r.conditional;return o?!(Ia(t,o,n)||!(r.choice?.resourceId||r.form?.resourceId)&&!ba(o)&&ga(Uf(t,e),n)):!0},qf=(e,n,t)=>{if(!N(e)||!Array.isArray(e.timeline))return Zn({pointer:n,replayStartIndex:1});let r=new WeakSet,o=e.timeline.flatMap((c,u)=>{if(!N(c))return[];try{let d=ma(c,t,`rollback.timeline[${u}]`),f=Gt({sectionId:d.sectionId,lineId:d.lineId,rollbackPolicy:c.rollbackPolicy,returnable:c.returnable});typeof c.returnable=="boolean"&&r.add(f);let p=pa(k(c.executedActions));return p&&(f.executedActions=p),[f]}catch{return[]}});if(o.length===0)return Zn({pointer:n,replayStartIndex:1});e.returnabilityVersion!==fo&&o.forEach((c,u)=>{!r.has(c)&&!zf(c,o[u+1],t)&&(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!==n.sectionId||l?.lineId!==n.lineId){let c=o.findLastIndex(u=>u.sectionId===n.sectionId&&u.lineId===n.lineId);c>=0?s=c:(o.push(Gt({sectionId:n.sectionId,lineId:n.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}},Yf=(e,n,t)=>{if(!N(e))throw new Error(`Malformed save slot contexts[${t}] entry.`);let r=Ao(n),o=ma(e.pointers?.read,n,`contexts[${t}].pointers.read`);if(e.variables!==void 0&&!N(e.variables))throw new Error(`Malformed save slot contexts[${t}].variables entry.`);if(e.runtime!==void 0&&!N(e.runtime))throw new Error(`Malformed save slot contexts[${t}].runtime entry.`);let i=e.variables?An(k(e.variables),n.resources?.variables??{}):{},s=ip({loadedContextRuntime:N(e.runtime)?k(e.runtime):{}}),l={currentPointerMode:"read",pointers:{read:o},configuration:N(e.configuration)?k(e.configuration):{},views:Array.isArray(e.views)?k(e.views):[],bgm:N(e.bgm)?k(e.bgm):{resourceId:void 0},variables:{...r,...i},rollback:qf(e.rollback,o,n)};return s&&(l.runtime=s),l},Hf=(e,n)=>{if(!N(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((t,r)=>Yf(t,n,r))}},Wf=(e,n)=>{if(!N(e))throw new Error("Malformed save slot.");let t=fa(e.formatVersion);return{...e,formatVersion:t,state:Hf(e.state,n)}},na=(e,n,{required:t=!1}={})=>{if(e===void 0){if(t)throw new Error(`showConfirmDialog requires ${n}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${n} must be an action object`);let r=k(e),o=r.hideConfirmDialog??{};return delete r.hideConfirmDialog,{hideConfirmDialog:o,...r}},Kf=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:na(e.confirmActions,"confirmActions",{required:!0}),cancelActions:na(e.cancelActions,"cancelActions")}},On=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Jf=e=>(N(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),$n=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},wa=e=>{if(!(!N(e)||!e.animations))return{animations:k(e.animations)}},Xf=(e,n)=>{let t=wa(n);if(t){e.global.pendingScreenTransition=t;return}delete e.global.pendingScreenTransition},Qf=e=>{let n=e?.id??e?.resourceId;return typeof n=="string"&&n.length>0?n:void 0},Zf=(e,n)=>{let t=e?.sectionId,r=e?.lineId;if(!(!t||!r||!n))return`${t}:${r}:${n}`},Bt=e=>String(e??""),Aa=(e,n)=>{let t=Bt(n);return e?.trim===!0?t.trim():t},ep=e=>N(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,n])=>N(n)).map(([n,t])=>[n,{id:n,...k(t)}])):{},np=(e,n)=>{if(!n||!N(e.global.formDrafts))return;let t=e.global.formDrafts[n];return N(t)?t:void 0},Ea=(e,n)=>{let t=Jf(e);N(t[n])||(t[n]={values:{},touched:{},errors:{},submitted:!1});let r=t[n];return N(r.values)||(r.values={}),N(r.touched)||(r.touched={}),N(r.errors)||(r.errors={}),typeof r.submitted!="boolean"&&(r.submitted=!1),r},Io=(e,n)=>{let t=Aa(e,n);return e?.required===!0&&t.length===0?"required":null},tp=({state:e,pointer:n})=>{if(!n?.sectionId||!n?.lineId)return{};let r=de({state:e},{sectionId:n.sectionId})?.lines||[],o=r.findIndex(i=>i.id===n.lineId);return o<0?{}:cn(r.slice(0,o+1).map(i=>i.actions||{}))},rp=({state:e,form:n,pointer:t})=>{if(!n?.resourceId)return null;let r=Qf(n),o=Zf(t,r);if(!r||!o)return null;let i=np(e,o),s=ep(n),l=Yt({state:e}),a={},c=[],u={},d=!0;return Object.entries(s).forEach(([f,p])=>{let g=Bt(l?.[p.variableId]),h=Object.prototype.hasOwnProperty.call(i?.values??{},f)?Bt(i.values[f]):g,b=i?.touched?.[f]===!0,I=Io(p,h),E=i?.submitted||b?I:null,A=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,$={id:f,variableId:p.variableId,value:h,initialValue:g,valid:!I,error:E,touched:b,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...A!==void 0?{maxLength:A}:{}};I&&(d=!1),a[f]=$,c.push($),u[f]=h}),{id:r,key:o,resourceId:n.resourceId,animations:n.animations,valid:d,submitted:i?.submitted===!0,fields:a,fieldList:c,values:u,submitActions:{submitForm:{formKey:o,actions:k(n.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:k(n.cancelActions??{})}}}},mn=[],ta="line",wo="interaction",Gt=({sectionId:e,lineId:n,rollbackPolicy:t,returnable:r})=>({sectionId:e,lineId:n,rollbackPolicy:t??"free",...typeof r=="boolean"?{returnable:r}:{}}),Ao=e=>{let n=ie(e)?Ue(e):e,{contextVariableDefaultValues:t}=Ct(n??{});return k(t)},xa=()=>({...k(qn)}),va=({loadedRuntime:e,runtimeIds:n,defaults:t={},path:r})=>{if(e===void 0)return{runtimeState:k(t),hasLoadedValues:!1};if(!N(e))throw new Error(`Malformed ${r}.`);let o=k(t),i=!1;return n.forEach(s=>{e[s]!==void 0&&(o[s]=Ra(s,k(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},op=({loadedGlobalRuntime:e={}})=>va({loadedRuntime:e,runtimeIds:Dr,defaults:ln,path:"global.runtime"}).runtimeState,ip=({loadedContextRuntime:e={}})=>{let{runtimeState:n,hasLoadedValues:t}=va({loadedRuntime:e,runtimeIds:Mr,defaults:xa(),path:"context.runtime"});return t?n:void 0},rt=e=>{let n=Array.isArray(e?.contexts)?e.contexts:[];return n[n.length-1]},J=e=>{let n=rt(e);return n?.kind==="sceneReplay"&&N(n.sceneReplay)?n:null},Sa=(e,n)=>{let t=n?.sceneReplay?.replayId,r=e.projectData?.resources?.sceneReplay?.replays?.find(o=>o.id===t);Object.entries(r?.initialVariables??{}).forEach(([o,i])=>{n.variables[o]=k(i)})},sp=e=>({autoMode:e.global.autoMode,skipMode:e.global.skipMode,dialogueUIHidden:e.global.dialogueUIHidden,nextLineConfig:k(e.global.nextLineConfig),overlayStack:k(e.global.overlayStack),confirmDialog:k(e.global.confirmDialog),formDrafts:k(e.global.formDrafts),isLineCompleted:e.global.isLineCompleted,...e.global.isDialogueHistoryShowing===void 0?{}:{isDialogueHistoryShowing:e.global.isDialogueHistoryShowing},...e.global.pendingScreenTransition===void 0?{}:{pendingScreenTransition:k(e.global.pendingScreenTransition)}}),ap=e=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,delete e.global.pendingScreenTransition,e.global.nextLineConfig=et(),e.global.overlayStack=[],e.global.confirmDialog=null,e.global.formDrafts={},e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"})},cp=(e,n)=>{e.global.autoMode=n.autoMode,e.global.skipMode=n.skipMode,e.global.dialogueUIHidden=n.dialogueUIHidden,e.global.nextLineConfig=k(n.nextLineConfig),e.global.overlayStack=k(n.overlayStack),e.global.confirmDialog=k(n.confirmDialog),e.global.formDrafts=k(n.formDrafts),e.global.isLineCompleted=n.isLineCompleted,n.isDialogueHistoryShowing===void 0?delete e.global.isDialogueHistoryShowing:e.global.isDialogueHistoryShowing=n.isDialogueHistoryShowing,n.pendingScreenTransition===void 0?delete e.global.pendingScreenTransition:e.global.pendingScreenTransition=k(n.pendingScreenTransition),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"});let t=Ae({state:e});e.global.autoMode&&e.global.isLineCompleted&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:it({state:e})}}),e.global.skipMode&&!t&&e.global.pendingEffects.push({name:"startSkipNextTimer"}),e.global.nextLineConfig.auto?.enabled&&!t&&(e.global.nextLineConfig.auto.trigger==="fromStart"||e.global.isLineCompleted)&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})},lp=e=>e.runtime?(Mr.forEach(n=>{e.runtime[n]===void 0&&(e.runtime[n]=k(qn[n]))}),e.runtime):(e.runtime=xa(),e.runtime),up=e=>rs(e.global),dp=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:up(e)}})},fp=e=>ts[e],pp=(e,n)=>{let t=fp(e);if(t==="number"){if(typeof n!="number"||!Number.isFinite(n))throw new Error(`${e} requires a finite numeric value`);return}if(t==="boolean"){if(typeof n!="boolean")throw new Error(`${e} requires a boolean value`);return}if(t==="string"){if(typeof n!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},Ra=(e,n)=>{if(pp(e,n),e==="autoForwardSpeed"&&n<=0)throw new Error("autoForwardSpeed requires a value greater than 0");return e==="saveLoadPagination"?Math.max(1,Math.trunc(n)):n},Ca=(e,n,t)=>{let r=Ra(n,t);if(n in qn){let o=rt(e);if(!o)return r;let i=lp(o);return i[n]=r,r}return e.global[n]=r,r},Eo=({pointer:e,projectData:n,kind:t,sceneReplay:r})=>({...t===void 0?{}:{kind:t},...r===void 0?{}:{sceneReplay:k(r)},currentPointerMode:"read",pointers:{read:k(e)},configuration:{},views:[],bgm:Pf(),variables:Ao(n),rollback:Zn({pointer:e})}),Tn=e=>e?(e.currentPointerMode="read",N(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,mp=(e,{queueRender:n=!0}={})=>{let t=e.contexts?.[e.contexts.length-1],r=t?.pointers?.read;if(!t||!r?.sectionId||!r?.lineId)return null;let o=Eo({pointer:r,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,gp(e,{queueRender:n}),o},gp=(e,{queueRender:n=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,On(e),$n(e),e.global.nextLineConfig=et(),e.global.overlayStack=[],e.global.isLineCompleted=!0,bo(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),n&&e.global.pendingEffects.push({name:"render"})},_a=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},Zn=({pointer:e,replayStartIndex:n=0})=>{let t=e?.sectionId&&e?.lineId;return{currentIndex:t?0:-1,isRestoring:!1,replayStartIndex:n,timeline:t?[Gt({sectionId:e.sectionId,lineId:e.lineId})]:[]}},yn=(e,n={})=>{if(e?.rollback)return _a(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 t=e?.pointers?.read;return e.rollback=Zn({pointer:t,replayStartIndex:n.compatibilityAnchor?1:0}),e.rollback},xo=(e,n)=>{let t=e.contexts?.[e.contexts.length-1];if(!t)return;let r=yn(t);r.isRestoring||(r.currentIndex<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,r.currentIndex+1)),r.timeline.push(Gt(n)),r.currentIndex=r.timeline.length-1)},hp=({state:e})=>{let t=e.contexts?.[e.contexts.length-1]?.rollback;return!Array.isArray(t?.timeline)||typeof t.currentIndex!="number"?null:{checkpointIndex:t.currentIndex,checkpoint:t.timeline[t.currentIndex]??null}},yp=({state:e},n={})=>{let{checkpointIndex:t,checkpointIdentity:r,sectionId:o,lineId:i}=n,l=e.contexts?.[e.contexts.length-1]?.rollback;if(!Number.isInteger(t)||!Array.isArray(l?.timeline)||typeof l.currentIndex!="number")return e;let a=l.timeline[t];return(ie(a)?ur(a):a)!==r||a?.sectionId!==o||a?.lineId!==i||(a.returnable=!1),e},bp=({state:e},n={})=>{let{slotId:t,saveSlotIdentity:r,checkpointIndex:o,sectionId:i,lineId:s}=n,l=tt(t),a=e.global.saveSlots?.[l],c=ie(a)?ur(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=fo,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}})),e},Ip=e=>{let t=e.contexts?.[e.contexts.length-1]?.rollback;if(!t||t.isRestoring||!Array.isArray(t.timeline)||typeof t.currentIndex!="number")return null;let r=mn[mn.length-1],o=typeof r?.checkpointIndex=="number"?r.checkpointIndex:t.currentIndex;return o<0||o>=t.timeline.length?null:(typeof r?.checkpointIndex!="number"&&o<t.timeline.length-1&&(t.timeline=t.timeline.slice(0,o+1)),t.timeline[o]??null)},wp=({state:e},n={})=>{let t=n?.source===ta?ta:wo,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?(mn.push({checkpointIndex:null,source:t}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),mn.push({checkpointIndex:o.currentIndex,source:t}),e)},Ap=({state:e})=>(mn.pop(),e),Le=(e,n,t)=>{let o=mn[mn.length-1]?.source??wo;if(!vg(n,o))return;let i=Ip(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:n,payload:k(t)}))},ra=(e,n)=>{let t=e.contexts?.[e.contexts.length-1];if(!t)return;let r=n?.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(Se(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Gn(c,o),_t(u,i,o),Or(u,i,s,o,{roundTo:l}),c==="context"&&(t.variables[o]=kt(t.variables[o],i,s,{roundTo:l}))}},Ep=(e,n)=>{Array.isArray(n?.executedActions)&&n.executedActions.forEach(({type:t,payload:r})=>{Sg(e,t,r)})},xp=(e,n)=>{let{sectionId:t,lineId:r}=n,s=de({state:e},{sectionId:t})?.lines?.find(l=>l.id===r)?.actions;s&&Object.entries(s).forEach(([l,a])=>{sc(e,l,a)})},ka=(e,n)=>{let t=e.contexts?.[e.contexts.length-1];if(!t)return e;let r=yn(t),o=r.timeline[n];if(!o)return e;e.global.autoMode&&at({state:e}),e.global.skipMode&&Je({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=n;try{t.variables=Ao(e.projectData),t.kind==="sceneReplay"&&(Sa(e,t),t.sceneReplay.finishOnNextAdvance=!1,t.sceneReplay.exitOnLineCompleted=!1),delete t.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=k(Ut),e.global.overlayStack=[],On(e),$n(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let l=i;l<=n;l++)l>i&&yo(e),xp(e,r.timeline[l]),Ep(e,r.timeline[l]);let s=Tn(t);s.read={sectionId:o.sectionId,lineId:o.lineId},t.kind==="sceneReplay"&&(t.sceneReplay.entryId=aa(e)),e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},vp=e=>{let{projectData:n}=e,t=e.global??{},{saveSlots:r={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=t;ua(n),jn(n),Fn(n),Un(n),an(n?.resources?.variables??{});let l=n.story.initialSceneId,a=n.story.scenes[l],c=a.initialSectionId,u=a.sections[c],d={sceneId:l,sectionId:c,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:f}=Ct(n),p={...f,...An(o,n.resources?.variables??{})};return{projectData:n,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:jf(s,"accountViewedRegistry"),nextLineConfig:et(),imageGalleryNavigation:po(),sceneReplayNavigation:ho(),sceneReplayEntryId:0,audioCommandId:0,musicRoomPlayer:zt(),saveSlots:Mf(r),overlayStack:[],variables:p,...op({loadedGlobalRuntime:i})},contexts:[Eo({pointer:d,projectData:n})]}},Sp=({state:e})=>e.global.overlayStack||[],Rp=({state:e})=>e.global.pendingEffects,Oa=({state:e})=>e.global.skipMode,Cp=({state:e})=>e.global.autoMode,$a=({state:e})=>e.global.dialogueUIHidden,Ta=({state:e})=>{let n=Array.isArray(e.contexts)?e.contexts:[],t=n[n.length-1];if(!t)return[];let{sectionId:r,lineId:o}=t.pointers.read,i=de({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=Bn({variables:{...e.global?.variables??{},...rt(e)?.variables??{}},runtime:un(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let d of l){let f=d.actions||{};if(c=cn([c,f]),!f.dialogue)continue;let p=c.dialogue||{},g=Rt({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:u}),h=Lf({sectionId:r,lineId:d.id,content:f.dialogue.append===!0?p.content:f.dialogue.content,dialogueState:p,characterName:g});if(f.dialogue.append===!0&&a.length>0){a[a.length-1]={...a[a.length-1],content:h.content,text:h.text,characterId:h.characterId,character:h.character,characterName:h.characterName};continue}a.push(h)}return a},_p=({state:e})=>e.global.confirmDialog??null,ot=({state:e},{pointer:n}={})=>{let t=n??Ce({state:e})?.pointer,r=tp({state:e,pointer:t});return rp({state:e,form:r.form,pointer:t})},kp=({state:e},{pointer:n}={})=>!!ot({state:e},{pointer:n}),Ae=({state:e},{pointer:n}={})=>{let t=ot({state:e},{pointer:n});if(t)return{source:Ke,formId:t.id,formKey:t.key};let r=Ma({state:e,pointer:n});return r?{source:_n,resourceId:r}:null},Op=({state:e,registry:n},t)=>{let{sectionId:r,lineId:o}=t,s=(Array.isArray(n?.sections)?n.sections:[]).find(u=>u.sectionId===r);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let l=de({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},vo=({registry:e},n)=>{let{resourceId:t}=n;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===t)},So=({state:e},n)=>Op({state:e,registry:e.global.accountViewedRegistry},n),$p=({state:e},n)=>vo({registry:e.global.accountViewedRegistry},n),Qn=(e,n)=>!vo({registry:e.global.accountViewedRegistry},{resourceId:n.imageId}),Ro=e=>e.groups.length===0?0:Math.ceil(e.groups.length/e.pageSize),Co=(e,n)=>{let t=Ro(e);if(t===0)return 0;let r=Number.isInteger(n?.pageIndex)?n.pageIndex:0;return Math.min(Math.max(r,0),t-1)},co=(e,n,t,r)=>{for(let o=t+r;o>=0&&o<n.length;o+=r)if(!Qn(e,n[o]))return n[o]},Tp=({state:e})=>{let n=e.projectData?.resources?.imageGallery;return n===void 0?void 0:k(n)},La=({state:e})=>{let n=e.projectData?.resources?.imageGallery;if(n===void 0)return null;let t=e.global.imageGalleryNavigation??po(),r=Ro(n),o=Co(n,t),i=o*n.pageSize,s=n.groups.slice(i,i+n.pageSize).map(a=>({groupId:a.id,locked:Qn(e,a.variants[0]),variants:a.variants.map(c=>({variantId:c.id,imageId:c.imageId,locked:Qn(e,c)}))})),l=null;if(typeof t.groupId=="string"&&typeof t.variantId=="string"){let a=n.groups.findIndex(p=>p.id===t.groupId),c=n.groups[a],u=c?.variants.findIndex(p=>p.id===t.variantId),d=u===void 0||u<0?void 0:c.variants[u],f=a<0?-1:Math.floor(a/n.pageSize);d&&f===o&&!Qn(e,d)&&(l={groupId:c.id,variantId:d.id,imageId:d.imageId,canMoveToPreviousVariant:co(e,c.variants,u,-1)!==void 0,canMoveToNextVariant:co(e,c.variants,u,1)!==void 0})}return{pageGroups:s,selection:l,pagination:{pageIndex:o,pageCount:r,canMoveToPreviousPage:o>0,canMoveToNextPage:o+1<r}}},_o=(e,n)=>!vo({registry:e.global.accountViewedRegistry},{resourceId:n.soundId}),ko=e=>e.tracks.length===0?0:Math.ceil(e.tracks.length/e.pageSize),Oo=(e,n)=>{let t=ko(e);if(t===0)return 0;let r=Number.isInteger(n?.pageIndex)?n.pageIndex:0;return Math.min(Math.max(r,0),t-1)},lo=(e,n,t,r)=>{for(let o=t+r;o>=0&&o<n.length;o+=r)if(!_o(e,n[o]))return n[o]},Pa=e=>({trackId:e.id,soundId:e.soundId,title:e.title,artist:e.artist??null,album:e.album??null,description:e.description??null,coverImageId:e.coverImageId??null}),Lp=(e,n)=>({...Pa(n),locked:_o(e,n)}),oa=e=>{let n=Math.floor(e/1e3),t=n%60,r=Math.floor(n/60);if(r<60)return`${r}:${String(t).padStart(2,"0")}`;let o=Math.floor(r/60),i=r%60;return`${o}:${String(i).padStart(2,"0")}:${String(t).padStart(2,"0")}`},Pp=({state:e})=>{let n=e.projectData?.resources?.musicRoom;return n===void 0?void 0:k(n)},Na=({state:e})=>{let n=e.projectData?.resources?.musicRoom;if(n===void 0)return null;let t=e.global.musicRoomPlayer??zt(),r=ko(n),o=Oo(n,t),i=o*n.pageSize,s=n.tracks.slice(i,i+n.pageSize).map(u=>Lp(e,u)),l=n.tracks.findIndex(u=>u.id===t.trackId),a=n.tracks[l],c=a?{...Pa(a),canPlayPreviousTrack:lo(e,n.tracks,l,-1)!==void 0,canPlayNextTrack:lo(e,n.tracks,l,1)!==void 0}:null;return{pageTracks:s,selection:c,playback:c?{status:t.status,readiness:t.readiness,positionMs:t.positionMs,durationMs:t.durationMs,positionText:oa(t.positionMs),durationText:t.durationMs===null?null:oa(t.durationMs),canPlay:t.status!=="playing",canPause:t.status==="playing",canSeek:t.readiness==="ready"&&t.durationMs!==null}:null,pagination:{pageIndex:o,pageCount:r,canMoveToPreviousPage:o>0,canMoveToNextPage:o+1<r}}},$o=e=>e.replays.length===0?0:Math.ceil(e.replays.length/e.pageSize),To=(e,n)=>{let t=$o(e);if(t===0)return 0;let r=Number.isInteger(n?.pageIndex)?n.pageIndex:0;return Math.min(Math.max(r,0),t-1)},Np=({state:e})=>{let n=e.projectData?.resources?.sceneReplay;return n===void 0?void 0:k(n)},Dp=({state:e})=>J(e)!==null,Mp=({state:e})=>{let n=J(e);return n?{replayId:n.sceneReplay.replayId,entryId:n.sceneReplay.entryId}:null},Da=({state:e})=>{let n=e.projectData?.resources?.sceneReplay;if(n===void 0)return null;let t=e.global.sceneReplayNavigation??ho(),r=$o(n),o=To(n,t),i=o*n.pageSize,s=n.replays.slice(i,i+n.pageSize).map(a=>({replayId:a.id,title:a.title,thumbnailImageId:a.thumbnailImageId})),l=J(e);return{isActive:l!==null,activeReplayId:l?.sceneReplay.replayId??null,pageReplays:s,pagination:{pageIndex:o,pageCount:r,canMoveToPreviousPage:o>0,canMoveToNextPage:o+1<r}}},Vp=({state:e})=>e.global.nextLineConfig,Ma=({state:e,pointer:n}={})=>{let t=n??Ce({state:e})?.pointer;if(!t)return;let r=t?.sectionId,o=t?.lineId,s=de({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},Va=({state:e})=>!!Ma({state:e}),jp=({state:e})=>structuredClone(e),Fp=({state:e})=>k(e.projectData.resources?.achievements??{}),Up=({state:e},n)=>{let t=e.projectData.resources?.achievements?.[n?.resourceId];return t===void 0?void 0:k(t)},ja=({state:e})=>e.global.saveSlots,Bp=({state:e},n)=>{let t=n?.slotId,r=tt(t);return e.global.saveSlots[r]},Lo=({state:e})=>un(e),Gp=({state:e},n)=>Ye(e,n?.runtimeId),Yt=({state:e})=>{let n={...e.global?.variables??{},...rt(e)?.variables??{}};return Bn({variables:n,runtime:un(e),variableConfigs:e.projectData.resources?.variables??{}})},Ce=({state:e})=>{let n=Array.isArray(e.contexts)?e.contexts:[],t=n[n.length-1];if(t)return{currentPointerMode:"read",pointer:t.pointers?.read}},de=({state:e},n)=>{let{sectionId:t}=n;return hn(e.projectData,t).section},Ht=({state:e})=>{let n=Ce({state:e});if(!n?.pointer)return;let{sectionId:t,lineId:r}=n.pointer,o=de({state:e},{sectionId:t});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},Fa=({state:e})=>{let{sectionId:n,lineId:t}=Ce({state:e}).pointer,o=de({state:e},{sectionId:n})?.lines||[],i=o.findIndex(c=>c.id===t),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 cn(l)},zp=e=>{let n=Ht({state:e})?.actions?.dialogue;if(n?.clear===!0||!Array.isArray(n?.content))return"";let t=Yt({state:e});return n.content.map(r=>`${En(r?.text,{variables:t})??""}`).join("")},it=({state:e})=>Zs({text:zp(e),baseDelay:Ye(e,"autoForwardDelay"),speed:Ye(e,"autoForwardSpeed")}),qp=({state:e})=>{let n=Ua({state:e}),r=Ht({state:e})?.actions??{},o=cn([n??{},r]);return Tr(n??{},o??{})},Yp=({state:e},{sectionId:n})=>{let t=de({state:e},{sectionId:n});if(!t?.lines)return[];let r=[],o={};for(let i of t.lines){let s=i.actions||{},l=cn([o,s]),a=Tr(o,l);r.push({id:i.id,changes:a,presentationState:l}),o=Lr(l)}return r},Hp=({state:e},{sectionId:n,includePresentationState:t=!1})=>{let r=Yp({state:e},{sectionId:n});return t?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},Ua=({state:e})=>{let{sectionId:n,lineId:t}=Ce({state:e}).pointer,o=de({state:e},{sectionId:n})?.lines||[],i=o.findIndex(a=>a.id===t);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 Lr(cn(l))},Po=({state:e},{slotsPerPage:n=6}={})=>{let o=((Lo({state:e}).saveLoadPagination??1)-1)*n+1,i=[];for(let s=0;s<n;s++){let l=o+s,a=e.global.saveSlots&&e.global.saveSlots[tt(l)]||{};i.push({...a,slotId:l})}return{saveSlots:i}},Wp=ja,Kp=Po,Jp=e=>{let t=e.contexts?.[e.contexts.length-1]?.rollback;return!t||!Array.isArray(t.timeline)||typeof t.currentIndex!="number"?!1:t.currentIndex>=0&&t.currentIndex<t.timeline.length-1},Xp=({state:e},n={})=>{let t=Fa({state:e}),r=Ua({state:e}),o=Ht({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:k(i)}:o,l=i?.animations&&r===null?{}:r,{sectionId:a}=Ce({state:e}).pointer,{sceneId:c}=hn(e.projectData,a),u=Lo({state:e}),d=n?.activePersistentAnimations??[],f=n?.restoredPersistentAnimations??[],p=ot({state:e}),g=Va({state:e}),h=La({state:e}),b=Na({state:e}),I=Da({state:e}),E=Yt({state:e}),{saveSlots:A}=Po({state:e}),$=Jp(e);return Ps({presentationState:t,previousPresentationState:l,currentLineActions:s,resources:e.projectData.resources,currentSceneId:c,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:g,isFormVisible:!!p,canRollback:lc({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||$,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:Ta({state:e}),saveSlots:A,variables:E,runtime:u,activePersistentAnimations:d,restoredPersistentAnimations:f,imageGallery:h,musicRoom:b,sceneReplay:I,musicRoomPlayer:k(e.global.musicRoomPlayer)})},Qp=({state:e},n)=>(e.global.confirmDialog=Kf(n),e.global.pendingEffects.push({name:"render"}),e),Zp=({state:e})=>(e.global.confirmDialog&&(On(e),e.global.pendingEffects.push({name:"render"})),e),em=({state:e},n)=>(e.global.overlayStack.push(n),e.global.pendingEffects.push({name:"render"}),Le(e,"pushOverlay",n),e),nm=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Le(e,"popOverlay",void 0),e),tm=({state:e},n)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=n),e.global.pendingEffects.push({name:"render"}),Le(e,"replaceLastOverlay",n),e),rm=({state:e})=>(e.global.overlayStack=[],On(e),$n(e),e.global.pendingEffects.push({name:"render"}),Le(e,"clearOverlays",void 0),e),om=(e,{activeInteraction:n})=>{e.global.autoMode&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),n&&e.global.skipMode&&e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},st=(e,n,{screenTransition:t}={})=>{e.global.isLineCompleted=!1,Xf(e,t),$n(e);let r=Ae({state:e},{pointer:n}),o=r?.source===_n,i=r?.source===Ke;om(e,{activeInteraction:r});let s=J(e),l={name:"handleLineActions"};if(typeof s?.sceneReplay?.replayId=="string"){let a=aa(e);s.sceneReplay.entryId=a,l.payload={sceneReplayId:s.sceneReplay.replayId,entryId:a}}return e.global.pendingEffects.push(l),{isChoiceVisible:o,isFormVisible:i,activeInteraction:r}},Wt=(e,n,t)=>{!(n?.source===_n||n?.source===Ke)||t||!e.global.skipMode||e.global.pendingEffects.push({name:"startSkipNextTimer"})},Ba=({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:it({state:e})}}),e.global.pendingEffects.push({name:"render"})),e),at=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),im=({state:e})=>{let n=e.global.autoMode;return Ae({state:e})&&!n||(n?at({state:e}):Ba({state:e})),e},Ga=({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),Je=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),sm=({state:e})=>{let n=Oa({state:e});return Ae({state:e})&&!n||(n?Je({state:e}):Ga({state:e})),e},Kt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Le(e,"showDialogueUI",void 0),e),za=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Le(e,"hideDialogueUI",void 0),e),am=({state:e})=>($a({state:e})?Kt({state:e}):za({state:e}),e),Xe=(e,n,t)=>(Ca(e,n,t),dp(e),e.global.pendingEffects.push({name:"render"}),e),ct=(e,n,t,r)=>{let o=Ca(e,n,t);return e.global.pendingEffects.push({name:"render"}),Le(e,r,{value:o}),e},cm=({state:e},n)=>Xe(e,"dialogueTextSpeed",n?.value),lm=({state:e},n)=>Xe(e,"autoForwardDelay",n?.value),um=({state:e},n)=>Xe(e,"autoForwardSpeed",n?.value),dm=({state:e},n)=>Xe(e,"skipUnseenText",n?.value),fm=({state:e},n)=>Xe(e,"skipTransitionsAndAnimations",n?.value),pm=({state:e},n)=>Xe(e,"soundVolume",n?.value),mm=({state:e},n)=>Xe(e,"musicVolume",n?.value),gm=({state:e},n)=>Xe(e,"muteAll",n?.value),hm=({state:e},n)=>ct(e,"saveLoadPagination",n?.value,"setSaveLoadPagination"),ym=({state:e})=>{let n=Ye(e,"saveLoadPagination")+1;return ct(e,"saveLoadPagination",n,"incrementSaveLoadPagination"),e},bm=({state:e})=>{let n=Ye(e,"saveLoadPagination")-1;return ct(e,"saveLoadPagination",n,"decrementSaveLoadPagination"),e},Im=({state:e},n)=>ct(e,"menuPage",n?.value,"setMenuPage"),wm=({state:e},n)=>ct(e,"menuEntryPoint",n?.value,"setMenuEntryPoint"),Am=({state:e})=>(e.global.pendingEffects=[],e),Em=({state:e},n)=>(e.global.pendingEffects.push(n),e),xm=({state:e},n)=>{if(J(e))return e;let t=n?.resourceId;return ca(e,t),e.global.pendingEffects.push({name:"completeAchievement",payload:{resourceId:t}}),e},vm=({state:e},n)=>{if(J(e))return e;let t=n?.resourceId,r=ca(e,t);if(r.type!=="number")throw new Error(`Achievement resource "${t}" does not support numeric progress`);let o=n?.current;if(!Number.isInteger(o)||o<0)throw new Error(`Achievement progress for "${t}" must be a non-negative integer`);if(!Number.isInteger(r.target)||r.target<1)throw new Error(`Achievement resource "${t}" must have a positive integer target`);let i=Math.min(o,r.target);return e.global.pendingEffects.push({name:"setAchievementProgress",payload:{resourceId:t,current:i,target:r.target,completed:i>=r.target}}),e},qa=(e,{sectionId:n,resetStoryState:t=!1,screen:r})=>{let o=!!wa(r),i=de({state:e},{sectionId:n});if(!i)return console.warn(`Section not found: ${n}`),e;let s=i.lines?.[0];if(!s)return console.warn(`Section ${n} has no lines`),e;if(t&&!mp(e,{queueRender:!o}))return e;let l=Ae({state:e});t&&e.global.skipMode&&Je({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let u=Tn(a),d=u.read;t||gn(e,{sectionId:d?.sectionId,lineId:d?.lineId}),a.rollback||yn(a,{compatibilityAnchor:!0}),u.read={sectionId:n,lineId:s.id},t?a.rollback=Zn({pointer:u.read}):xo(e,{sectionId:n,lineId:s.id})}let{activeInteraction:c}=st(e,a?.pointers?.read,{screenTransition:r});return Wt(e,l,c),e},Sm=({state:e},n)=>{if(J(e))throw new Error("Cannot reset the story while a scene replay is active");return qa(e,{sectionId:n?.sectionId,resetStoryState:!0,screen:n?.screen})},Ya=e=>(e.global.accountViewedRegistry=$f(e.global.accountViewedRegistry),e.global.accountViewedRegistry),No=(e,n)=>{!Array.isArray(n)||n.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:n.map(t=>({scope:t.scope,path:t.path,op:t.op,value:k(t.value)}))}})},Ha=(e,n)=>{No(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(n?.sections)?n.sections:[]).map(t=>({sectionId:t.sectionId,...t.lastLineId===void 0?{}:{lineId:t.lastLineId}})),resources:Array.isArray(n?.resources)?n.resources:[]}}])},Rm=(e,n,{sectionId:t,lineId:r})=>{if(!t||!r)return!1;let o=N(n)?n:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===t);if(i){if(i.lastLineId===void 0)return!1;let s=de({state:e},{sectionId:t});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:t,lastLineId:r}),!0},gn=(e,n)=>{if(J(e)||e.global.accountViewedRegistry===void 0)return;Rm(e,Ya(e),n)&&Ha(e,{sections:[{sectionId:n.sectionId,lastLineId:n.lineId}],resources:[]})},Cm=({state:e},n)=>(gn(e,n),e.global.pendingEffects.push({name:"render"}),e),_m=({state:e},n)=>{if(J(e))return e;let{resourceId:t}=n;if(e.global.accountViewedRegistry!==void 0){let r=Ya(e);r.resources.find(i=>i.resourceId===t)||(r.resources.push({resourceId:t}),Ha(e,{sections:[],resources:[{resourceId:t}]}))}return e.global.pendingEffects.push({name:"render"}),e},Pe=(e,n,t)=>{if(!N(n))throw new Error(`${e} payload must be an object`);Object.keys(n).forEach(r=>{if(!t.has(r))throw new Error(`${e} payload contains unsupported property "${r}"`)})},uo=(e,n,t)=>{if(typeof t!="string"||t.length===0)throw new Error(`${e} requires a non-empty ${n}`)},Jt=(e,n)=>{let t=e.global.imageGalleryNavigation;t.groupId===n.groupId&&t.variantId===n.variantId&&t.pageIndex===n.pageIndex||(e.global.imageGalleryNavigation=n,e.global.pendingEffects.push({name:"render"}))},km=({state:e},n)=>{let t="showImageGalleryVariant";Pe(t,n,vf),uo(t,"groupId",n.groupId),Object.prototype.hasOwnProperty.call(n,"variantId")&&uo(t,"variantId",n.variantId);let r=e.projectData?.resources?.imageGallery;if(r===void 0)return e;let o=r.groups.findIndex(l=>l.id===n.groupId),i=r.groups[o];if(!i)return e;let s=n.variantId===void 0?i.variants[0]:i.variants.find(l=>l.id===n.variantId);return!s||Qn(e,s)||Jt(e,{groupId:i.id,variantId:s.id,pageIndex:Math.floor(o/r.pageSize)}),e},Wa=(e,n,t,r)=>{Pe(r,n,mo);let o=e.projectData?.resources?.imageGallery;if(o===void 0)return e;let i=e.global.imageGalleryNavigation;if(typeof i.groupId!="string"||typeof i.variantId!="string")return e;let s=o.groups.find(c=>c.id===i.groupId),l=s?.variants.findIndex(c=>c.id===i.variantId);if(!s||l===void 0||l<0)return e;let a=co(e,s.variants,l,t);return a&&Jt(e,{...i,variantId:a.id}),e},Om=({state:e},n)=>Wa(e,n,-1,"moveToPreviousImageGalleryVariant"),$m=({state:e},n)=>Wa(e,n,1,"moveToNextImageGalleryVariant"),Tm=({state:e},n)=>{if(Pe("clearImageGallerySelection",n,mo),e.projectData?.resources?.imageGallery===void 0)return e;let r=e.global.imageGalleryNavigation;return Jt(e,{groupId:null,variantId:null,pageIndex:r.pageIndex}),e},Ka=(e,n)=>{let t=e.projectData?.resources?.imageGallery;if(t===void 0)return e;let r=Ro(t);if(n>=r)return e;let o=e.global.imageGalleryNavigation,i=Co(t,o);return n===i||Jt(e,{groupId:null,variantId:null,pageIndex:n}),e},Lm=({state:e},n)=>{if(Pe("moveToImageGalleryPage",n,Sf),!Number.isInteger(n.pageIndex)||n.pageIndex<0)throw new Error("moveToImageGalleryPage requires a non-negative integer pageIndex");return Ka(e,n.pageIndex)},Ja=(e,n,t,r)=>{Pe(r,n,mo);let o=e.projectData?.resources?.imageGallery;if(o===void 0)return e;let s=Co(o,e.global.imageGalleryNavigation)+t;return s<0?e:Ka(e,s)},Pm=({state:e},n)=>Ja(e,n,1,"moveToNextImageGalleryPage"),Nm=({state:e},n)=>Ja(e,n,-1,"moveToPreviousImageGalleryPage"),Fe=(e,n,t)=>{if(!N(n))throw new Error(`${e} payload must be an object`);Object.keys(n).forEach(r=>{if(!t.has(r))throw new Error(`${e} payload contains unsupported property "${r}"`)})},Dm=(e,n)=>{if(typeof n!="string"||n.length===0)throw new Error(`${e} requires a non-empty trackId`)},Oe=e=>{e.global.pendingEffects.push({name:"render"})},Xa=(e,n)=>{let t=e.projectData.resources.musicRoom,r=e.global.musicRoomPlayer,o=r.trackId!==null,i=r.trackId===n.id,s=r.bgmPlayback;o||(s={commandId:qt(e),operation:"pause"});let l=nt(e,"play",0),a=t.tracks.indexOf(n),c=i?r.durationMs:null;e.global.musicRoomPlayer={trackId:n.id,pageIndex:Math.floor(a/t.pageSize),status:"playing",readiness:c===null?"loading":"ready",positionMs:0,durationMs:c,playback:l,seekFallback:null,bgmPlayback:s},Oe(e)},Mm=({state:e},n)=>{let t="playMusicRoomTrack";Fe(t,n,Rf),Dm(t,n.trackId);let o=e.projectData?.resources?.musicRoom?.tracks.find(i=>i.id===n.trackId);return!o||_o(e,o)||Xa(e,o),e},Vm=({state:e},n)=>{Fe("playMusicRoom",n,kn);let r=e.global.musicRoomPlayer;if(r.trackId===null||r.status==="playing")return e;let o=r.status==="ended",i=r.readiness==="error",s=r.status==="paused"&&!i?"resume":"play",l=o?0:r.positionMs;return r.playback=nt(e,s,s==="play"?l:void 0),r.seekFallback=null,r.status="playing",r.positionMs=l,i&&(r.readiness=r.durationMs===null?"loading":"ready"),Oe(e),e},jm=({state:e},n)=>{Fe("pauseMusicRoom",n,kn);let r=e.global.musicRoomPlayer;return r.trackId===null||r.status!=="playing"||(r.playback=nt(e,"pause"),r.seekFallback=null,r.status="paused",Oe(e)),e},Fm=({state:e},n)=>{Fe("stopMusicRoom",n,kn);let r=e.global.musicRoomPlayer;return r.trackId===null||r.status==="stopped"&&r.positionMs===0||(r.playback=nt(e,"stop"),r.seekFallback=null,r.status="stopped",r.positionMs=0,Oe(e)),e},Um=({state:e},n)=>{if(Fe("seekMusicRoom",n,Cf),typeof n.positionMs!="number"||!Number.isFinite(n.positionMs)||n.positionMs<0)throw new Error("seekMusicRoom requires a finite non-negative positionMs");let r=e.global.musicRoomPlayer;if(r.trackId===null||r.readiness!=="ready"||r.durationMs===null||n.positionMs>r.durationMs)return e;let o=nt(e,"seek",n.positionMs);return r.seekFallback={commandId:o.commandId,status:r.status,positionMs:r.positionMs},r.playback=o,r.positionMs=n.positionMs,n.positionMs===r.durationMs?r.status="ended":r.status==="ended"&&(r.status="stopped"),Oe(e),e},Qa=(e,n,t,r)=>{Fe(r,n,kn);let o=e.projectData?.resources?.musicRoom,i=e.global.musicRoomPlayer;if(!o||i.trackId===null)return e;let s=o.tracks.findIndex(a=>a.id===i.trackId);if(s<0)return e;let l=lo(e,o.tracks,s,t);return l&&Xa(e,l),e},Bm=({state:e},n)=>Qa(e,n,-1,"playPreviousMusicRoomTrack"),Gm=({state:e},n)=>Qa(e,n,1,"playNextMusicRoomTrack"),zm=({state:e},n)=>{Fe("clearMusicRoomSelection",n,kn);let r=e.global.musicRoomPlayer;if(r.trackId===null)return e;let o=r.pageIndex,i={commandId:qt(e),operation:"resume"};return e.global.musicRoomPlayer={...zt({bgmPlayback:i}),pageIndex:o},Oe(e),e},Za=(e,n)=>{let t=e.projectData?.resources?.musicRoom;if(!t||n>=ko(t))return e;let r=e.global.musicRoomPlayer,o=Oo(t,r);return n===o||(r.pageIndex=n,Oe(e)),e},qm=({state:e},n)=>{if(Fe("moveToMusicRoomPage",n,_f),!Number.isInteger(n.pageIndex)||n.pageIndex<0)throw new Error("moveToMusicRoomPage requires a non-negative integer pageIndex");return Za(e,n.pageIndex)},ec=(e,n,t,r)=>{Fe(r,n,kn);let o=e.projectData?.resources?.musicRoom;if(!o)return e;let i=Oo(o,e.global.musicRoomPlayer)+t;return i<0?e:Za(e,i)},Ym=({state:e},n)=>ec(e,n,1,"moveToNextMusicRoomPage"),Hm=({state:e},n)=>ec(e,n,-1,"moveToPreviousMusicRoomPage"),pn=e=>{let n=J(e);if(!n)return!1;if(e.contexts.length<2)throw new Error("Scene replay context has no caller context to restore");let t=k(n.sceneReplay.returnState),r=n.sceneReplay.replayId;return e.global.pendingEffects=e.global.pendingEffects.filter(o=>o?.name!=="handleLineActions"||o?.payload?.sceneReplayId!==r),e.contexts.pop(),cp(e,t),e.global.pendingEffects.push({name:"render"}),!0},Wm=({state:e},n)=>{let t="startSceneReplay";if(Pe(t,n,kf),uo(t,"replayId",n.replayId),J(e))throw new Error("Cannot start a scene replay while another replay is active");let o=e.projectData?.resources?.sceneReplay?.replays.find(u=>u.id===n.replayId);if(!o)return e;let{sceneId:i,section:s}=hn(e.projectData,o.startSectionId),l=s?.initialLineId??s?.lines?.[0]?.id;if(!s||!l||!s.lines.some(u=>u.id===l))throw new Error(`Scene replay "${o.id}" has an invalid start section`);let a=sp(e);ap(e);let c=Eo({pointer:{sceneId:i,sectionId:o.startSectionId,lineId:l},projectData:e.projectData,kind:"sceneReplay",sceneReplay:{replayId:o.id,entryId:0,finishOnNextAdvance:!1,exitOnLineCompleted:!1,returnState:a}});return Sa(e,c),e.contexts.push(c),st(e,c.pointers.read),e},nc=({state:e},n)=>{Pe("finishSceneReplay",n,go);let r=J(e);return r&&(r.sceneReplay.finishOnNextAdvance=!0),e},Km=({state:e},n)=>(Pe("exitSceneReplay",n,go),pn(e),e),tc=(e,n)=>{let t=e.projectData?.resources?.sceneReplay;if(!t||n>=$o(t))return e;let r=To(t,e.global.sceneReplayNavigation);return n===r||(e.global.sceneReplayNavigation.pageIndex=n,e.global.pendingEffects.push({name:"render"})),e},Jm=({state:e},n)=>{if(Pe("moveToSceneReplayPage",n,Of),!Number.isInteger(n.pageIndex)||n.pageIndex<0)throw new Error("moveToSceneReplayPage requires a non-negative integer pageIndex");return tc(e,n.pageIndex)},rc=(e,n,t,r)=>{Pe(r,n,go);let o=e.projectData?.resources?.sceneReplay;if(!o)return e;let i=To(o,e.global.sceneReplayNavigation)+t;return i<0?e:tc(e,i)},Xm=({state:e},n)=>rc(e,n,1,"moveToNextSceneReplayPage"),Qm=({state:e},n)=>rc(e,n,-1,"moveToPreviousSceneReplayPage"),Xt=(e,n)=>{let t=e.global.musicRoomPlayer;return!N(n)||n.id!==Ef||t.trackId===null||!t.playback||n.commandId!==t.playback.commandId?null:t},Do=e=>typeof e.positionMs=="number"&&Number.isFinite(e.positionMs)&&e.positionMs>=0&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>0&&e.positionMs<=e.durationMs,oc=(e,n,t,{readiness:r=n.readiness}={})=>((n.readiness!==r||n.positionMs!==t.positionMs||n.durationMs!==t.durationMs||n.seekFallback!==null)&&(n.readiness=r,n.positionMs=t.positionMs,n.durationMs=t.durationMs,n.seekFallback=null,Oe(e)),e),Zm=({state:e},n)=>{let t=Xt(e,n);return!t||t.readiness!=="loading"||!Do(n)?e:oc(e,t,n,{readiness:"ready"})},eg=({state:e},n)=>{let t=Xt(e,n);return!t||t.readiness!=="ready"||!Do(n)||t.status==="stopped"&&n.positionMs!==0||t.status==="ended"&&n.positionMs!==n.durationMs?e:oc(e,t,n)},ng=({state:e},n)=>{let t=Xt(e,n);return!t||t.readiness!=="ready"||t.status!=="playing"||!Do(n)||n.positionMs!==n.durationMs||(t.status="ended",t.positionMs=n.positionMs,t.durationMs=n.durationMs,t.seekFallback=null,Oe(e)),e},tg=({state:e},n)=>{let t=Xt(e,n);if(!t||typeof n.errorCode!="string"||!xf.has(n.errorCode)||t.readiness==="error"&&t.status==="stopped")return e;if(n.errorCode==="invalid-position"){let r=t.seekFallback;if(t.playback.operation!=="seek"||r?.commandId!==n.commandId)return e;let o=t.status!==r.status||t.positionMs!==r.positionMs;return t.status=r.status,t.positionMs=r.positionMs,t.seekFallback=null,o&&Oe(e),e}return t.readiness="error",t.status="stopped",t.positionMs=0,t.seekFallback=null,Oe(e),e},ic=({state:e},n)=>{let t=Nf(n.manual),{auto:r,applyMode:o}=n,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;t&&r?(e.global.nextLineConfig={manual:t,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(t&&(e.global.nextLineConfig.manual=t),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"}),Le(e,"setNextLineConfig",n),e},rg=({state:e},n)=>{if(J(e))throw new Error("Cannot save while a scene replay is active");let t=n?.slotId;if(t==null||t==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:r}=n,o=n?.savedAt,i=tt(t),s=k(e.contexts);s?.forEach(c=>{Tn(c),_a(c.rollback),Vf(c.rollback)});let l={contexts:s},a={formatVersion:sa,slotId:da(t),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},og=({state:e},n)=>{if(J(e))throw new Error("Cannot load while a scene replay is active");let t=n?.slotId;if(t==null||t==="")throw new Error("loadSlot requires slotId");let r=tt(t),o=e.global.saveSlots[r];if(o){let i=Wf(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=et(),e.global.overlayStack=[],e.global.isLineCompleted=!0,On(e),$n(e),bo(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},ig=({state:e},n)=>{if(J(e))throw new Error("Cannot update project data while a scene replay is active");let{projectData:t}=n;ua(t),jn(t),Fn(t),Un(t),an(t?.resources?.variables??{}),e.projectData=t,e.global.imageGalleryNavigation=po(),e.global.sceneReplayNavigation=ho(),bo(e);let r=t?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=Ct(t??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...An(e.global.variables,r)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...An(s.variables,r)})}),On(e),$n(e),e.global.pendingEffects.push({name:"render"}),e},sg=({state:e},n)=>{let{sectionId:t,lineId:r}=n;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=t||o.pointers.read?.sectionId;if(t&&!de({state:e},{sectionId:t}))return console.warn(`Section not found: ${t}`),e;let s=de({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=Tn(o);c.read={sectionId:i,lineId:r};let{activeInteraction:u}=st(e,c.read);return Wt(e,a,u),e},ag=({state:e},n)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return Kt({state:e}),e;let t=Ae({state:e});if(t?.source===_n&&n?.bypassChoice!==!0||t?.source===Ke&&n?._interactionSource!==Ke)return e;if(!e.global.isLineCompleted){if(e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition,J(e)?.sceneReplay.exitOnLineCompleted)return pn(e),e;let f=Ce({state:e})?.pointer,p=f?.sectionId,g=f?.lineId;p&&g&&gn(e,{sectionId:p,lineId:g}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:it({state:e})}});let h=e.global.nextLineConfig;return h?.auto?.enabled&&!t&&h.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:h.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}if(J(e)?.sceneReplay.finishOnNextAdvance)return pn(e),e;let o=Ce({state:e})?.pointer,i=o?.sectionId,s=de({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=!Ye(e,"skipUnseenText");if(e.global.skipMode&&f&&!So({state:e},{sectionId:i,lineId:d.id}))return Je({state:e}),e;if(l&&!l.rollback&&yn(l,{compatibilityAnchor:!0}),l){let g=Tn(l),h=g.read?.lineId;h&&i&&gn(e,{sectionId:i,lineId:h}),g.read={sectionId:i,lineId:d.id}}xo(e,{sectionId:i,lineId:d.id}),yo(e);let{activeInteraction:p}=st(e,{sectionId:i,lineId:d.id});Wt(e,t,p)}else{if(J(e))return console.warn("Scene replay reached the end of a section without finishSceneReplay; exiting replay."),pn(e),e;e.global.autoMode&&at({state:e}),e.global.skipMode&&Je({state:e})}return e},cg=({state:e})=>{if(e.global.isLineCompleted)return e;if(e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition,J(e)?.sceneReplay.exitOnLineCompleted)return pn(e),e;let t=Ae({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:it({state:e})}});let r=Ce({state:e})?.pointer,o=r?.sectionId,i=r?.lineId;o&&i&&gn(e,{sectionId:o,lineId:i});let s=e.global.nextLineConfig;return s?.auto?.enabled&&!t&&s.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:s.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},lg=({state:e},n)=>qa(e,{sectionId:n?.sectionId,screen:n?.screen}),ug=({state:e},n)=>{let t=n?._conditionalContinuation===!0;if(e.global.dialogueUIHidden&&!t)return Kt({state:e}),e;let r=Ae({state:e});if(r?.source===_n&&n?.bypassChoice!==!0||r?.source===Ke&&n?._interactionSource!==Ke||r&&r.source!==_n&&r.source!==Ke)return e;let o=J(e);if(o?.sceneReplay.finishOnNextAdvance)return e.global.isLineCompleted?(pn(e),e):(o.sceneReplay.exitOnLineCompleted=!0,e);let i=Ce({state:e})?.pointer,s=i?.sectionId,l=de({state:e},{sectionId:s}),a=e.contexts[e.contexts.length-1],c=l?.lines||[],d=c.findIndex(f=>f.id===i?.lineId)+1;if(d<c.length){let f=c[d],p=!Ye(e,"skipUnseenText");if(e.global.skipMode&&p&&!So({state:e},{sectionId:s,lineId:f.id})&&(Je({state:e}),!t))return e;if(a&&!a.rollback&&yn(a,{compatibilityAnchor:!0}),a){let h=Tn(a),b=h.read?.lineId;b&&s&&gn(e,{sectionId:s,lineId:b}),h.read={sectionId:s,lineId:f.id}}xo(e,{sectionId:s,lineId:f.id}),yo(e);let{activeInteraction:g}=st(e,{sectionId:s,lineId:f.id});Wt(e,r,g)}else{if(J(e))return console.warn("Scene replay reached the end of a section without finishSceneReplay; exiting replay."),pn(e),e;e.global.autoMode&&at({state:e}),e.global.skipMode&&Je({state:e}),e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}))}return e},Mo=(e,n={})=>{let t=ot({state:e});return!t||n.formKey&&n.formKey!==t.key||n.formId&&n.formId!==t.id?null:t},dg=(e,n)=>{if(!n.variableId)throw new Error(`form field "${n.id}" requires variableId`);let t=e.projectData.resources?.variables?.[n.variableId],r=t?.scope,o=t?.type;if(Se(t))throw new Error(`Cannot update computed variable: ${n.variableId}`);if(t?.readonly===!0)throw new Error(`Cannot update readonly variable: ${n.variableId}`);if(Gn(r,n.variableId),_t(o,"set",n.variableId),J(e)&&r!=="context")throw new Error(`Cannot update ${r}-scoped variable "${n.variableId}" while a scene replay is active`);return{variableConfig:t,scope:r}},fg=(e,n)=>({id:e.id,key:e.key,valid:!0,values:k(n),fields:k(e.fields),fieldList:k(e.fieldList)}),pg=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let n=Ce({state:e})?.pointer,t=n?.sectionId,r=n?.lineId;t&&r&&gn(e,{sectionId:t,lineId:r})},mg=({state:e},n={})=>{let t=Mo(e,n),r=n.field;if(!t?.fields?.[r])return e;let o=Ea(e,t.key),i=Bt(n.value),s=t.fields[r],l=Io(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},gg=({state:e},n={})=>{let t=Mo(e,n);if(!t)return{submitted:!1,valid:!1,reason:"inactive"};let r=Ea(e,t.key);r.submitted=!0;let o={},i={};if(Object.entries(t.fields).forEach(([d,f])=>{let p=Object.prototype.hasOwnProperty.call(r.values,d)?r.values[d]:f.value,g=Io(f,p);r.touched[d]=!0,g&&(i[d]=g),o[d]=Aa(f,p)}),r.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:k(i),form:{id:t.id,key:t.key,values:k(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let l=!1,a=[],c=[];Object.entries(t.fields).forEach(([d,f])=>{let{scope:p}=dg(e,f),g=p==="context"?s.variables:e.global.variables,h=o[d];g[f.variableId]=kt(g[f.variableId],"set",h),p==="context"&&(l=!0,c.push({variableId:f.variableId,op:"set",value:h})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${f.variableId}`,op:"set",value:k(g[f.variableId])})}),l&&Le(e,"updateVariable",{id:"submitForm",operations:c}),No(e,a);let u=fg(t,o);return pg(e),delete e.global.formDrafts[t.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},hg=({state:e},n={})=>{let t=Mo(e,n);return t?(delete e.global.formDrafts?.[t.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:t.id,key:t.key,values:k(t.values),fields:k(t.fields),fieldList:k(t.fieldList)}}):{cancelled:!1,reason:"inactive"}},yg=({state:e},n)=>{let{id:t,operations:r=[]}=n;if(!t)throw new Error("updateVariable requires an id field");if(typeof t!="string"||!/^[a-zA-Z0-9]+$/.test(t))throw new Error(`updateVariable id must be alphanumeric, got: "${t}"`);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,g=f?.type;if(Se(f))throw new Error(`Cannot update computed variable: ${a}`);if(f?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);if(Gn(p,a),_t(g,c,a),Or(g,c,u,a,{roundTo:d}),J(e)&&p!=="context")throw new Error(`Cannot update ${p}-scoped variable "${a}" while a scene replay is active`);let h=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)}h[a]=kt(h[a],c,u,{roundTo:d}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:k(h[a])})}),i&&Le(e,"updateVariable",{id:t,operations:l}),No(e,s),e.global.pendingEffects.push({name:"render"}),e},ia=e=>(n,t)=>e({state:n},t),bg=e=>({variables:Bn({variables:{...e.global?.variables??{},...rt(e)?.variables??{}},runtime:un(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:un(e)}),Ig=e=>{if(!N(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")},wg=(e,n,t)=>{if(!N(e))throw new Error(`conditional branch at index ${n} must be an object`);if(!N(e.actions))throw new Error(`conditional branch at index ${n} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&n!==t-1)throw new Error("conditional else branch must be the last branch")},Ag=(e,n)=>{Ig(n);for(let t=0;t<n.branches.length;t+=1){let r=n.branches[t];if(wg(r,t,n.branches.length),!(Object.prototype.hasOwnProperty.call(r,"when")&&!Vn(r.when,bg(e)))){Object.entries(r.actions).forEach(([i,s])=>{sc(e,i,s)});return}}},Eg={conditional:{replayLine:Ag},updateVariable:{recordSources:[wo],replayLine:ra,replayRecorded:ra,persistInSaveSlot:!0},setNextLineConfig:{replayLine:ia(ic)},finishSceneReplay:{replayLine:ia(nc)}},Qt=e=>Eg[e]??null,xg=e=>Qt(e)?.persistInSaveSlot===!0,vg=(e,n)=>{let t=Qt(e)?.recordSources;return Array.isArray(t)&&t.includes(n)},Sg=(e,n,t)=>{Qt(n)?.replayRecorded?.(e,t)},sc=(e,n,t)=>{Qt(n)?.replayLine?.(e,t)},Rg=e=>e?.returnable!==!1,ac=(e,n)=>{if(n>=0)return e.currentIndex+n;let t=Math.abs(n);for(let r=e.currentIndex-1;r>=0;r-=1)if(Rg(e.timeline[r])&&(t-=1,t===0))return r;return-1},cc=({state:e},n)=>{let{offset:t}=n;if(t===void 0||typeof t!="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=ac(o,t);if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},lc=({state:e})=>cc({state:e},{offset:-1})!==null,Cg=({state:e},n)=>{let{offset:t=-1}=n;if(t>=0)throw new Error("rollbackByOffset requires a negative offset");let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let o=yn(r,{compatibilityAnchor:!r.rollback}),i=ac(o,t);return i<0||i>=o.timeline.length?e:ka(e,i)},_g=({state:e},n)=>{let{sectionId:t,lineId:r}=n,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=yn(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===t&&a.lineId===r);if(l===-1)throw new Error(`Line ${r} not found in section ${t} rollback timeline`);return l===i.currentIndex?e:ka(e,l)},uc=e=>{let n=vp(e);return Ti(n,{selectPendingEffects:Rp,selectSkipMode:Oa,selectAutoMode:Cp,selectIsChoiceVisible:Va,selectIsFormVisible:kp,selectActiveInteraction:Ae,selectActiveForm:ot,selectDialogueUIHidden:$a,selectDialogueHistory:Ta,selectConfirmDialog:_p,selectIsLineAccountViewed:So,selectIsResourceAccountViewed:$p,selectImageGalleryConfig:Tp,selectImageGallery:La,selectMusicRoomConfig:Pp,selectMusicRoom:Na,selectSceneReplayConfig:Np,selectSceneReplay:Da,selectIsSceneReplayActive:Dp,selectActiveSceneReplayEntry:Mp,selectNextLineConfig:Vp,selectSystemState:jp,selectAchievements:Fp,selectAchievement:Up,selectSaveSlotMap:ja,selectSaveSlots:Wp,selectSaveSlot:Bp,selectRuntime:Lo,selectRuntimeValue:Gp,selectAllVariables:Yt,selectCurrentPointer:Ce,selectSection:de,selectCurrentLine:Ht,selectPresentationState:Fa,selectAutoForwardTimerDelay:it,selectPresentationChanges:qp,selectSectionLineChanges:Hp,selectSaveSlotPage:Po,selectCurrentPageSlots:Kp,selectRenderState:Xp,selectOverlayStack:Sp,selectLineIdByOffset:cc,selectCanRollback:lc,selectRollbackCursor:hp,startAutoMode:Ba,stopAutoMode:at,toggleAutoMode:im,startSkipMode:Ga,stopSkipMode:Je,toggleSkipMode:sm,showDialogueUI:Kt,hideDialogueUI:za,toggleDialogueUI:am,setDialogueTextSpeed:cm,setAutoForwardDelay:lm,setAutoForwardSpeed:um,setSkipUnseenText:dm,setSkipTransitionsAndAnimations:fm,setSoundVolume:pm,setMusicVolume:mm,setMuteAll:gm,setSaveLoadPagination:hm,incrementSaveLoadPagination:ym,decrementSaveLoadPagination:bm,setMenuPage:Im,setMenuEntryPoint:wm,showConfirmDialog:Qp,hideConfirmDialog:Zp,resetStoryAtSection:Sm,clearPendingEffects:Am,appendPendingEffect:Em,completeAchievement:xm,setAchievementProgress:vm,beginRollbackActionBatch:wp,endRollbackActionBatch:Ap,markRollbackCheckpointTransient:yp,markSavedRollbackCheckpointTransient:bp,addViewedLine:Cm,addViewedResource:_m,showImageGalleryVariant:km,moveToPreviousImageGalleryVariant:Om,moveToNextImageGalleryVariant:$m,clearImageGallerySelection:Tm,moveToImageGalleryPage:Lm,moveToNextImageGalleryPage:Pm,moveToPreviousImageGalleryPage:Nm,playMusicRoomTrack:Mm,playMusicRoom:Vm,pauseMusicRoom:jm,stopMusicRoom:Fm,seekMusicRoom:Um,playPreviousMusicRoomTrack:Bm,playNextMusicRoomTrack:Gm,clearMusicRoomSelection:zm,moveToMusicRoomPage:qm,moveToNextMusicRoomPage:Ym,moveToPreviousMusicRoomPage:Hm,musicRoomSoundReady:Zm,musicRoomSoundProgress:eg,musicRoomSoundComplete:ng,musicRoomSoundError:tg,startSceneReplay:Wm,finishSceneReplay:nc,exitSceneReplay:Km,moveToSceneReplayPage:Jm,moveToNextSceneReplayPage:Xm,moveToPreviousSceneReplayPage:Qm,setNextLineConfig:ic,saveSlot:rg,loadSlot:og,updateProjectData:ig,sectionTransition:lg,jumpToLine:sg,nextLine:ag,markLineCompleted:cg,rollbackToLine:_g,rollbackByOffset:Cg,pushOverlay:em,popOverlay:nm,replaceLastOverlay:tm,clearOverlays:rm,updateFormField:mg,submitForm:gg,cancelForm:hg,updateVariable:yg,nextLineFromSystem:ug},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var kg="route-engine",Og="projectPersistence";var fc=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),se=e=>Object.prototype.toString.call(e)==="[object Object]",dc="variables.",$g=(e={})=>{let n=se(e)?e:{};return{sections:(Array.isArray(n.sections)?n.sections:[]).map(t=>typeof t=="string"||typeof t=="number"?{sectionId:String(t)}:!se(t)||typeof t.sectionId!="string"||t.sectionId.length===0?null:{sectionId:t.sectionId,...typeof t.lineId=="string"?{lineId:t.lineId}:{}}).filter(Boolean),resources:(Array.isArray(n.resources)?n.resources:[]).map(t=>typeof t=="string"||typeof t=="number"?{resourceId:String(t)}:!se(t)||typeof t.resourceId!="string"||t.resourceId.length===0?null:{resourceId:t.resourceId}).filter(Boolean)}},Tg=(e={})=>{let n=se(e)?e:{};return{sections:(Array.isArray(n.sections)?n.sections:[]).map(t=>typeof t=="string"||typeof t=="number"?{sectionId:String(t)}:!se(t)||typeof t.sectionId!="string"||t.sectionId.length===0?null:{sectionId:t.sectionId,...typeof t.lastLineId=="string"?{lastLineId:t.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(n.resources)?n.resources:[]).map(t=>typeof t=="string"||typeof t=="number"?{resourceId:String(t)}:!se(t)||typeof t.resourceId!="string"||t.resourceId.length===0?null:{resourceId:t.resourceId}).filter(Boolean)}},Lg=(e,n)=>{let t=Tg(e),r=$g(n),o=t.sections.map(s=>({...s})),i=t.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}},pc=(e={})=>{let n=se(e)?e:{};return{saveSlots:se(n.saveSlots)?n.saveSlots:{},globalDeviceVariables:se(n.globalDeviceVariables)?n.globalDeviceVariables:{},globalAccountVariables:se(n.globalAccountVariables)?n.globalAccountVariables:{},globalRuntime:se(n.globalRuntime)?n.globalRuntime:{},accountViewedRegistry:se(n.accountViewedRegistry)?n.accountViewedRegistry:{}}},Pg=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((n,t)=>{if(!se(n))throw new Error(`Malformed applyScopedDataUpdates.updates[${t}] entry.`);let r=n.path?.startsWith(dc)?n.path.slice(dc.length):null;if(r!==null){if(!["device","account"].includes(n.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${n.scope}" at updates[${t}].`);if(r.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${n.path}" at updates[${t}].`);if(n.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${n.op}" at updates[${t}].`);return{scope:n.scope,path:n.path,op:n.op,value:n.value,variableId:r}}if(n.path==="viewedRegistry"){if(n.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${n.scope}" at updates[${t}].`);if(n.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${n.op}" at updates[${t}].`);return n}throw typeof n.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${t}].`):new Error(`Unsupported applyScopedDataUpdates path "${n.path}" at updates[${t}].`)})},Ng=(e,n)=>{let t={};return Pg(n).forEach(r=>{if(r.path==="viewedRegistry"){t.accountViewedRegistry=Lg(t.accountViewedRegistry??e.accountViewedRegistry,r.value);return}let o=r.scope==="device"?"globalDeviceVariables":"globalAccountVariables";t[o]={...e[o],...t[o],[r.variableId]:r.value}}),t},Vo=e=>{if(typeof e!="string")return null;let n=e.trim();return n.length>0?n:null},Dg=e=>{let n=Vo(e);if(!n)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return n},Mg=e=>{let n=e??globalThis.indexedDB;if(!n)throw new Error("IndexedDB is not available in this environment.");return n},Vg=({indexedDB:e,databaseName:n,objectStoreName:t})=>new Promise((r,o)=>{let i=e.open(n,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(t)||s.createObjectStore(t,{keyPath:"namespace"})},i.onsuccess=()=>{r(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${n}".`))}}),jg=async({databasePromise:e,objectStoreName:n,namespace:t})=>{let r=await e;return new Promise((o,i)=>{let a=r.transaction(n,"readonly").objectStore(n).get(t);a.onsuccess=()=>{o(a.result??null)},a.onerror=()=>{i(a.error??new Error(`Failed to read persisted namespace "${t}" from IndexedDB.`))}})},lt=async({databasePromise:e,objectStoreName:n,namespace:t,patch:r})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(n,"readwrite"),a=l.objectStore(n),c=a.get(t),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 "${t}" before updating IndexedDB.`))},c.onsuccess=()=>{let p=pc(c.result),g=typeof r=="function"?r(p):r,h={namespace:t,version:1,...fc(),...p,...g},b=a.put(h);b.onerror=()=>{d(b.error??new Error(`Failed to persist namespace "${t}" to IndexedDB.`))}},l.oncomplete=()=>{f()},l.onerror=()=>{d(l.error??new Error(`IndexedDB transaction failed while updating namespace "${t}".`))},l.onabort=()=>{d(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${t}".`))}})},Fg=async({databasePromise:e,objectStoreName:n,namespace:t})=>{let r=await e;return new Promise((o,i)=>{let s=r.transaction(n,"readwrite"),a=s.objectStore(n).delete(t),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 "${t}" from IndexedDB.`))},s.oncomplete=()=>{d()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${t}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${t}".`))}})},jo=(e={})=>{let{indexedDB:n,databaseName:t=kg,objectStoreName:r=Og,namespace:o}=e,i=Mg(n),s=Dg(o),l=Vg({indexedDB:i,databaseName:t,objectStoreName:r});return{namespace:s,load:async()=>{let a=await jg({databasePromise:l,objectStoreName:r,namespace:s});return{...fc(),...pc(a)}},clear:async()=>Fg({databasePromise:l,objectStoreName:r,namespace:s}),saveSlots:async a=>lt({databasePromise:l,objectStoreName:r,namespace:s,patch:{saveSlots:se(a)?a:{}}}),saveGlobalDeviceVariables:async a=>lt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:se(a)?a:{}}}),saveGlobalAccountVariables:async a=>lt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalAccountVariables:se(a)?a:{}}}),saveGlobalRuntime:async a=>lt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalRuntime:se(a)?a:{}}}),applyScopedDataUpdates:async a=>lt({databasePromise:l,objectStoreName:r,namespace:s,patch:c=>Ng(c,a)})}},Ug=jo;var Bg=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Gg=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),mc="conditional",Bo=Symbol("conditionalAutoContinue"),zg=new Set(["sectionTransition","resetStoryAtSection"]),qg=new Set(["nextLine","nextLineFromSystem","resetStoryAtSection","sectionTransition"]),Yg=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),Fo="form",Hg=new Set(["submitForm","cancelForm"]),Wg="showImageGalleryVariant",Kg="playMusicRoomTrack",Jg="startSceneReplay",Qe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Zt=e=>e?.type===Bo,Uo=(e,n)=>e?.sectionId===n?.sectionId&&e?.lineId===n?.lineId;function Go(e){let n,t=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=(m=new Map,w=Date.now())=>new Map(Array.from(m.entries()).filter(([,v])=>w<v.expiresAt).map(([v,_])=>[v,{animation:structuredClone(_.animation),startedAt:_.startedAt,expiresAt:_.expiresAt}])),g=(m=new Map)=>Array.from(m.values()).map(w=>structuredClone(w.animation)),h=(m=Date.now())=>{c=new Map(Array.from(c.entries()).filter(([,w])=>m<w.expiresAt))},b=()=>{if(!(o>0||i)){i=!0;try{for(;n.selectPendingEffects().length>0;){let m=[...n.selectPendingEffects()];n.clearPendingEffects();try{f(m)}catch(w){throw n.clearPendingEffects(),m.forEach(v=>{n.appendPendingEffect(v)}),w}}}finally{i=!1}}},I=m=>{o+=1;let w=!1;try{let v=m();return w=!0,v}finally{o-=1,w&&b()}},E=({initialState:m,namespace:w})=>{n=uc(m),t=0,r=Vo(w),o=0,i=!1,s=0,l=[],a=null,c=new Map,u=new Map,d=new Map,n.appendPendingEffect({name:"handleLineActions"}),b()},A=()=>r,$=()=>n.selectPresentationState(),B=()=>n.selectPresentationChanges(),L=m=>n.selectSectionLineChanges(m),T=(m={})=>{t+=1;let w=Date.now();h(w);let v=u.size>0,_=p(c,w),D=v?p(u,w):new Map,X={...n.selectRenderState({activePersistentAnimations:g(_),restoredPersistentAnimations:g(D)}),id:`render-${t}`};return d.set(X.id,{builtAt:w,persistentAnimationSessions:new Map([...D.entries(),..._.entries()]),usedRestoredPersistentAnimationSessions:v}),X},z=(m={})=>T(m),G=(m={})=>T(m),S=m=>{let w=typeof m?.id=="string"&&m.id.length>0?m.id:null,v=w?d.get(w):null;w&&d.delete(w);let _=new Map;ys(m?.animations).forEach(D=>{let F=Lt(D);if(!F)return;let X=v?.persistentAnimationSessions?.get(F)??c.get(F),Z=Math.max(0,ws(D)),Ze=X?.startedAt??v?.builtAt??Date.now();_.set(F,{animation:structuredClone(D),startedAt:Ze,expiresAt:Ze+Z})}),c=_,v?.usedRestoredPersistentAnimationSessions&&(u=new Map)},q=()=>n.selectSystemState(),W=()=>n.selectAchievements(),me=m=>n.selectAchievement(m),Y=()=>n.selectSaveSlotMap(),ae=m=>n.selectSaveSlot(m),oe=m=>n.selectSaveSlotPage(m),ge=()=>n.selectImageGallery(),$e=()=>n.selectMusicRoom(),ce=()=>n.selectSceneReplay(),te=()=>n.selectIsSceneReplayActive(),fe=()=>n.selectSkipMode(),le=()=>n.selectAutoMode(),x=()=>n.selectRuntime(),C=()=>n.selectIsChoiceVisible(),O=()=>n.selectIsFormVisible(),Q=()=>n.selectActiveInteraction(),Ie=()=>n.selectPendingEffects().some(m=>m?.name==="handleLineActions"||m?.name==="render"),H=(m,w,v={})=>!Qe(w)||m!=="nextLine"?w:v.bypassChoice===!0?{...w,bypassChoice:!0}:v.interactionSource===Fo?{...w,_interactionSource:Fo}:w,Te=(m={})=>({type:Bo,payload:H("nextLine",{_conditionalContinuation:!0},m)}),he=(m,w)=>Zt(m)?{type:Bo,payload:{...m.payload,...w.payload}}:w,Ic=m=>{m.savedCheckpointOccurrences.forEach(w=>{n.markSavedRollbackCheckpointTransient(w)}),m.savedCheckpointOccurrences=[]},wc=(m,w)=>{let v=a;return a=null,!v||!Uo(v.pointer,m)||v.checkpointIndex!==w?.checkpointIndex||v.checkpointIdentity!==w?.checkpoint?[]:v.savedCheckpointOccurrences},qo=m=>{m.markCurrentCheckpointTransient&&(n.markRollbackCheckpointTransient({checkpointIndex:m.rollbackCursor?.checkpointIndex,checkpointIdentity:m.rollbackCursor?.checkpoint,sectionId:m.pointer?.sectionId,lineId:m.pointer?.lineId}),Ic(m))},Ac=(m,w,v)=>qg.has(m)?m==="resetStoryAtSection"?v?.checkpoint!==w?.checkpoint:v?.checkpoint!==w?.checkpoint&&v?.checkpointIndex>w?.checkpointIndex:!1,Ec=m=>{let w=l.at(-1);if(!w?.markCurrentCheckpointTransient)return;let v=n.selectSaveSlot({slotId:m?.slotId});v&&w.savedCheckpointOccurrences.push({slotId:m.slotId,saveSlotIdentity:v,checkpointIndex:w.rollbackCursor?.checkpointIndex,sectionId:w.pointer?.sectionId,lineId:w.pointer?.lineId})},xc=(m,w,v)=>{let _=l.at(-1);if(!_)return;let D=n.selectCurrentPointer()?.pointer,F=Ac(m,w,v);if(Uo(_.pointer,D)){let X=v?.checkpoint!==w?.checkpoint||v?.checkpointIndex!==w?.checkpointIndex;(F||X&&Yg.has(m))&&(qo(_),_.pointer=D,_.rollbackCursor=v,_.markCurrentCheckpointTransient=F,_.savedCheckpointOccurrences=[]);return}qo(_),_.pointer=D,_.rollbackCursor=n.selectRollbackCursor?.()??null,_.markCurrentCheckpointTransient=F,_.savedCheckpointOccurrences=[]},dt=(m,w)=>{if(!n[m])return;m==="updateProjectData"&&vc(w),zg.has(m)&&(s+=1);let v=n.selectIsSceneReplayActive?.()===!0,_=Gg.has(m)?p(c):null,D=n.selectRollbackCursor?.()??null,F=n[m](w);Bg.has(m)&&(u=_??new Map,c=new Map);let X=n.selectIsSceneReplayActive?.()===!0;v!==X&&(c=new Map,u=new Map);let Z=n.selectRollbackCursor?.()??null;return m==="saveSlot"&&Ec(w),xc(m,D,Z),b(),F},vc=m=>{if(!Object.prototype.hasOwnProperty.call(m??{},"projectData"))throw new Error("updateProjectData requires projectData");an(m?.projectData?.resources?.variables??{}),jn(m.projectData),Fn(m.projectData),Un(m.projectData)},Sc=(m,w,v)=>{let _=n.selectCurrentPointer()?.pointer;w!==_||v!==s||(n.appendPendingEffect({name:"clearAutoNextTimer"}),n.appendPendingEffect({name:"clearNextLineConfigTimer"}),dt("nextLineFromSystem",m.payload))},Rc=()=>({renderSequence:t,conditionalRoutingSequence:s,rollbackNavigationContexts:l.slice(),pendingRollbackLineEntrySaveHandoff:a,persistentAnimationSessions:new Map(c),restoredPersistentAnimationSessions:new Map(u),renderPersistentAnimationMetadata:new Map(d)}),Cc=m=>{t=m.renderSequence,s=m.conditionalRoutingSequence,l=m.rollbackNavigationContexts.slice(),a=m.pendingRollbackLineEntrySaveHandoff,c=new Map(m.persistentAnimationSessions),u=new Map(m.restoredPersistentAnimationSessions),d=new Map(m.renderPersistentAnimationMetadata)},Yo=(m,w={})=>I(()=>{let v=Rc();try{return n[kr](()=>{let _,D=n.selectCurrentPointer()?.pointer??null,F=n.selectRollbackCursor?.()??null,X=s,Z={pointer:D,rollbackCursor:F,markCurrentCheckpointTransient:w.rollbackSource==="line",savedCheckpointOccurrences:w.savedCheckpointOccurrences?.slice()??[]};l.push(Z);try{n.beginRollbackActionBatch({source:w.rollbackSource});try{_=m()}finally{n.endRollbackActionBatch({})}Zt(_)&&Sc(_,D,X)}finally{l.pop(),(!Uo(D,Z.pointer)||F?.checkpoint!==Z.rollbackCursor?.checkpoint)&&Z.markCurrentCheckpointTransient&&Z.savedCheckpointOccurrences.length>0&&(a={pointer:Z.pointer,checkpointIndex:Z.rollbackCursor?.checkpointIndex,checkpointIdentity:Z.rollbackCursor?.checkpoint,savedCheckpointOccurrences:Z.savedCheckpointOccurrences})}})}catch(_){throw Cc(v),_}}),Ho=(m,w,v,_={})=>{if(m===mc)return Yo(()=>{let D=er(v),F=Pr({[m]:w},D);return Wo(F[m],v,_)},_);dt(m,w)},_c=(m,w)=>{Ho(m,w)},er=m=>{if(!m)return{variables:n.selectAllVariables?n.selectAllVariables():void 0,runtime:n.selectRuntime?n.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(m,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:w,...v}=m,_=n.selectAllVariables?n.selectAllVariables():void 0;return{...v,_event:w,variables:_,runtime:n.selectRuntime?n.selectRuntime():{}}},kc=m=>{if(!Qe(m))return{templatePayload:m,literalTargetIds:null};let w=n.selectImageGalleryConfig();if(!Array.isArray(w?.groups))return{templatePayload:m,literalTargetIds:null};let v=typeof m.groupId=="string"?w.groups.find(D=>D.id===m.groupId):void 0;if(!v)return{templatePayload:m,literalTargetIds:null};let _=typeof m.variantId=="string"&&v.variants.some(D=>D.id===m.variantId);return{templatePayload:{...m,groupId:null,..._?{variantId:null}:{}},literalTargetIds:{groupId:m.groupId,..._?{variantId:m.variantId}:{}}}},Oc=m=>!Qe(m)||typeof m.trackId!="string"?{templatePayload:m,literalTargetIds:null}:n.selectMusicRoomConfig()?.tracks?.some(_=>_.id===m.trackId)?{templatePayload:{...m,trackId:null},literalTargetIds:{trackId:m.trackId}}:{templatePayload:m,literalTargetIds:null},$c=m=>!Qe(m)||typeof m.replayId!="string"?{templatePayload:m,literalTargetIds:null}:n.selectSceneReplayConfig()?.replays?.some(_=>_.id===m.replayId)?{templatePayload:{...m,replayId:null},literalTargetIds:{replayId:m.replayId}}:{templatePayload:m,literalTargetIds:null},Tc=m=>{if(!Qe(m))throw new Error("conditional action payload must be an object");if(!Array.isArray(m.branches))throw new Error("conditional action requires branches array");if(m.branches.length===0)throw new Error("conditional action requires at least one branch")},Lc=(m,w,v)=>{if(!Qe(m))throw new Error(`conditional branch at index ${w} must be an object`);if(!Qe(m.actions))throw new Error(`conditional branch at index ${w} requires actions object`);if(!Object.prototype.hasOwnProperty.call(m,"when")&&w!==v-1)throw new Error("conditional else branch must be the last branch")},Wo=(m,w,v)=>{Tc(m);let _=Te(v);for(let D=0;D<m.branches.length;D+=1){let F=m.branches[D];Lc(F,D,m.branches.length);let X=er(w);if(Object.prototype.hasOwnProperty.call(F,"when")&&!Vn(F.when,X))continue;let Ze=nr(F.actions,w,v);return Zt(Ze)?he(_,Ze):_}return _},Pc=(m,w)=>({...m??{},_form:w}),Nc=(m,w,v,_)=>{let D=dt(m,w),F=D?.submitted===!0&&D.valid===!0,X=D?.cancelled===!0;if(!(!F&&!X)&&Qe(w.actions))return nr(w.actions,Pc(v,D.form),{..._,interactionSource:Fo})},Dc=(m,w,v,_)=>{let D=er(v),F={templatePayload:w,literalTargetIds:null};m===Wg?F=kc(w):m===Kg?F=Oc(w):m===Jg&&(F=$c(w));let{templatePayload:X,literalTargetIds:Z}=F,Jo=Pr({[m]:X},D)[m],Xo=Z?{...Jo,...Z}:Jo;if(m===mc)return Wo(Xo,v,_);let Qo=H(m,Xo,_);if(Hg.has(m))return Nc(m,Qo,v,_);dt(m,Qo)},nr=(m,w,v)=>{let _;return Object.entries(m).forEach(([D,F])=>{let X=Dc(D,F,w,v);Zt(X)&&(_=he(_,X))}),_},Ko=(m,w,v={})=>Yo(()=>nr(m,w,v),v),Mc=m=>{let w=n.selectCurrentPointer()?.pointer;if(m!==w||n.selectActiveInteraction())return;let v=n.selectNextLineConfig();v?.auto?.enabled&&v.auto.trigger==="fromStart"&&n.appendPendingEffect({name:"nextLineConfigTimer",payload:{delay:v.auto.delay}})};return{init:E,handleAction:Ho,handleInternalAction:_c,handleActions:Ko,selectRenderState:z,prepareRenderState:G,commitRenderState:S,selectPresentationState:$,selectPresentationChanges:B,selectSectionLineChanges:L,selectSystemState:q,selectAchievements:W,selectAchievement:me,selectSaveSlotMap:Y,selectSaveSlot:ae,selectSaveSlotPage:oe,selectSaveSlots:Y,selectImageGallery:ge,selectMusicRoom:$e,selectSceneReplay:ce,selectIsSceneReplayActive:te,selectRuntime:x,selectIsChoiceVisible:C,selectIsFormVisible:O,selectActiveInteraction:Q,selectHasPendingRenderWork:Ie,handleLineActions:m=>{if(typeof m?.sceneReplayId=="string"){let w=n.selectActiveSceneReplayEntry?.();if(w?.replayId!==m.sceneReplayId||w?.entryId!==m.entryId)return!1}return I(()=>{let w=n.selectCurrentPointer()?.pointer,v=n.selectRollbackCursor?.()??null,_=a,D=wc(w,v),F=n.selectCurrentLine(),X=!1;if(F?.actions){try{Ko(F.actions,void 0,{rollbackSource:"line",savedCheckpointOccurrences:D})}catch(Z){throw a=_,Z}X=!0}return Mc(w),X})},getNamespace:A}}var zo=()=>{let e=0,n=null;return{getElapsed:()=>e,setElapsed:t=>{e=t},addElapsed:t=>{e+=t},getCallback:()=>n,setCallback:t=>{n=t}}},Xg=80,Qg="music-room:player",yc=new Map([["soundReady","musicRoomSoundReady"],["soundProgress","musicRoomSoundProgress"],["soundComplete","musicRoomSoundComplete"],["soundError","musicRoomSoundError"]]),gc=(e,n)=>yc.has(e)&&n?._event?.id===Qg,bc=({engine:e,routeGraphics:n,trackRenderDispatch:t},r)=>{if(e.selectHasPendingRenderWork?.())return;let o=e.prepareRenderState?.(r)??e.selectRenderState(r);t?.(o),n.render(o),e.commitRenderState?.(o)},Zg=({engine:e,routeGraphics:n,trackRenderDispatch:t,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions(o);(r?.()??0)===i&&bc({engine:e,routeGraphics:n,trackRenderDispatch:t},o)},eh=({engine:e,ticker:n,autoTimer:t},r)=>{let o=t.getCallback();o&&n.remove(o),t.setElapsed(0);let i=s=>{t.addElapsed(s.deltaMS);let l=r.delay??1e3;t.getElapsed()>=l&&(n.remove(i),t.setCallback(null),t.setElapsed(0),ut(e,"nextLineFromSystem",{}))};t.setCallback(i),n.add(i)},nh=({ticker:e,autoTimer:n},t)=>{let r=n.getCallback();r&&(e.remove(r),n.setCallback(null)),n.setElapsed(0)},th=({engine:e,ticker:n,skipTimer:t},r)=>{let o=t.getCallback();o&&n.remove(o),t.setElapsed(0);let i=s=>{t.addElapsed(s.deltaMS);let l=r?.delay??Xg;t.getElapsed()>=l&&(t.setElapsed(0),ut(e,"nextLineFromSystem",{}))};t.setCallback(i),n.add(i)},rh=({ticker:e,skipTimer:n},t)=>{let r=n.getCallback();r&&(e.remove(r),n.setCallback(null)),n.setElapsed(0)},oh=({engine:e,ticker:n,nextLineConfigTimerState:t},r)=>{let o=t.getCallback();o&&n.remove(o),t.setElapsed(0);let i=s=>{t.addElapsed(s.deltaMS);let l=r.delay??1e3;t.getElapsed()>=l&&(t.setElapsed(0),ut(e,"nextLineFromSystem",{}),n.remove(i),t.getCallback()===i&&t.setCallback(null))};t.setCallback(i),n.add(i)},ih=({ticker:e,nextLineConfigTimerState:n},t)=>{let r=n.getCallback();r&&(e.remove(r),n.setCallback(null)),n.setElapsed(0)},sh=({enqueuePersistenceWrite:e},n)=>{e(t=>t.saveSlots(n?.saveSlots))},ah=({enqueuePersistenceWrite:e},n)=>{e(t=>t.saveGlobalDeviceVariables(n?.globalDeviceVariables))},ch=({enqueuePersistenceWrite:e},n)=>{e(t=>t.saveGlobalAccountVariables(n?.globalAccountVariables))},lh=({enqueuePersistenceWrite:e},n)=>{e(t=>t.saveGlobalRuntime(n?.globalRuntime))},uh=({enqueuePersistenceWrite:e},n)=>{e(t=>{if(typeof t.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return t.applyScopedDataUpdates(n?.updates)})},hc={render:bc,saveSlots:sh,saveGlobalDeviceVariables:ah,saveGlobalAccountVariables:ch,saveGlobalRuntime:lh,applyScopedDataUpdates:uh,handleLineActions:Zg,startAutoNextTimer:eh,clearAutoNextTimer:nh,startSkipNextTimer:th,clearSkipNextTimer:rh,nextLineConfigTimer:oh,clearNextLineConfigTimer:ih},dh=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),ut=(e,n,t)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(n,t)},fh=(e=[])=>{let n=new Set,t=[];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(!dh.has(o.name)){t.unshift(o);continue}n.has(o.name)||(n.add(o.name),t.unshift(o))}return t},ph=({getEngine:e,routeGraphics:n,ticker:t,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let a=zo(),c=zo(),u=zo(),d=s??null,f=Promise.resolve(),p=null,g=null,h=!1,b=0,I=x=>{if(o){o(x);return}console.error("RouteEngine persistence write failed.",x)},E=()=>{if(d)return d;let x=e();return d=jo({indexedDB:i,namespace:l??x?.getNamespace?.()}),d},A=x=>{f=f.catch(()=>{}).then(()=>{let C=E();return x(C)}).catch(C=>{I(C)})},$=x=>{let C=typeof x?.id=="string"&&x.id.length>0?x.id:null;b+=1,p=C,h=!1},B=()=>b,L=(x={})=>{if(x?.aborted===!0)return!1;let C=typeof x?.id=="string"&&x.id.length>0?x.id:null;return C?C!==p||C===g?!1:(g=C,!0):p!==null||h?!1:(h=!0,!0)},T=(x,C={})=>{if(gc(x,C)){let Q=yc.get(x),Ie=e();return ut(Ie,Q,C?._event),!0}if(x!=="renderComplete"||!L(C))return!1;let O=e();return ut(O,"markLineCompleted",{}),!0},z=new Set(["updateFormField","submitForm","cancelForm"]),G=new Set(["updateVariable"]),S=x=>typeof x?.selectActiveInteraction=="function"?x.selectActiveInteraction():typeof x?.selectIsChoiceVisible=="function"&&x.selectIsChoiceVisible()?{source:"choice"}:null,q=x=>x?._formKey??x?.formKey,W=(x,C)=>q(x)===C?.formKey,me=(x,C)=>!x||typeof x!="object"||Array.isArray(x)?!1:x._interactionSource===C?.source,Y=(x,C)=>me(x,C)?C.source==="form"?W(x,C):!0:!1,ae=(x,C)=>!x||typeof x!="object"||Array.isArray(x)||C?.source!=="form"?!1:W(x,C),oe=(x={})=>Object.keys(x).some(C=>z.has(C)),ge=(x={},C)=>Object.entries(x).some(([O,Q])=>z.has(O)&&ae(Q,C)),$e=(x={})=>Object.keys(x).length>0&&Object.keys(x).every(C=>G.has(C)),ce=(x={},C)=>{let O=x?.actions;return C?.source==="form"?!O||typeof O!="object"||Array.isArray(O)?!1:ge(O,C)?!0:oe(O)?!1:$e(O):Y(x,C)?!0:!O||typeof O!="object"||Array.isArray(O)?!1:Object.values(O).some(Q=>Y(Q,C))},te=(x,C={})=>{if(!C?.actions)return!1;let O=S(x);return!O||O.source==="choice"?!1:!ce(C,O)},fe=({preprocessPayload:x,onEvent:C}={})=>async(O,Q={})=>{if(gc(O,Q))return T(O,Q),C?.(O,Q);let Ie=e();if(te(Ie,Q))return C?.(O,Q);let H=await x?.(O,Q)??Q;if(te(Ie,H))return C?.(O,H);if(T(O,H),H?.actions){let Te=H?._event?{_event:H._event}:H?.event?{_event:H.event}:void 0,he;H?.bypassChoice===!0?he={bypassChoice:!0}:H?._interactionSource&&(he={interactionSource:H._interactionSource}),he?Ie.handleActions(H.actions,Te,he):Ie.handleActions(H.actions,Te)}return C?.(O,H)},le=x=>{let C=e(),O=fh(x),Q=O.some(H=>H.name==="handleLineActions");O.forEach(H=>{if(!hc[H.name]&&!r)throw new Error(`Unhandled pending effect "${H.name}".`)});let Ie={engine:C,routeGraphics:n,ticker:t,autoTimer:a,skipTimer:c,nextLineConfigTimerState:u,trackRenderDispatch:$,getRenderDispatchCount:B,enqueuePersistenceWrite:A};for(let H of O){if(Q&&H.name==="render")continue;let Te=hc[H.name];if(Te){Te(Ie,H.payload);continue}r(H,Ie)}};return le.handleRouteGraphicsEvent=T,le.createRouteGraphicsEventHandler=fe,le},mh=ph;var gh=(e,n={})=>{let{resources:t={}}=n;return io(e,t)};var Hy=Go;export{Vr as DEFAULT_VISUAL_LAYER,xn as RENDER_LAYER,Ne as VISUAL_LAYER,mh as createEffectsHandler,Ug as createIndexedDbPersistence,Hy as default,$r as formatDate,au as resolveComputedVariables,gh as resolveLayoutReferences};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "route-engine-js",
3
- "version": "1.32.1",
3
+ "version": "1.33.0",
4
4
  "description": "A lightweight Visual Novel engine built in JavaScript for creating interactive narrative games with branching storylines",
5
5
  "repository": {
6
6
  "type": "git",
@@ -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.30.2",
62
+ "route-graphics": "1.33.0",
63
63
  "vitest": "4.0.16"
64
64
  }
65
65
  }