route-engine-js 1.33.0 → 1.33.1

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 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};
1
+ var Uc=Object.defineProperty;var Bc=(e,n)=>{for(var t in n)Uc(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 Gc=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)===Gc}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 zc(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=qc),Object.freeze(e),n&&Object.entries(e).forEach(([t,r])=>dr(r,!0))),e}function qc(){Ee(2)}function bt(e){return Object.isFrozen(e)}var Yc={};function tn(e){let n=Yc[e];return n||Ee(0,e),n}var Ln;function ai(){return Ln}function Hc(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(Wc),e.drafts_=null}function ar(e){e===Ln&&(Ln=e.parent_)}function ni(e){return Ln=Hc(Ln,e)}function Wc(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 Kc(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 Jc(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(zc(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 Jc(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 Xc=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):Kc(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 Xc,pr=we.produce,Eh=we.produceWithPatches.bind(we),xh=we.setAutoFreeze.bind(we),vh=we.setUseStrictShallowCopy.bind(we),Sh=we.applyPatches.bind(we),Rh=we.createDraft.bind(we),Ch=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 Qc=(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 el(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 tl(e,n,t,r);case y.LOOP:return al(e,n,t,r);case y.OBJECT:return ll(e,n,t,r);case y.ARRAY:return ul(e,n,t,r);case y.PARTIAL:return dl(e,n,t,r);case y.PATH_REFERENCE:return fl(e,n,t,r);default:throw new Error(`Unknown node type: ${e.type}`)}},pi=new Map,Zc=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=Zc(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},el=(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}`)},nl=(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},tl=(e,n,t,r)=>{let o=nl(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},rl=(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},ol=(e,n)=>{let t=e.body,r=e.itemVar,o=rl(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},il=(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},sl=(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},al=(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=sl(e,o,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=ol(e,o);if(c!==null)return c}let i=il(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},cl=(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},ll=(e,n,t,r)=>{let o=n.functions||n;if(e.whenCondition&&!Be(e.whenCondition,o,t,r))return;let i=cl(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={},ul=(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},dl=(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)},fl=(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=Qc;var pl=/\$\{([^}]*)\}/g,ml=/#\{([^}]*)\}/g,Ii=(e,n={})=>{let t=e.match(/^(\w+)\((.*)\)$/);if(!t)return{isFunction:!1};let[,r,o]=t,i=gl(o,n);return{isFunction:!0,type:y.FUNCTION,name:r,args:i}},gl=(e,n={})=>e.trim()?hl(e).map(r=>yl(r.trim(),n)):[],hl=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},yl=(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+\(.*\)$/,bl=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Il=e=>{if(!(!e||e.trim()===""||wi.test(e))&&bl.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();Il(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(pl)],i=[...t.matchAll(ml)],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)?Al(e,n):El(e,n):{type:y.LITERAL,value:e},wl=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}},Al=(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=wl(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}},El=(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=xl(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},xl=(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},vl=new Set(["var","literal","call","not",...Object.keys(yr),...Object.keys(br)]),Sl=(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},Rl=(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}))},Cl=(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=>vl.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 Cl(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),Rl(e[i],i,br[i],n,[...t,i]);if(i in yr){Ge(e,new Set([i]),t);let s=Sl(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},_l=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=_l(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}},kl=(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();kl(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 Ol=(e,n={})=>{let{functions:t={}}=n;return ze(e,t)},It=Ol;var Dn={};Bc(Dn,{now:()=>$l});var $l=()=>Date.now();var Tl=(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=Tl;var Ll=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Pl=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Nl=(e,n)=>{if(Ll(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new R("Empty condition expression");return re(e,n)}return be(e,n)},Dl=(e,n={},t={})=>{let r=Pl(t),o={...Dn,...r},i=Nl(e,o);return!!Be(i,{functions:o,partials:{}},n,{})},wr=Dl;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}`]))),Ml=Object.freeze(Object.fromEntries(Object.entries($i).map(([e,n])=>[n,qe[e]]))),Si=(e,n)=>Object.prototype.hasOwnProperty.call(e??{},n),Vl=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(Vl(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:Ml})},jl=["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 Fl=(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),Ul=new Set(["pageSize","groups"]),Bl=new Set(["id","variants"]),Gl=new Set(["id","imageId"]),zl=new Set(["pageSize","tracks"]),ql=new Set(["id","soundId","title","artist","album","description","coverImageId"]),Yl=new Set(["pageSize","replays"]),Hl=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,Ul,"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,Bl,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,Gl,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,zl,"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,ql,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}"`)}},Wl=(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,Yl,"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,Hl,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}"`);Wl(a,u,c)}}}},Li=e=>{let n=ie(e)?Ue(e):e;return structuredClone(n)},Kl=({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=Kl({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)}`),Jl=(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(Jl(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`)},Xl=(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=>Xl(e,i)),o},Ql=(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 Ql(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)]))},Zl=(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)),eu=(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(Zl(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}`)}},nu=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}),tu=new Set(["and","or","all","any"]),ru=new Set(["add","sub","mul","div","mod","neg","round","floor","ceil","min","max","clamp","length"]),ou=new Set(["add","sub","mul","div","mod","neg","round","floor","ceil","min","max","clamp"]),iu=new Set(["eq","neq","gt","gte","lt","lte","in","and","or","all","any","not","includes"]),su=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}"`)},au=(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=nu[s];if(a===void 0&&!tu.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(ou.has(s)&&c.forEach(u=>{if(u!==void 0&&u!=="number")throw new Error(`Computed expression operator "${s}" requires numeric operands`)}),ru.has(s))return"number";if(iu.has(s))return"boolean"},cu=(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=>su.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`});au(n,t.type,l,`${i}.expr`)},lu=(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`);cu(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,lu(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=eu(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},uu=({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=Fl(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(", ")}`)},du=2,Ci=12,Bi=(e=du)=>{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},fu=(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 fu(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:jl[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])},pu=(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,mu=(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,gu=(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=gu(e.background,n.background);i&&(t.background=i),o("screen"),o("bgm"),o("voice");let s=pu(e.dialogue,n.dialogue);s&&(t.dialogue=s);let l=mu(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},hu=(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},yu=(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=hu(n,t);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},bu={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"])},Iu=(e,n)=>{let t=e[e.length-1];return t?bu[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,Iu(t,r)?o:_r(o,n,[...t,r])])):typeof e=="string"?e==="_event"||e.startsWith("_event.")?yu(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},wu=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"],Au=e=>Ki.some(n=>j(e,n)),Xi=e=>e?.text&&j(e.text,"content")&&j(e.text,"textStyleId"),Qi=e=>j(e,"text"),Eu=(e,n)=>e.resourceId?!0:Xi(e)?!n?.text:!1,xu=(e,n)=>{let t={...K(e),...n};return n.text&&e.text&&(t.text={...K(e.text),...K(n.text)}),t},vu=(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)),Su=(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)},Ru=(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},Cu=(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=wu(s),d=Au(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),Cu(Ru(g,a),a)}).filter(s=>n(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},_u=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"),ku=e=>{let n={},t=!1,r=_u(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},Ou=({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=()=>({}),Tu=(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},Lu=(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])}Su(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={})},Pu=(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&&Ou({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=ku(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)}},Nu=(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},Du=(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)}},Mu=(e,n)=>{if(n.visual){let t=e.visual?.items||[];n.visual.items?.forEach((i,s)=>{vu(i,Zi(t,i,s))});let{hasValidItems:r,processedItems:o}=es(n.visual.items,Eu,t,{hasPatchFn:Qi,mergeItemFn:xu});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))},Vu=(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},ju=(e,n)=>{n.animation?e.animation=n.animation:e.animation&&delete e.animation},Fu=(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},Uu=(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},Bu=(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},Gu=(e,n)=>{if(n.control){if(!n.control.resourceId){delete e.control;return}e.control=n.control}},zu=(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},qu=(e,n)=>{n.cleanAll&&Object.keys(e).forEach(t=>{delete e[t]})},cn=e=>St($u,[qu,Tu,Lu,Nu,Du,Mu,Pu,Vu,ju,Fu,Uu,Bu,Gu,zu])(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 Yu=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:50,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"]),Hu=(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(Yu).map(([n,t])=>{let r=Hu(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 Wu={__arrayOrEmpty:e=>Array.isArray(e)?e:[],objectValues:e=>Object.entries(e).map(([n,t])=>({id:n,...t})),formatDate:$r},Ku=/^\$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=Ku.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:Wu};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".`)},Ju=({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=ed(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},Xu=(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},Qu=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Zu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},ed=(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},nd=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)/nd(e),td=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:td(e)||i&&!n||os({animationInstances:e,activePersistentAnimations:r})?!0:i?!1:os({animationInstances:e,activePersistentAnimations:o}),rd=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(n=>e[n]!==void 0),od=(e,n)=>{if(rd(e))throw new Error(`[${n}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},id=({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?Ju({id:r,targetId:o,animation:s,playback:t,animationPath:i}):null},sd=(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(sd(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},ad=({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},cd=(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},ld=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],ud=(e={})=>ld.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}`},dd=(e={})=>e.textStyles||{},fd=(e={})=>e.images||{},pd=.5,md=(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=md(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??pd,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}`)},gd=(e={})=>e.colors||{},hd=/^#(?:[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"||!hd.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})`},yd=(e={},n)=>{let t=dd(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=yd(n,e.textStyleId)),r},oo=(e={},n)=>{let t=gd(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`)},bd=(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]=bd(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=fd(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"),Id="#000000",Xr="bg-cg-background-color",wd=({resources:e={},background:n={},screen:t})=>n?.colorId===void 0?Dt(t?.backgroundColor??Id,"screen.backgroundColor"):oo(e,n.colorId),Rs=(e={})=>{if(dn(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Ad=(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=Ad(e),o={};return(n||t!==void 0)&&(o.alpha=t??1),r&&(o.blur=r),o},Ed=(e={})=>{if(dn(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},xd=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Cs=(e={})=>{let n=Ed(e),t=xd(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},vd=["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,Sd=({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},Rd=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 vd)if(dn(e.text,n))throw new Error(`Visual item "${e.id}" text.${n} is reserved for the visual item`)}},Cd=({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:wd({resources:e,background:n,screen:t})};if(r){let i=Rs(n);i!==void 0&&(o.alpha=i)}return o},_d=(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,kd="channel:bgm",Od="channel:music-room",$d="music-room:player",Td="channel:voice",Ld="default",Pd=e=>String(e).replaceAll("%","%25").replaceAll(":","%3A"),Wn=(...e)=>e.map(Pd).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)})},Nd=(e,n)=>e*n/_s,ks=(e={},n)=>e?.[n]??ln[n],Mt=(e={},n,t=He)=>Nd(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,Dd=["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)};Dd.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??50,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=Ud({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},Md=e=>Nt(e,n=>({...n,revealEffect:"none"})),Vd=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?Md(e):t?Vd(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}}:{}}}}},jd=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 jd){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}}),Fd=e=>!(!e||e.mode==="adv"&&e.content===void 0),Ud=({dialogueState:e,includeInactiveAdvDialogue:n=!1,characters:t={},variables:r,runtime:o}={})=>{if(!n&&!Fd(e))return;let i=e.content===void 0?[{text:""}]:Wr(e.content,"dialogue.content"),s=e.content===void 0?0:ad({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)}}})},Bd=(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=id({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;od(e,s);let p=Qu(e),g=Zu(e),h=n?.animations?.[p],b=Xu(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},Gd=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),zd=(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=cd(o,n.background),q=S||ud(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=_d(o,Y),ge={...n.background,colorId:ae};if((ae!==void 0||oe)&&G.children.push(Cd({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},qd=(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(", ")}.`)},Yd=(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},Hd=(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=Yd(S,q);if(A!==void 0&&W!==A)continue;if(Rd(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(Sd({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",Wd=(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},Kd=(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)}}Wd(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},Jd=(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},Xd=(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},Qd=(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=Bd(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},Zd=(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:kd,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},ef=(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:Od,volume:Mt(a,"musicVolume",He),children:[c],runtime:a})),e},nf=(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:Ld,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},tf=(e,n,t)=>{if(!(!n||!t))return e?.voices?.[n]?.[t]},rf=(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=tf(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:Td,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},of=(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},sf=(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},af=(e,{presentationState:n})=>{let t=fn(e.elements);return!t||!n?.screen||Object.assign(t,Cs(n.screen)),e},cf=(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},lf=(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)=>Hd(n,{...t,visualLayer:e}),uf=Xn(Ne.BEHIND_BACKGROUND),df=Xn(Ne.BEHIND_CHARACTER),ff=Xn(Ne.BEHIND_DIALOGUE),pf=Xn(Ne.BEHIND_CHOICE),mf=Xn(Ne.FOREGROUND),Ps=e=>St(Gd,[Qd,uf,zd,df,qd,ff,Kd,pf,Jd,Xd,of,mf,af,sf,Zd,ef,nf,rf,cf,lf])(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 gf(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||gf(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,na=50,hf=0,Qs=100,Zs=50,yf=60,bf=3,If=.5,wf=2e4,Af=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,Ef=/^\s+$/u,ea,xf=e=>{let n=`${e??""}`.normalize("NFC"),t=globalThis.Intl?.Segmenter;return typeof t!="function"?Array.from(Js(n)):(ea??=new t(void 0,{granularity:"grapheme"}),Array.from(ea.segment(n),({segment:r})=>r))},vf=e=>xf(e).reduce((n,t)=>Ef.test(t)?n+If:Af.test(t)?n+bf:n+1,0),Sf=e=>2**(((Number.isFinite(e)?Math.min(Qs,Math.max(hf,e)):na)-Zs)/(Qs-Zs)),ta=({text:e="",baseDelay:n=Xs,speed:t=na}={})=>{let r=Number.isFinite(n)?Math.max(0,n):Xs,o=Sf(t),i=vf(e)*yf/o,s=Math.max(r,wf);return Math.min(r+i,s)};var Ut={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},la=1,fo=1,_n="choice",Ke="form",et=()=>({manual:{...Ut.manual},auto:{...Ut.auto},applyMode:Ut.applyMode}),po=()=>({groupId:null,variantId:null,pageIndex:0}),Rf="music-room:player",Cf=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,_f=new Set(["groupId","variantId"]),kf=new Set(["pageIndex"]),kn=new Set,Of=new Set(["trackId"]),$f=new Set(["positionMs"]),Tf=new Set(["pageIndex"]),go=new Set,Lf=new Set(["replayId"]),Pf=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},ua=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})},da=(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),fa=()=>({sections:[],resources:[]}),Nf=e=>N(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):fa(),Df=e=>Array.isArray(e)?e.map(n=>n?.text??"").join(""):"",Mf=({sectionId:e,lineId:n,content:t,dialogueState:r,characterName:o})=>({sectionId:e,lineId:n,content:t,text:Df(t),characterId:r.characterId,character:{...r.character||{},name:o},characterName:o}),Vf=()=>({resourceId:void 0}),jf=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}},pa=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)}}},ma=e=>{if(typeof e=="number"||typeof e!="string")return e;let n=Number(e);return Number.isFinite(n)?n:e},ga=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==la)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Ff=(e,n={})=>{let t;try{t=ga(n.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...n,formatVersion:t,slotId:ma(n.slotId??n.slotKey??e),savedAt:typeof n.savedAt=="number"?n.savedAt:n.date};return delete r.slotKey,delete r.date,r},Uf=(e={})=>Object.fromEntries(Object.entries(e).map(([n,t])=>[n,Ff(n,t)])),ha=e=>{if(!Array.isArray(e))return;let n=e.filter(({type:t})=>Cg(t));return n.length>0?n:void 0},Bf=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=ha(n.executedActions);if(t){n.executedActions=t;return}delete n.executedActions}))},ra=(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}},Gf=(e,n="viewedRegistry")=>{if(e===void 0)return fa();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=ra(o,"sections",i,n);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(r.map((o,i)=>{let s=ra(o,"resources",i,n);return[s.resourceId,s]})))}},ya=(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}},ba=(e,n)=>e?.sectionId===n?.sectionId&&e?.lineId===n?.lineId,zf=(e,n)=>{let{section:t}=hn(e,n?.sectionId);return t?.lines?.find(r=>r.id===n?.lineId)},qf=(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},Ia=(e,n,t)=>{if(typeof n?.sectionId!="string")return!1;let{section:r}=hn(e,n.sectionId);return ba({sectionId:n.sectionId,lineId:r?.lines?.[0]?.id},t)},Yf=new Set(["jumpToLine","rollbackByOffset","rollbackToLine","sectionTransition","resetStoryAtSection"]),Cn={always:"always",maybe:"maybe",never:"never"},Hf=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},wa=(e,n)=>{if(!Array.isArray(e?.branches))return!1;for(let t of e.branches){let r=Hf(t);if(r!==Cn.never){if(n(t))return!0;if(r===Cn.always)return!1}}return!1},Aa=e=>wa(e,n=>Object.entries(n?.actions??{}).some(([t,r])=>t==="conditional"?Aa(r):Yf.has(t))),Ea=(e,n,t)=>wa(n,r=>Object.entries(r?.actions??{}).some(([o,i])=>o==="sectionTransition"?Ia(e,i,t):o==="conditional"?Ea(e,i,t):!1)),Wf=(e,n,t)=>{if(!n)return!0;let r=zf(t,e)?.actions;if(!N(r))return!0;if(Ia(t,r.sectionTransition,n))return!1;let o=r.conditional;return o?!(Ea(t,o,n)||!(r.choice?.resourceId||r.form?.resourceId)&&!Aa(o)&&ba(qf(t,e),n)):!0},Kf=(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=ya(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=ha(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)&&!Wf(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}},Jf=(e,n,t)=>{if(!N(e))throw new Error(`Malformed save slot contexts[${t}] entry.`);let r=Ao(n),o=ya(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=lp({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:Kf(e.rollback,o,n)};return s&&(l.runtime=s),l},Xf=(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)=>Jf(t,n,r))}},Qf=(e,n)=>{if(!N(e))throw new Error("Malformed save slot.");let t=ga(e.formatVersion);return{...e,formatVersion:t,state:Xf(e.state,n)}},oa=(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}},Zf=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:oa(e.confirmActions,"confirmActions",{required:!0}),cancelActions:oa(e.cancelActions,"cancelActions")}},On=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},ep=e=>(N(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),$n=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},xa=e=>{if(!(!N(e)||!e.animations))return{animations:k(e.animations)}},np=(e,n)=>{let t=xa(n);if(t){e.global.pendingScreenTransition=t;return}delete e.global.pendingScreenTransition},tp=e=>{let n=e?.id??e?.resourceId;return typeof n=="string"&&n.length>0?n:void 0},rp=(e,n)=>{let t=e?.sectionId,r=e?.lineId;if(!(!t||!r||!n))return`${t}:${r}:${n}`},Bt=e=>String(e??""),va=(e,n)=>{let t=Bt(n);return e?.trim===!0?t.trim():t},op=e=>N(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,n])=>N(n)).map(([n,t])=>[n,{id:n,...k(t)}])):{},ip=(e,n)=>{if(!n||!N(e.global.formDrafts))return;let t=e.global.formDrafts[n];return N(t)?t:void 0},Sa=(e,n)=>{let t=ep(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=va(e,n);return e?.required===!0&&t.length===0?"required":null},sp=({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||{}))},ap=({state:e,form:n,pointer:t})=>{if(!n?.resourceId)return null;let r=tp(n),o=rp(t,r);if(!r||!o)return null;let i=ip(e,o),s=op(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=[],ia="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)},Ra=()=>({...k(qn)}),Ca=({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]=ka(s,k(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},cp=({loadedGlobalRuntime:e={}})=>Ca({loadedRuntime:e,runtimeIds:Dr,defaults:ln,path:"global.runtime"}).runtimeState,lp=({loadedContextRuntime:e={}})=>{let{runtimeState:n,hasLoadedValues:t}=Ca({loadedRuntime:e,runtimeIds:Mr,defaults:Ra(),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},_a=(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)})},up=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)}}),dp=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"})},fp=(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}})},pp=e=>e.runtime?(Mr.forEach(n=>{e.runtime[n]===void 0&&(e.runtime[n]=k(qn[n]))}),e.runtime):(e.runtime=Ra(),e.runtime),mp=e=>rs(e.global),gp=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:mp(e)}})},hp=e=>ts[e],yp=(e,n)=>{let t=hp(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}"`)},ka=(e,n)=>{if(yp(e,n),e==="autoForwardSpeed"&&(n<0||n>100))throw new Error("autoForwardSpeed requires a value between 0 and 100");return e==="saveLoadPagination"?Math.max(1,Math.trunc(n)):n},Oa=(e,n,t)=>{let r=ka(n,t);if(n in qn){let o=rt(e);if(!o)return r;let i=pp(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:Vf(),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,bp=(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,Ip(e,{queueRender:n}),o},Ip=(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)},wp=({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}},Ap=({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},Ep=({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},xp=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)},vp=({state:e},n={})=>{let t=n?.source===ia?ia: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)},Sp=({state:e})=>(mn.pop(),e),Le=(e,n,t)=>{let o=mn[mn.length-1]?.source??wo;if(!_g(n,o))return;let i=xp(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:n,payload:k(t)}))},sa=(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}))}},Rp=(e,n)=>{Array.isArray(n?.executedActions)&&n.executedActions.forEach(({type:t,payload:r})=>{kg(e,t,r)})},Cp=(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])=>{lc(e,l,a)})},Ta=(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"&&(_a(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),Cp(e,r.timeline[l]),Rp(e,r.timeline[l]);let s=Tn(t);s.read={sectionId:o.sectionId,lineId:o.lineId},t.kind==="sceneReplay"&&(t.sceneReplay.entryId=ua(e)),e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},_p=e=>{let{projectData:n}=e,t=e.global??{},{saveSlots:r={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=t;pa(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:Gf(s,"accountViewedRegistry"),nextLineConfig:et(),imageGalleryNavigation:po(),sceneReplayNavigation:ho(),sceneReplayEntryId:0,audioCommandId:0,musicRoomPlayer:zt(),saveSlots:Uf(r),overlayStack:[],variables:p,...cp({loadedGlobalRuntime:i})},contexts:[Eo({pointer:d,projectData:n})]}},kp=({state:e})=>e.global.overlayStack||[],Op=({state:e})=>e.global.pendingEffects,La=({state:e})=>e.global.skipMode,$p=({state:e})=>e.global.autoMode,Pa=({state:e})=>e.global.dialogueUIHidden,Na=({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=Mf({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},Tp=({state:e})=>e.global.confirmDialog??null,ot=({state:e},{pointer:n}={})=>{let t=n??Ce({state:e})?.pointer,r=sp({state:e,pointer:t});return ap({state:e,form:r.form,pointer:t})},Lp=({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=Fa({state:e,pointer:n});return r?{source:_n,resourceId:r}:null},Pp=({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)=>Pp({state:e,registry:e.global.accountViewedRegistry},n),Np=({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]},Dp=({state:e})=>{let n=e.projectData?.resources?.imageGallery;return n===void 0?void 0:k(n)},Da=({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]},Ma=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}),Mp=(e,n)=>({...Ma(n),locked:_o(e,n)}),aa=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")}`},Vp=({state:e})=>{let n=e.projectData?.resources?.musicRoom;return n===void 0?void 0:k(n)},Va=({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=>Mp(e,u)),l=n.tracks.findIndex(u=>u.id===t.trackId),a=n.tracks[l],c=a?{...Ma(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:aa(t.positionMs),durationText:t.durationMs===null?null:aa(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)},jp=({state:e})=>{let n=e.projectData?.resources?.sceneReplay;return n===void 0?void 0:k(n)},Fp=({state:e})=>J(e)!==null,Up=({state:e})=>{let n=J(e);return n?{replayId:n.sceneReplay.replayId,entryId:n.sceneReplay.entryId}:null},ja=({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}}},Bp=({state:e})=>e.global.nextLineConfig,Fa=({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},Ua=({state:e})=>!!Fa({state:e}),Gp=({state:e})=>structuredClone(e),zp=({state:e})=>k(e.projectData.resources?.achievements??{}),qp=({state:e},n)=>{let t=e.projectData.resources?.achievements?.[n?.resourceId];return t===void 0?void 0:k(t)},Ba=({state:e})=>e.global.saveSlots,Yp=({state:e},n)=>{let t=n?.slotId,r=tt(t);return e.global.saveSlots[r]},Lo=({state:e})=>un(e),Hp=({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)},Ga=({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)},Wp=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})=>ta({text:Wp(e),baseDelay:Ye(e,"autoForwardDelay"),speed:Ye(e,"autoForwardSpeed")}),Kp=({state:e})=>{let n=za({state:e}),r=Ht({state:e})?.actions??{},o=cn([n??{},r]);return Tr(n??{},o??{})},Jp=({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},Xp=({state:e},{sectionId:n,includePresentationState:t=!1})=>{let r=Jp({state:e},{sectionId:n});return t?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},za=({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}},Qp=Ba,Zp=Po,em=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},nm=({state:e},n={})=>{let t=Ga({state:e}),r=za({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=Ua({state:e}),h=Da({state:e}),b=Va({state:e}),I=ja({state:e}),E=Yt({state:e}),{saveSlots:A}=Po({state:e}),$=em(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:fc({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||$,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:Na({state:e}),saveSlots:A,variables:E,runtime:u,activePersistentAnimations:d,restoredPersistentAnimations:f,imageGallery:h,musicRoom:b,sceneReplay:I,musicRoomPlayer:k(e.global.musicRoomPlayer)})},tm=({state:e},n)=>(e.global.confirmDialog=Zf(n),e.global.pendingEffects.push({name:"render"}),e),rm=({state:e})=>(e.global.confirmDialog&&(On(e),e.global.pendingEffects.push({name:"render"})),e),om=({state:e},n)=>(e.global.overlayStack.push(n),e.global.pendingEffects.push({name:"render"}),Le(e,"pushOverlay",n),e),im=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Le(e,"popOverlay",void 0),e),sm=({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),am=({state:e})=>(e.global.overlayStack=[],On(e),$n(e),e.global.pendingEffects.push({name:"render"}),Le(e,"clearOverlays",void 0),e),cm=(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,np(e,t),$n(e);let r=Ae({state:e},{pointer:n}),o=r?.source===_n,i=r?.source===Ke;cm(e,{activeInteraction:r});let s=J(e),l={name:"handleLineActions"};if(typeof s?.sceneReplay?.replayId=="string"){let a=ua(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"})},qa=({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),lm=({state:e})=>{let n=e.global.autoMode;return Ae({state:e})&&!n||(n?at({state:e}):qa({state:e})),e},Ya=({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),um=({state:e})=>{let n=La({state:e});return Ae({state:e})&&!n||(n?Je({state:e}):Ya({state:e})),e},Kt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Le(e,"showDialogueUI",void 0),e),Ha=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Le(e,"hideDialogueUI",void 0),e),dm=({state:e})=>(Pa({state:e})?Kt({state:e}):Ha({state:e}),e),Xe=(e,n,t)=>(Oa(e,n,t),gp(e),e.global.pendingEffects.push({name:"render"}),e),ct=(e,n,t,r)=>{let o=Oa(e,n,t);return e.global.pendingEffects.push({name:"render"}),Le(e,r,{value:o}),e},fm=({state:e},n)=>Xe(e,"dialogueTextSpeed",n?.value),pm=({state:e},n)=>Xe(e,"autoForwardDelay",n?.value),mm=({state:e},n)=>Xe(e,"autoForwardSpeed",n?.value),gm=({state:e},n)=>Xe(e,"skipUnseenText",n?.value),hm=({state:e},n)=>Xe(e,"skipTransitionsAndAnimations",n?.value),ym=({state:e},n)=>Xe(e,"soundVolume",n?.value),bm=({state:e},n)=>Xe(e,"musicVolume",n?.value),Im=({state:e},n)=>Xe(e,"muteAll",n?.value),wm=({state:e},n)=>ct(e,"saveLoadPagination",n?.value,"setSaveLoadPagination"),Am=({state:e})=>{let n=Ye(e,"saveLoadPagination")+1;return ct(e,"saveLoadPagination",n,"incrementSaveLoadPagination"),e},Em=({state:e})=>{let n=Ye(e,"saveLoadPagination")-1;return ct(e,"saveLoadPagination",n,"decrementSaveLoadPagination"),e},xm=({state:e},n)=>ct(e,"menuPage",n?.value,"setMenuPage"),vm=({state:e},n)=>ct(e,"menuEntryPoint",n?.value,"setMenuEntryPoint"),Sm=({state:e})=>(e.global.pendingEffects=[],e),Rm=({state:e},n)=>(e.global.pendingEffects.push(n),e),Cm=({state:e},n)=>{if(J(e))return e;let t=n?.resourceId;return da(e,t),e.global.pendingEffects.push({name:"completeAchievement",payload:{resourceId:t}}),e},_m=({state:e},n)=>{if(J(e))return e;let t=n?.resourceId,r=da(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},Wa=(e,{sectionId:n,resetStoryState:t=!1,screen:r})=>{let o=!!xa(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&&!bp(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},km=({state:e},n)=>{if(J(e))throw new Error("Cannot reset the story while a scene replay is active");return Wa(e,{sectionId:n?.sectionId,resetStoryState:!0,screen:n?.screen})},Ka=e=>(e.global.accountViewedRegistry=Nf(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)}))}})},Ja=(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:[]}}])},Om=(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;Om(e,Ka(e),n)&&Ja(e,{sections:[{sectionId:n.sectionId,lastLineId:n.lineId}],resources:[]})},$m=({state:e},n)=>(gn(e,n),e.global.pendingEffects.push({name:"render"}),e),Tm=({state:e},n)=>{if(J(e))return e;let{resourceId:t}=n;if(e.global.accountViewedRegistry!==void 0){let r=Ka(e);r.resources.find(i=>i.resourceId===t)||(r.resources.push({resourceId:t}),Ja(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"}))},Lm=({state:e},n)=>{let t="showImageGalleryVariant";Pe(t,n,_f),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},Xa=(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},Pm=({state:e},n)=>Xa(e,n,-1,"moveToPreviousImageGalleryVariant"),Nm=({state:e},n)=>Xa(e,n,1,"moveToNextImageGalleryVariant"),Dm=({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},Qa=(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},Mm=({state:e},n)=>{if(Pe("moveToImageGalleryPage",n,kf),!Number.isInteger(n.pageIndex)||n.pageIndex<0)throw new Error("moveToImageGalleryPage requires a non-negative integer pageIndex");return Qa(e,n.pageIndex)},Za=(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:Qa(e,s)},Vm=({state:e},n)=>Za(e,n,1,"moveToNextImageGalleryPage"),jm=({state:e},n)=>Za(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}"`)})},Fm=(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"})},ec=(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)},Um=({state:e},n)=>{let t="playMusicRoomTrack";Fe(t,n,Of),Fm(t,n.trackId);let o=e.projectData?.resources?.musicRoom?.tracks.find(i=>i.id===n.trackId);return!o||_o(e,o)||ec(e,o),e},Bm=({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},Gm=({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},zm=({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},qm=({state:e},n)=>{if(Fe("seekMusicRoom",n,$f),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},nc=(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&&ec(e,l),e},Ym=({state:e},n)=>nc(e,n,-1,"playPreviousMusicRoomTrack"),Hm=({state:e},n)=>nc(e,n,1,"playNextMusicRoomTrack"),Wm=({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},tc=(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},Km=({state:e},n)=>{if(Fe("moveToMusicRoomPage",n,Tf),!Number.isInteger(n.pageIndex)||n.pageIndex<0)throw new Error("moveToMusicRoomPage requires a non-negative integer pageIndex");return tc(e,n.pageIndex)},rc=(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:tc(e,i)},Jm=({state:e},n)=>rc(e,n,1,"moveToNextMusicRoomPage"),Xm=({state:e},n)=>rc(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(),fp(e,t),e.global.pendingEffects.push({name:"render"}),!0},Qm=({state:e},n)=>{let t="startSceneReplay";if(Pe(t,n,Lf),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=up(e);dp(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 _a(e,c),e.contexts.push(c),st(e,c.pointers.read),e},oc=({state:e},n)=>{Pe("finishSceneReplay",n,go);let r=J(e);return r&&(r.sceneReplay.finishOnNextAdvance=!0),e},Zm=({state:e},n)=>(Pe("exitSceneReplay",n,go),pn(e),e),ic=(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},eg=({state:e},n)=>{if(Pe("moveToSceneReplayPage",n,Pf),!Number.isInteger(n.pageIndex)||n.pageIndex<0)throw new Error("moveToSceneReplayPage requires a non-negative integer pageIndex");return ic(e,n.pageIndex)},sc=(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:ic(e,i)},ng=({state:e},n)=>sc(e,n,1,"moveToNextSceneReplayPage"),tg=({state:e},n)=>sc(e,n,-1,"moveToPreviousSceneReplayPage"),Xt=(e,n)=>{let t=e.global.musicRoomPlayer;return!N(n)||n.id!==Rf||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,ac=(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),rg=({state:e},n)=>{let t=Xt(e,n);return!t||t.readiness!=="loading"||!Do(n)?e:ac(e,t,n,{readiness:"ready"})},og=({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:ac(e,t,n)},ig=({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},sg=({state:e},n)=>{let t=Xt(e,n);if(!t||typeof n.errorCode!="string"||!Cf.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},cc=({state:e},n)=>{let t=jf(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},ag=({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),Bf(c.rollback)});let l={contexts:s},a={formatVersion:la,slotId:ma(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},cg=({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=Qf(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},lg=({state:e},n)=>{if(J(e))throw new Error("Cannot update project data while a scene replay is active");let{projectData:t}=n;pa(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},ug=({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},dg=({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},fg=({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},pg=({state:e},n)=>Wa(e,{sectionId:n?.sectionId,screen:n?.screen}),mg=({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},gg=(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}},hg=(e,n)=>({id:e.id,key:e.key,valid:!0,values:k(n),fields:k(e.fields),fieldList:k(e.fieldList)}),yg=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})},bg=({state:e},n={})=>{let t=Mo(e,n),r=n.field;if(!t?.fields?.[r])return e;let o=Sa(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},Ig=({state:e},n={})=>{let t=Mo(e,n);if(!t)return{submitted:!1,valid:!1,reason:"inactive"};let r=Sa(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]=va(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}=gg(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=hg(t,o);return yg(e),delete e.global.formDrafts[t.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},wg=({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"}},Ag=({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},ca=e=>(n,t)=>e({state:n},t),Eg=e=>({variables:Bn({variables:{...e.global?.variables??{},...rt(e)?.variables??{}},runtime:un(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:un(e)}),xg=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")},vg=(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")},Sg=(e,n)=>{xg(n);for(let t=0;t<n.branches.length;t+=1){let r=n.branches[t];if(vg(r,t,n.branches.length),!(Object.prototype.hasOwnProperty.call(r,"when")&&!Vn(r.when,Eg(e)))){Object.entries(r.actions).forEach(([i,s])=>{lc(e,i,s)});return}}},Rg={conditional:{replayLine:Sg},updateVariable:{recordSources:[wo],replayLine:sa,replayRecorded:sa,persistInSaveSlot:!0},setNextLineConfig:{replayLine:ca(cc)},finishSceneReplay:{replayLine:ca(oc)}},Qt=e=>Rg[e]??null,Cg=e=>Qt(e)?.persistInSaveSlot===!0,_g=(e,n)=>{let t=Qt(e)?.recordSources;return Array.isArray(t)&&t.includes(n)},kg=(e,n,t)=>{Qt(n)?.replayRecorded?.(e,t)},lc=(e,n,t)=>{Qt(n)?.replayLine?.(e,t)},Og=e=>e?.returnable!==!1,uc=(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(Og(e.timeline[r])&&(t-=1,t===0))return r;return-1},dc=({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=uc(o,t);if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},fc=({state:e})=>dc({state:e},{offset:-1})!==null,$g=({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=uc(o,t);return i<0||i>=o.timeline.length?e:Ta(e,i)},Tg=({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:Ta(e,l)},pc=e=>{let n=_p(e);return Ti(n,{selectPendingEffects:Op,selectSkipMode:La,selectAutoMode:$p,selectIsChoiceVisible:Ua,selectIsFormVisible:Lp,selectActiveInteraction:Ae,selectActiveForm:ot,selectDialogueUIHidden:Pa,selectDialogueHistory:Na,selectConfirmDialog:Tp,selectIsLineAccountViewed:So,selectIsResourceAccountViewed:Np,selectImageGalleryConfig:Dp,selectImageGallery:Da,selectMusicRoomConfig:Vp,selectMusicRoom:Va,selectSceneReplayConfig:jp,selectSceneReplay:ja,selectIsSceneReplayActive:Fp,selectActiveSceneReplayEntry:Up,selectNextLineConfig:Bp,selectSystemState:Gp,selectAchievements:zp,selectAchievement:qp,selectSaveSlotMap:Ba,selectSaveSlots:Qp,selectSaveSlot:Yp,selectRuntime:Lo,selectRuntimeValue:Hp,selectAllVariables:Yt,selectCurrentPointer:Ce,selectSection:de,selectCurrentLine:Ht,selectPresentationState:Ga,selectAutoForwardTimerDelay:it,selectPresentationChanges:Kp,selectSectionLineChanges:Xp,selectSaveSlotPage:Po,selectCurrentPageSlots:Zp,selectRenderState:nm,selectOverlayStack:kp,selectLineIdByOffset:dc,selectCanRollback:fc,selectRollbackCursor:wp,startAutoMode:qa,stopAutoMode:at,toggleAutoMode:lm,startSkipMode:Ya,stopSkipMode:Je,toggleSkipMode:um,showDialogueUI:Kt,hideDialogueUI:Ha,toggleDialogueUI:dm,setDialogueTextSpeed:fm,setAutoForwardDelay:pm,setAutoForwardSpeed:mm,setSkipUnseenText:gm,setSkipTransitionsAndAnimations:hm,setSoundVolume:ym,setMusicVolume:bm,setMuteAll:Im,setSaveLoadPagination:wm,incrementSaveLoadPagination:Am,decrementSaveLoadPagination:Em,setMenuPage:xm,setMenuEntryPoint:vm,showConfirmDialog:tm,hideConfirmDialog:rm,resetStoryAtSection:km,clearPendingEffects:Sm,appendPendingEffect:Rm,completeAchievement:Cm,setAchievementProgress:_m,beginRollbackActionBatch:vp,endRollbackActionBatch:Sp,markRollbackCheckpointTransient:Ap,markSavedRollbackCheckpointTransient:Ep,addViewedLine:$m,addViewedResource:Tm,showImageGalleryVariant:Lm,moveToPreviousImageGalleryVariant:Pm,moveToNextImageGalleryVariant:Nm,clearImageGallerySelection:Dm,moveToImageGalleryPage:Mm,moveToNextImageGalleryPage:Vm,moveToPreviousImageGalleryPage:jm,playMusicRoomTrack:Um,playMusicRoom:Bm,pauseMusicRoom:Gm,stopMusicRoom:zm,seekMusicRoom:qm,playPreviousMusicRoomTrack:Ym,playNextMusicRoomTrack:Hm,clearMusicRoomSelection:Wm,moveToMusicRoomPage:Km,moveToNextMusicRoomPage:Jm,moveToPreviousMusicRoomPage:Xm,musicRoomSoundReady:rg,musicRoomSoundProgress:og,musicRoomSoundComplete:ig,musicRoomSoundError:sg,startSceneReplay:Qm,finishSceneReplay:oc,exitSceneReplay:Zm,moveToSceneReplayPage:eg,moveToNextSceneReplayPage:ng,moveToPreviousSceneReplayPage:tg,setNextLineConfig:cc,saveSlot:ag,loadSlot:cg,updateProjectData:lg,sectionTransition:pg,jumpToLine:ug,nextLine:dg,markLineCompleted:fg,rollbackToLine:Tg,rollbackByOffset:$g,pushOverlay:om,popOverlay:im,replaceLastOverlay:sm,clearOverlays:am,updateFormField:bg,submitForm:Ig,cancelForm:wg,updateVariable:Ag,nextLineFromSystem:mg},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var Lg="route-engine",Pg="projectPersistence";var gc=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),se=e=>Object.prototype.toString.call(e)==="[object Object]",mc="variables.",Ng=(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)}},Dg=(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)}},Mg=(e,n)=>{let t=Dg(e),r=Ng(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}},hc=(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:{}}},Vg=(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(mc)?n.path.slice(mc.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}].`)})},jg=(e,n)=>{let t={};return Vg(n).forEach(r=>{if(r.path==="viewedRegistry"){t.accountViewedRegistry=Mg(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},Fg=e=>{let n=Vo(e);if(!n)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return n},Ug=e=>{let n=e??globalThis.indexedDB;if(!n)throw new Error("IndexedDB is not available in this environment.");return n},Bg=({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}".`))}}),Gg=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=hc(c.result),g=typeof r=="function"?r(p):r,h={namespace:t,version:1,...gc(),...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}".`))}})},zg=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=Lg,objectStoreName:r=Pg,namespace:o}=e,i=Ug(n),s=Fg(o),l=Bg({indexedDB:i,databaseName:t,objectStoreName:r});return{namespace:s,load:async()=>{let a=await Gg({databasePromise:l,objectStoreName:r,namespace:s});return{...gc(),...hc(a)}},clear:async()=>zg({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=>jg(c,a)})}},qg=jo;var Yg=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Hg=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),yc="conditional",Bo=Symbol("conditionalAutoContinue"),Wg=new Set(["sectionTransition","resetStoryAtSection"]),Kg=new Set(["nextLine","nextLineFromSystem","resetStoryAtSection","sectionTransition"]),Jg=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),Fo="form",Xg=new Set(["submitForm","cancelForm"]),Qg="showImageGalleryVariant",Zg="playMusicRoomTrack",eh="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=pc(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,Ec=m=>{m.savedCheckpointOccurrences.forEach(w=>{n.markSavedRollbackCheckpointTransient(w)}),m.savedCheckpointOccurrences=[]},xc=(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}),Ec(m))},vc=(m,w,v)=>Kg.has(m)?m==="resetStoryAtSection"?v?.checkpoint!==w?.checkpoint:v?.checkpoint!==w?.checkpoint&&v?.checkpointIndex>w?.checkpointIndex:!1,Sc=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})},Rc=(m,w,v)=>{let _=l.at(-1);if(!_)return;let D=n.selectCurrentPointer()?.pointer,F=vc(m,w,v);if(Uo(_.pointer,D)){let X=v?.checkpoint!==w?.checkpoint||v?.checkpointIndex!==w?.checkpointIndex;(F||X&&Jg.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"&&Cc(w),Wg.has(m)&&(s+=1);let v=n.selectIsSceneReplayActive?.()===!0,_=Hg.has(m)?p(c):null,D=n.selectRollbackCursor?.()??null,F=n[m](w);Yg.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"&&Sc(w),Rc(m,D,Z),b(),F},Cc=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)},_c=(m,w,v)=>{let _=n.selectCurrentPointer()?.pointer;w!==_||v!==s||(n.appendPendingEffect({name:"clearAutoNextTimer"}),n.appendPendingEffect({name:"clearNextLineConfigTimer"}),dt("nextLineFromSystem",m.payload))},kc=()=>({renderSequence:t,conditionalRoutingSequence:s,rollbackNavigationContexts:l.slice(),pendingRollbackLineEntrySaveHandoff:a,persistentAnimationSessions:new Map(c),restoredPersistentAnimationSessions:new Map(u),renderPersistentAnimationMetadata:new Map(d)}),Oc=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=kc();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(_)&&_c(_,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 Oc(v),_}}),Ho=(m,w,v,_={})=>{if(m===yc)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():{}}},Tc=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}:{}}}},Lc=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},Pc=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},Nc=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")},Dc=(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)=>{Nc(m);let _=Te(v);for(let D=0;D<m.branches.length;D+=1){let F=m.branches[D];Dc(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 _},Mc=(m,w)=>({...m??{},_form:w}),Vc=(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,Mc(v,D.form),{..._,interactionSource:Fo})},jc=(m,w,v,_)=>{let D=er(v),F={templatePayload:w,literalTargetIds:null};m===Qg?F=Tc(w):m===Zg?F=Lc(w):m===eh&&(F=Pc(w));let{templatePayload:X,literalTargetIds:Z}=F,Jo=Pr({[m]:X},D)[m],Xo=Z?{...Jo,...Z}:Jo;if(m===yc)return Wo(Xo,v,_);let Qo=H(m,Xo,_);if(Xg.has(m))return Vc(m,Qo,v,_);dt(m,Qo)},nr=(m,w,v)=>{let _;return Object.entries(m).forEach(([D,F])=>{let X=jc(D,F,w,v);Zt(X)&&(_=he(_,X))}),_},Ko=(m,w,v={})=>Yo(()=>nr(m,w,v),v),Fc=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=xc(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 Fc(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}}},nh=80,th="music-room:player",wc=new Map([["soundReady","musicRoomSoundReady"],["soundProgress","musicRoomSoundProgress"],["soundComplete","musicRoomSoundComplete"],["soundError","musicRoomSoundError"]]),bc=(e,n)=>wc.has(e)&&n?._event?.id===th,Ac=({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)},rh=({engine:e,routeGraphics:n,trackRenderDispatch:t,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions(o);(r?.()??0)===i&&Ac({engine:e,routeGraphics:n,trackRenderDispatch:t},o)},oh=({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)},ih=({ticker:e,autoTimer:n},t)=>{let r=n.getCallback();r&&(e.remove(r),n.setCallback(null)),n.setElapsed(0)},sh=({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??nh;t.getElapsed()>=l&&(t.setElapsed(0),ut(e,"nextLineFromSystem",{}))};t.setCallback(i),n.add(i)},ah=({ticker:e,skipTimer:n},t)=>{let r=n.getCallback();r&&(e.remove(r),n.setCallback(null)),n.setElapsed(0)},ch=({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)},lh=({ticker:e,nextLineConfigTimerState:n},t)=>{let r=n.getCallback();r&&(e.remove(r),n.setCallback(null)),n.setElapsed(0)},uh=({enqueuePersistenceWrite:e},n)=>{e(t=>t.saveSlots(n?.saveSlots))},dh=({enqueuePersistenceWrite:e},n)=>{e(t=>t.saveGlobalDeviceVariables(n?.globalDeviceVariables))},fh=({enqueuePersistenceWrite:e},n)=>{e(t=>t.saveGlobalAccountVariables(n?.globalAccountVariables))},ph=({enqueuePersistenceWrite:e},n)=>{e(t=>t.saveGlobalRuntime(n?.globalRuntime))},mh=({enqueuePersistenceWrite:e},n)=>{e(t=>{if(typeof t.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return t.applyScopedDataUpdates(n?.updates)})},Ic={render:Ac,saveSlots:uh,saveGlobalDeviceVariables:dh,saveGlobalAccountVariables:fh,saveGlobalRuntime:ph,applyScopedDataUpdates:mh,handleLineActions:rh,startAutoNextTimer:oh,clearAutoNextTimer:ih,startSkipNextTimer:sh,clearSkipNextTimer:ah,nextLineConfigTimer:ch,clearNextLineConfigTimer:lh},gh=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)},hh=(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(!gh.has(o.name)){t.unshift(o);continue}n.has(o.name)||(n.add(o.name),t.unshift(o))}return t},yh=({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(bc(x,C)){let Q=wc.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(bc(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=hh(x),Q=O.some(H=>H.name==="handleLineActions");O.forEach(H=>{if(!Ic[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=Ic[H.name];if(Te){Te(Ie,H.payload);continue}r(H,Ie)}};return le.handleRouteGraphicsEvent=T,le.createRouteGraphicsEventHandler=fe,le},bh=yh;var Ih=(e,n={})=>{let{resources:t={}}=n;return io(e,t)};var Xy=Go;export{Vr as DEFAULT_VISUAL_LAYER,xn as RENDER_LAYER,Ne as VISUAL_LAYER,bh as createEffectsHandler,qg as createIndexedDbPersistence,Xy as default,$r as formatDate,uu as resolveComputedVariables,Ih as resolveLayoutReferences};