route-engine-js 1.29.1 → 1.29.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/RouteEngine.js +1 -1
- package/package.json +1 -1
package/dist/RouteEngine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Ss=Object.defineProperty;var _s=(e,t)=>{for(var r in t)Ss(e,r,{get:t[r],enumerable:!0})};var Gn=Symbol.for("immer-nothing"),zn=Symbol.for("immer-draftable"),fe=Symbol.for("immer-state");function be(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var rt=Object.getPrototypeOf;function de(e){return!!e&&!!e[fe]}function Ue(e){return e?Kn(e)||Array.isArray(e)||!!e[zn]||!!e.constructor?.[zn]||Nt(e)||Vt(e):!1}var Rs=Object.prototype.constructor.toString();function Kn(e){if(!e||typeof e!="object")return!1;let t=rt(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===Rs}function kt(e,t){Pt(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function Pt(e){let t=e[fe];return t?t.type_:Array.isArray(e)?1:Nt(e)?2:Vt(e)?3:0}function xr(e,t){return Pt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Jn(e,t,r){let n=Pt(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function Os(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Nt(e){return e instanceof Map}function Vt(e){return e instanceof Set}function Me(e){return e.copy_||e.base_}function vr(e,t){if(Nt(e))return new Map(e);if(Vt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=Kn(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[fe];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],c=n[s];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(n[s]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[s]})}return Object.create(rt(e),n)}else{let n=rt(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function Or(e,t=!1){return jt(e)||de(e)||!Ue(e)||(Pt(e)>1&&(e.set=e.add=e.clear=e.delete=Ls),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>Or(n,!0))),e}function Ls(){be(2)}function jt(e){return Object.isFrozen(e)}var $s={};function Be(e){let t=$s[e];return t||be(0,e),t}var dt;function Xn(){return dt}function ks(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Wn(e,t){t&&(Be("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Cr(e){Sr(e),e.drafts_.forEach(Ds),e.drafts_=null}function Sr(e){e===dt&&(dt=e.parent_)}function qn(e){return dt=ks(dt,e)}function Ds(e){let t=e[fe];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Hn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[fe].modified_&&(Cr(t),be(4)),Ue(e)&&(e=Dt(t,e),t.parent_||Tt(t,e)),t.patches_&&Be("Patches").generateReplacementPatches_(r[fe].base_,e,t.patches_,t.inversePatches_)):e=Dt(t,r,[]),Cr(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Gn?e:void 0}function Dt(e,t,r){if(jt(t))return t;let n=t[fe];if(!n)return kt(t,(o,i)=>Yn(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return Tt(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let o=n.copy_,i=o,s=!1;n.type_===3&&(i=new Set(o),o.clear(),s=!0),kt(i,(c,a)=>Yn(e,n,o,c,a,r,s)),Tt(e,o,!1),r&&e.patches_&&Be("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function Yn(e,t,r,n,o,i,s){if(de(o)){let c=i&&t&&t.type_!==3&&!xr(t.assigned_,n)?i.concat(n):void 0,a=Dt(e,o,c);if(Jn(r,n,a),de(a))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(Ue(o)&&!jt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Dt(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&Tt(e,o)}}function Tt(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Or(t,r)}function Ts(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:Xn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=Lr;r&&(o=[n],i=pt);let{revoke:s,proxy:c}=Proxy.revocable(o,i);return n.draft_=c,n.revoke_=s,c}var Lr={get(e,t){if(t===fe)return e;let r=Me(e);if(!xr(r,t))return Ps(e,r,t);let n=r[t];return e.finalized_||!Ue(n)?n:n===wr(e.base_,t)?(Er(e),e.copy_[t]=Rr(n,e)):n},has(e,t){return t in Me(e)},ownKeys(e){return Reflect.ownKeys(Me(e))},set(e,t,r){let n=Qn(Me(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=wr(Me(e),t),i=o?.[fe];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(Os(r,o)&&(r!==void 0||xr(e.base_,t)))return!0;Er(e),_r(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return wr(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Er(e),_r(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Me(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){be(11)},getPrototypeOf(e){return rt(e.base_)},setPrototypeOf(){be(12)}},pt={};kt(Lr,(e,t)=>{pt[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});pt.deleteProperty=function(e,t){return pt.set.call(this,e,t,void 0)};pt.set=function(e,t,r){return Lr.set.call(this,e[0],t,r,e[0])};function wr(e,t){let r=e[fe];return(r?Me(r):e)[t]}function Ps(e,t,r){let n=Qn(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function Qn(e,t){if(!(t in e))return;let r=rt(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=rt(r)}}function _r(e){e.modified_||(e.modified_=!0,e.parent_&&_r(e.parent_))}function Er(e){e.copy_||(e.copy_=vr(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Ns=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,n)=>{if(typeof t=="function"&&typeof r!="function"){let i=r;r=t;let s=this;return function(a=i,...l){return s.produce(a,f=>r.call(this,f,...l))}}typeof r!="function"&&be(6),n!==void 0&&typeof n!="function"&&be(7);let o;if(Ue(t)){let i=qn(this),s=Rr(t,void 0),c=!0;try{o=r(s),c=!1}finally{c?Cr(i):Sr(i)}return Wn(i,n),Hn(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===Gn&&(o=void 0),this.autoFreeze_&&Or(o,!0),n){let i=[],s=[];Be("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else be(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...c)=>this.produceWithPatches(s,a=>t(a,...c));let n,o;return[this.produce(t,r,(s,c)=>{n=s,o=c}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Ue(e)||be(8),de(e)&&(e=ze(e));let t=qn(this),r=Rr(e,void 0);return r[fe].isManual_=!0,Sr(t),r}finishDraft(e,t){let r=e&&e[fe];(!r||!r.isManual_)&&be(9);let{scope_:n}=r;return Wn(n,t),Hn(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let o=t[r];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}r>-1&&(t=t.slice(r+1));let n=Be("Patches").applyPatches_;return de(e)?n(e,t):this.produce(e,o=>n(o,t))}};function Rr(e,t){let r=Nt(e)?Be("MapSet").proxyMap_(e,t):Vt(e)?Be("MapSet").proxySet_(e,t):Ts(e,t);return(t?t.scope_:Xn()).drafts_.push(r),r}function ze(e){return de(e)||be(10,e),Zn(e)}function Zn(e){if(!Ue(e)||jt(e))return e;let t=e[fe],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=vr(e,t.scope_.immer_.useStrictShallowCopy_)}else r=vr(e,!0);return kt(r,(n,o)=>{Jn(r,n,Zn(o))}),t&&(t.finalized_=!1),r}var pe=new Ns,$r=pe.produce,_d=pe.produceWithPatches.bind(pe),Rd=pe.setAutoFreeze.bind(pe),Od=pe.setUseStrictShallowCopy.bind(pe),Ld=pe.applyPatches.bind(pe),$d=pe.createDraft.bind(pe),kd=pe.finishDraft.bind(pe);var m={LITERAL:0,VARIABLE:1,INTERPOLATION:2,FUNCTION:3,BINARY:4,UNARY:5,CONDITIONAL:6,LOOP:7,OBJECT:8,ARRAY:9,PARTIAL:10,PATH_REFERENCE:11},O={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},nt={NOT:0};var E=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},ue=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var kr=e=>{if(!e||e.trim()==="")throw new E("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new E(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${r}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let r of t)if(e.trim().endsWith(r))throw new E(`Incomplete comparison expression - missing right operand (got: '${e}')`)},eo=e=>{if(e.trim().endsWith(" in"))throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new E(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);let n=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of n){if(!o)throw new E(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new E(`Invalid loop syntax (got: '$for ${e}')`)}};var to=(e,t,r=!1)=>{if(t===null)return new ue(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new ue(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new ue(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new ue(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},ro=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new ue(`Unknown function '${e}' (${r})`)};var Vs=(e,t,r={})=>{let n={},o={};r&&typeof r=="object"&&(r.functions!==void 0||r.partials!==void 0?(n=r.functions||{},o=r.partials||{}):typeof r=="object"&&(n=r));let s=$(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},$=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return Y(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return Y(e.path,r,n);if(e.type===m.INTERPOLATION)return Fs(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return oo(e,t,r,n);case m.BINARY:return io(e,t,r,n);case m.UNARY:return so(e,t,r,n);case m.CONDITIONAL:return Us(e,t,r,n);case m.LOOP:return Hs(e,t,r,n);case m.OBJECT:return Gs(e,t,r,n);case m.ARRAY:return Ks(e,t,r,n);case m.PARTIAL:return Js(e,t,r,n);case m.PATH_REFERENCE:return Xs(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},no=new Map,js=e=>{let t=[],r="",n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")r&&(t.push({type:"property",value:r}),r=""),n=!0;else if(i==="]"){if(n&&r){let s=r.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let c=s.slice(1,-1);t.push({type:"property",value:c})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},Y=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=no.get(e);if(!n){let i=[],s="",c=0;for(let a=0;a<e.length;a++){let l=e[a];l==="["?(c++,s+=l):l==="]"?(c--,s+=l):l==="."&&c===0?s&&(i.push(s),s=""):s+=l}s&&i.push(s),n=[];for(let a of i){let l=js(a.trim());n.push(...l)}no.set(e,n)}let o=t;for(let i=0;i<n.length;i++){let s=n[i];if(s.type==="property"&&s.value in r){o=r[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},Fs=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=$(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},oo=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw ro(e.name,o);let s=e.args.map(c=>$(c,t,r,n));return i(...s)},$e=(e,t,r,n)=>{if(e.var&&!e.type)return Y(e.var,r,n);switch(e.type){case m.VARIABLE:return Y(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return io(e,t,r,n);case m.UNARY:return so(e,t,r,n);case m.FUNCTION:return oo(e,t,r,n);default:return $(e,t,r,n)}},io=(e,t,r,n)=>{if(e.op===O.AND||e.op===O.OR){let s=$e(e.left,t,r,n),c=$e(e.right,t,r,n);switch(e.op){case O.AND:return s&&c;case O.OR:return s||c}}let o=$(e.left,t,r,n),i=$(e.right,t,r,n);switch(e.op){case O.EQ:return o==i;case O.NEQ:return o!=i;case O.GT:return o>i;case O.LT:return o<i;case O.GTE:return o>=i;case O.LTE:return o<=i;case O.IN:return Array.isArray(i)?i.includes(o):!1;case O.ADD:if(typeof o!="number"||typeof i!="number")throw new ue(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case O.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new ue(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},so=(e,t,r,n)=>{let o=e.op===nt.NOT?$e(e.operand,t,r,n):$(e.operand,t,r,n);if(e.op===nt.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Ms=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(Y(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let c={};for(let a of s.properties){let l=a.parsedKey?$(a.parsedKey,t,r,n):a.key,f=a.value;if(f.type===m.LITERAL)c[l]=f.value;else if(f.type===m.VARIABLE)c[l]=Y(f.path,r,n);else if(f.type===m.INTERPOLATION){let u=[];for(let d of f.parts)if(typeof d=="string")u.push(d);else if(d.type===m.VARIABLE){let p=Y(d.path,r,n);u.push(p!=null?String(p):"")}else{let p=$(d,t,r,n);u.push(p!=null?String(p):"")}c[l]=u.join("")}else c[l]=$(f,t,r,n)}return c}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let c={};for(let a of s.properties){let l=a.parsedKey?$(a.parsedKey,t,r,n):a.key,f=a.value;if(f.type===m.LITERAL)c[l]=f.value;else if(f.type===m.VARIABLE)c[l]=Y(f.path,r,n);else if(f.type===m.INTERPOLATION){let u=[];for(let d of f.parts)if(typeof d=="string")u.push(d);else if(d.type===m.VARIABLE){let p=Y(d.path,r,n);u.push(p!=null?String(p):"")}else{let p=$(d,t,r,n);u.push(p!=null?String(p):"")}c[l]=u.join("")}else c[l]=$(f,t,r,n)}return c}}}return null},Us=(e,t,r,n)=>{let o=Ms(e,t,r,n);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||$e(s,t,r,n))return $(e.bodies[i],t,r,n)}return ao},Bs=(e,t)=>{let r=e.body,n=e.itemVar;if(r.type===m.CONDITIONAL&&r.conditions.length===1&&r.conditions[0].type===m.VARIABLE){let o=r.conditions[0].path,i=r.bodies[0];if(o.startsWith(n+".")){let s=o.substring(n.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let a of i.properties)if(a.parsedKey)return null;let c=[];for(let a=0;a<t.length;a++){let l=t[a];if(l[s]){let f={};for(let u of i.properties){let d=u.key,p=u.value;if(p.type===m.LITERAL)f[d]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)f[d]=l;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);f[d]=l[g]}else return null}else if(p.type===m.INTERPOLATION){let h=[],g=!0;for(let y of p.parts)if(typeof y=="string")h.push(y);else if(y.type===m.VARIABLE){let b=y.path;if(b===n)h.push(l!=null?String(l):"");else if(b.startsWith(n+".")){let A=b.substring(n.length+1),x=l[A];h.push(x!=null?String(x):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;f[d]=h.join("")}else return null}c.push(f)}}return c}}}return null},zs=(e,t)=>{let r=e.body,n=e.itemVar,o=Bs(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let c of r.properties)if(c.parsedKey)return null;let i=[],s=!0;for(let c of r.properties){let a=c.key,l=c.value;if(l.type===m.LITERAL)i.push({key:a,type:"literal",value:l.value});else if(l.type===m.VARIABLE){let f=l.path;if(f===n)i.push({key:a,type:"item"});else if(f.startsWith(n+".")){let u=f.substring(n.length+1);if(!u.includes(".")&&!u.includes("["))i.push({key:a,type:"prop",prop:u});else{s=!1;break}}else{s=!1;break}}else if(l.type===m.INTERPOLATION&&l.parts.length===1){let f=l.parts[0];if(f.type===m.VARIABLE){let u=f.path;if(u===n)i.push({key:a,type:"item_string"});else if(u.startsWith(n+".")){let d=u.substring(n.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:a,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let c=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let a=0;a<t.length;a++){let l=t[a];c[a]={id:l.id,title:l.title!=null?String(l.title):"",completed:l.completed}}else for(let a=0;a<t.length;a++){let l=t[a],f={};for(let u of i)if(u.type==="literal")f[u.key]=u.value;else if(u.type==="item")f[u.key]=l;else if(u.type==="prop")f[u.key]=l[u.prop];else if(u.type==="item_string")f[u.key]=l!=null?String(l):"";else if(u.type==="prop_string"){let d=l[u.prop];f[u.key]=d!=null?String(d):""}c[a]=f}return c}}return null},Ws=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let c=e.itemVar,a=e.indexVar;for(let l=0;l<o.length;l++){let f=o[l],u={},d={...n,[c]:f,...a&&{[a]:l}};d.__paths__||(d.__paths__=n.__paths__||{});let p=e.iterable.path||"";if(n&&n.__paths__&&p){let h=p.split("."),g=h[0];g in n.__paths__&&(p=n.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}d.__paths__={...d.__paths__,[c]:`${p}[${l}]`,...a&&{[a]:l}};for(let h of s.properties){let g=h.parsedKey?$(h.parsedKey,t,r,d):h.key,y=h.value;if(y.type===m.LITERAL)u[g]=y.value;else if(y.type===m.VARIABLE){let b=y.path;if(b===c)u[g]=f;else if(b===a)u[g]=l;else if(b.startsWith(c+".")){let A=b.substring(c.length+1);!A.includes(".")&&!A.includes("[")?u[g]=f[A]:u[g]=Y(b,r,{...n,[c]:f,...a&&{[a]:l}})}else u[g]=Y(b,r,{...n,[c]:f,...a&&{[a]:l}})}else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let x=A.path,S;if(x===c)S=f;else if(x===a)S=l;else if(x.startsWith(c+".")){let P=x.substring(c.length+1);!P.includes(".")&&!P.includes("[")?S=f[P]:S=Y(x,r,{...n,[c]:f,...a&&{[a]:l}})}else S=Y(x,r,{...n,[c]:f,...a&&{[a]:l}});b.push(S!=null?String(S):"")}else{let x={...n,[c]:f,...a&&{[a]:l}},S=$(A,t,r,x);b.push(S!=null?String(S):"")}u[g]=b.join("")}else{let b={...n,[c]:f,...a&&{[a]:l}};u[g]=$(y,t,r,b)}}i.push(u)}return i}return null},qs=(e,t,r)=>{let n=e.body;if(n.type===m.OBJECT&&n.properties.length===1&&n.properties[0].key==="$if item.visible"){let i=n.properties[0].value;if(i.type===m.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===m.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===m.OBJECT&&s.properties.length===2){let c=s.properties[0],a=s.properties[1];if(c.key==="id"&&c.value.type===m.VARIABLE&&c.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===m.CONDITIONAL){let l=[];for(let f=0;f<t.length;f++){let u=t[f];if(u.visible){let d={id:u.id};u.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${u.name}`):(d.highlight=!1,d.message=u.name),l.push(d)}}return l}}}}return null},Hs=(e,t,r,n)=>{let o=$(e.iterable,t,r,n);if(!Array.isArray(o)){let l,f=!1;if(e.iterable.type===m.FUNCTION){f=!0;let d=e.iterable.args.map(p=>p.type===m.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===m.VARIABLE?p.path:p.type===m.FUNCTION?`${p.name}(...)`:"?").join(", ");l=`${e.iterable.name}(${d})`}else l=e.iterable.path||"undefined";let u=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw to(u,o,f)}if(!e.indexVar){let l=qs(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=zs(e,o);if(l!==null)return l}let i=Ws(e,t,r,n,o);if(i!==null)return i;let s=[],c=e.iterable.path||"";if(n&&n.__paths__&&c){let l=c.split("."),f=l[0];f in n.__paths__&&(c=n.__paths__[f],l.length>1&&(c+="."+l.slice(1).join(".")))}let a=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(l=>l.type===m.OBJECT&&l.properties.some(f=>f.key.startsWith("$if ")||f.key.startsWith("$when "))));for(let l=0;l<o.length;l++){let f=e.indexVar?{...n,[e.itemVar]:o[l],[e.indexVar]:l}:{...n,[e.itemVar]:o[l]};f.__paths__||(f.__paths__=n.__paths__||{}),f.__paths__={...f.__paths__,[e.itemVar]:`${c}[${l}]`},e.indexVar&&(f.__paths__[e.indexVar]=l);let u=$(e.body,t,r,f);if(Array.isArray(u)&&u.length===1&&!a){let d=u[0];s.push(d===void 0?{}:d)}else s.push(u===void 0?{}:u)}return s},Ys=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?$(o.parsedKey,t,r,n):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let c={},a={},l=!0;for(let f of s.properties){let u=f.parsedKey?$(f.parsedKey,t,r,n):f.key,d=f.value;if(d.type===m.LITERAL)a[u]=d.value;else if(d.type===m.VARIABLE)a[u]=Y(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=Y(h.path,r,n);p.push(g!=null?String(g):"")}else{l=!1;break}if(!l)break;a[u]=p.join("")}else if(d.type===m.OBJECT&&d.properties.length<=5){let p={};for(let h of d.properties){let g=h.key,y=h.value;if(y.type===m.LITERAL)p[g]=y.value;else if(y.type===m.VARIABLE)p[g]=Y(y.path,r,n);else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let x=Y(A.path,r,n);b.push(x!=null?String(x):"")}else{l=!1;break}if(!l)break;p[g]=b.join("")}else{l=!1;break}}if(!l)break;a[u]=p}else{l=!1;break}}if(l)return c[i]=a,c}}return null},Gs=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!$e(e.whenCondition,o,r,n))return;let i=Ys(e,t,r,n);if(i!==null)return i;if(e.fast){let l={};for(let f of e.properties){let u=f.parsedKey?$(f.parsedKey,t,r,n):f.key,d=f.value;if(d.type===m.LITERAL)l[u]=d.value;else if(d.type===m.VARIABLE)l[u]=Y(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=Y(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=$(h,t,r,n);p.push(g!=null?String(g):"")}l[u]=p.join("")}else l[u]=$(d,t,r,n)}return l}let s={},c=null,a=!1;for(let l of e.properties)if(!l.key.startsWith("$if ")&&!l.key.match(/^\$if\s+\w+.*:?$/)&&!l.key.startsWith("$elif")&&!l.key.startsWith("$else")&&!l.key.startsWith("$for ")){a=!0;break}for(let l of e.properties)if(l.key.startsWith("$if ")||l.key.match(/^\$if\s+\w+.*:?$/)){let f=$(l.value,t,r,n);if(!a&&f!==null&&f!==void 0)return Array.isArray(f)&&f.length===1?f[0]:f;typeof f=="object"&&f!==null&&!Array.isArray(f)&&Object.assign(s,f)}else if(l.key.startsWith("$for ")){if(e.properties.length===1)return $(l.value,t,r,n)}else{let f=l.value;if(f&&f.type===m.OBJECT&&f.properties){let u=f.properties.find(d=>d.key.startsWith("$for "));if(u){let d=$(u.value,t,r,n);d!==void 0&&(s[l.key]=d)}else{let d=$(l.value,t,r,n);d!==void 0&&(s[l.key]=d)}}else{let u=l.parsedKey?$(l.parsedKey,t,r,n):l.key,d=$(l.value,t,r,n);d!==void 0&&(s[u]=d)}}return s},ao={},Ks=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=$(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=$(i,t,r,n);s!==ao&&s!==void 0&&o.push(s)}return o},Js=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,c=t.partials||{},a=t.functions||t;if(s&&!$e(s,a,r,n))return;if(!c[o])throw new ue(`Partial '${o}' is not defined`);let l=n._partialStack||[];if(l.includes(o))throw new ue(`Circular partial reference detected: ${o}`);let f=c[o],u=r,d={...n,_partialStack:[...l,o]};if(n){u={...r};for(let p of Object.keys(n))p.startsWith("_")||(u[p]=n[p])}if(i){let p=$(i,t,r,n);u={...u,...p}}return $(f,t,u,d)},Xs=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],c=i.slice(1);if(!n||!(s in n))throw new ue(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(n.__paths__||(n.__paths__={}),!(s in n.__paths__))throw new ue(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=n.__paths__[s];if(typeof a=="number"){if(c.length>0)throw new ue(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return c.length>0&&(a+="."+c.join(".")),a};var Dr=Vs;var Qs=/\$\{([^}]*)\}/g,Zs=/#\{([^}]*)\}/g,lo=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=ea(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},ea=(e,t={})=>e.trim()?ta(e).map(n=>ra(n.trim(),t)):[],ta=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let c=e[s],a=s>0?e[s-1]:"";!o&&(c==='"'||c==="'")?(o=!0,i=c,r+=c):o&&c===i&&a!=="\\"?(o=!1,i="",r+=c):!o&&c==="("?(n++,r+=c):!o&&c===")"?(n--,r+=c):!o&&c===","&&n===0?(t.push(r),r=""):r+=c}return r&&t.push(r),t},ra=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:m.LITERAL,value:parseFloat(e)};if(e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};let r=lo(e,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};let n=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:c,type:a}of o){let l=0;for(;l<n.length;){let f=We(n.substring(l),c);if(f===-1)break;let u=l+f;u>i&&(i=u,s={op:c,type:a}),l=u+c.length}}if(i!==-1)try{return J(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},uo=/^\w+\(.*\)$/,na=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,oa=e=>{if(!(!e||e.trim()===""||uo.test(e))&&na.test(e))throw e.includes("?")&&e.includes(":")?new E(`Complex expressions not supported in variable replacements - consider calculating the value in your data instead. Offending expression: "${e}"`):e.includes("||")||e.includes("&&")||e.includes("??")?new E(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new E(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},co=e=>{let t=e.trim();if(uo.test(t))throw new E(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new E(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new E(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new E(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("?")&&t.includes(":"))throw new E(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:m.PATH_REFERENCE,path:t}},ht=(e,t={})=>{let r=e.trim();oa(r);let n=lo(r,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};if(r.includes("[")&&!/[\s+\-*/%|&?:]/.test(r)){let o=0;for(let i of r)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:r}},Tr=(e,t={})=>{let r=e,n=[];(e.includes("\\${")||e.includes("\\#{"))&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),r=r.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(l,f)=>{let u=`__ESCAPED_${n.length}__`;return n.push(f),u}),r=r.replace(/\\(#\{[^}]*\})/g,(l,f)=>{let u=`__ESCAPED_${n.length}__`;return n.push(f),u}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(Qs)],i=[...r.matchAll(Zs)],s=[...o.map(l=>({match:l,type:"variable"})),...i.map(l=>({match:l,type:"pathref"}))].sort((l,f)=>l.match.index-f.match.index);if(s.length===0){let l=r;for(let f=0;f<n.length;f++)l=l.replace(`__ESCAPED_${f}__`,n[f]);return{type:m.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:l,type:f}=s[0];try{return f==="variable"?ht(l[1],t):co(l[1])}catch(u){if(u.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw u}}let c=[],a=0;for(let{match:l,type:f}of s){let[u,d]=l,p=l.index;if(p>a){let h=r.substring(a,p);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&c.push(h)}try{let h;f==="variable"?h=ht(d.trim(),t):h=co(d.trim()),c.push(h)}catch(h){if(h.message==="Invalid array index syntax")c.push(u);else throw h}a=p+u.length}if(a<r.length){let l=r.substring(a);for(let f=0;f<n.length;f++)l=l.replace(`__ESCAPED_${f}__`,n[f]);l&&c.push(l)}return{type:m.INTERPOLATION,parts:c}};var Vr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ho=e=>Object.keys(e),ie=e=>e.join("."),ke=(e,t,r)=>{let n=ho(e).filter(o=>!t.has(o));if(n.length>0)throw new E(`Unexpected key '${n[0]}' in condition JSON at '${ie(r)}'`)},De=(e,t)=>typeof e=="string"?Tr(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?sa(e,t):aa(e,t):{type:m.LITERAL,value:e},ia=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new E("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new E("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new E("Empty $each body not allowed");if(r.$partial!==void 0)throw new E("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${n}`]:r}},sa=(e,t)=>{let r=[],n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let a=ia(i),l=Object.keys(a);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let f=po(l[0],a[l[0]],t,!0);r.push(f),n=!0;continue}}catch(a){throw a instanceof E?a:new E(a.message)}let c=Object.keys(i);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let a=po(c[0],i[c[0]],t);r.push(a),n=!0;continue}}let s=De(i,t);r.push(s),(s.type===m.FUNCTION||s.type===m.CONDITIONAL||s.type===m.LOOP||s.type===m.PARTIAL||s.type===m.OBJECT&&!s.fast||s.type===m.ARRAY&&!s.fast)&&(n=!0)}return{type:m.ARRAY,items:r,fast:!n}},aa=(e,t)=>{let r=[],n=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new E("$partial value must be a string");if(e.$partial.trim()==="")throw new E("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],l=[];for(let[b]of i)for(let A of a)if(b===A||b.startsWith(A+" ")||b.startsWith(A+"#")){l.push(A);break}if(l.length>0)throw new E(`Cannot use $partial with ${l.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:f,$when:u,...d}=e,p={},h=!1;for(let[b,A]of Object.entries(d)){let x=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(x=b.slice(1)),p[x]=A,h=!0}let g=null;if(h&&(g=De(p,t),g.type===m.OBJECT)){let b=!1;for(let A of g.properties)if(A.value.type===m.VARIABLE||A.value.type===m.INTERPOLATION||A.value.type===m.FUNCTION||A.value.type===m.CONDITIONAL||A.value.type===m.OBJECT&&!A.value.fast||A.value.type===m.ARRAY&&!A.value.fast){b=!0;break}b&&(g.fast=!1)}let y={type:m.PARTIAL,name:f,data:g};return u!==void 0&&(y.whenCondition=fo(u,t)),y}for(let[a,l]of i)if(a==="$when"){if(o!==null)throw new E("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new E("Missing condition expression after '$when'");o=fo(l,t),n=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new E("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[a,l]=i[s];if(a==="$when"){s++;continue}if(a==="$each")throw new E("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let f=ca(i,s,t);r.push({key:a,value:f.node}),n=!0,s=f.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let f=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",u=f?`:${f}`:"";throw new E(`$for loops must be inside arrays - use '- $for${u} item in items:' instead of '$for${u} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(a.startsWith("$elif ")||a.startsWith("$else"))throw new E(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new E("Missing condition expression after '$if'");{let f=De(l,t);(f.type===m.FUNCTION||f.type===m.CONDITIONAL||f.type===m.PARTIAL||f.type===m.OBJECT&&!f.fast||f.type===m.ARRAY&&!f.fast)&&(n=!0);let u=Tr(a,t),d={key:a,value:f};(u.type!==m.LITERAL||u.value!==a)&&(d.parsedKey=u),r.push(d),s++}}}let c={type:m.OBJECT,properties:r,fast:!n};return o&&(c.whenCondition=o),c},ca=(e,t,r={})=>{let n=[],o=[],i=t,[s,c]=e[i],a=null,l;if(s.startsWith("$if#")){let u=s.match(/^\$if#(\w+)\s+(.+)$/);if(u)a=u[1],l=u[2];else throw new E(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());kr(l);let f=J(l,r);for(n.push(f),o.push(De(c,r)),i++;i<e.length;){let[u,d]=e[i],p=!1,h;if(a?u.startsWith(`$elif#${a} `)?(h=u.substring(`$elif#${a} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(u===`$else#${a}`||u===`$else#${a}:`)&&(p=!0,h=null):u.startsWith("$elif ")?(h=u.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(u==="$else"||u==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{kr(h);let g=J(h,r);n.push(g)}if(o.push(De(d,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:a},nextIndex:i}},Pr={eq:O.EQ,neq:O.NEQ,gt:O.GT,gte:O.GTE,lt:O.LT,lte:O.LTE,in:O.IN,add:O.ADD,sub:O.SUBTRACT},Nr={all:O.AND,any:O.OR},la=new Set(["var","literal","call","not",...Object.keys(Pr),...Object.keys(Nr)]),ua=(e,t,r)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${ie(r)}' requires an array`);if(e.length!==2)throw new E(`Condition JSON operator '${t}' at '${ie(r)}' requires exactly 2 operands`);return e},fa=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${ie(o)}' requires an array`);if(e.length===0)throw new E(`Condition JSON operator '${t}' at '${ie(o)}' requires at least 1 condition`);return e.map((s,c)=>Ce(s,n,[...o,c])).reduce((s,c)=>({type:m.BINARY,op:r,left:s,right:c}))},da=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],ke(e,new Set(["call","args"]),r);else if(Vr(e.call))n=e.call.name,o=e.call.args??[],ke(e,new Set(["call"]),r),ke(e.call,new Set(["name","args"]),[...r,"call"]);else throw new E(`Condition JSON call at '${ie(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new E(`Condition JSON call at '${ie(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new E(`Invalid condition JSON function name '${n}' at '${ie(r)}'`);if(!Array.isArray(o))throw new E(`Condition JSON call '${n}' at '${ie(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>Ce(i,t,[...r,"args",s]))}},Ce=(e,t={},r=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:m.LITERAL,value:e};if(Array.isArray(e))throw new E(`Condition JSON array at '${ie(r)}' must be wrapped in an operator or { literal: [...] }`);if(!Vr(e))throw new E(`Invalid condition JSON value at '${ie(r)}'`);let n=ho(e);if(n.length===0)throw new E(`Condition JSON object at '${ie(r)}' must contain an operator`);let o=n.filter(s=>la.has(s));if(o.length===0)throw new E(`Unknown condition JSON operator '${n[0]}' at '${ie(r)}'`);if(o.length>1)throw new E(`Condition JSON at '${ie(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(ke(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new E(`Condition JSON var at '${ie(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return ke(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return da(e,t,r);if(i==="not")return ke(e,new Set(["not"]),r),{type:m.UNARY,op:nt.NOT,operand:Ce(e.not,t,[...r,"not"])};if(i in Nr)return ke(e,new Set([i]),r),fa(e[i],i,Nr[i],t,[...r,i]);if(i in Pr){ke(e,new Set([i]),r);let s=ua(e[i],i,[...r,i]);return{type:m.BINARY,op:Pr[i],left:Ce(s[0],t,[...r,i,0]),right:Ce(s[1],t,[...r,i,1])}}throw new E(`Unknown condition JSON operator '${i}' at '${ie(r)}'`)},fo=(e,t={})=>{if(e==null)throw new E("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression after '$when'");return J(e,t)}return Vr(e)||Array.isArray(e)?Ce(e,t):{type:m.LITERAL,value:e}},J=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let l=e.slice(1,-1),f=0,u=!0;for(let d=0;d<l.length;d++)if(l[d]==="("?f++:l[d]===")"&&f--,f<0){u=!1;break}if(u&&f===0)return J(l,t)}let r=We(e,"||");if(r!==-1)return{type:m.BINARY,op:O.OR,left:J(e.substring(0,r).trim(),t),right:J(e.substring(r+2).trim(),t)};let n=We(e,"&&");if(n!==-1)return{type:m.BINARY,op:O.AND,left:J(e.substring(0,n).trim(),t),right:J(e.substring(n+2).trim(),t)};let o=[{op:">=",type:O.GTE},{op:"<=",type:O.LTE},{op:"==",type:O.EQ},{op:"!=",type:O.NEQ},{op:">",type:O.GT},{op:"<",type:O.LT},{op:" in ",type:O.IN}];for(let{op:l,type:f}of o){let u=We(e,l);if(u!==-1)return{type:m.BINARY,op:f,left:J(e.substring(0,u).trim(),t),right:J(e.substring(u+l.length).trim(),t)}}let i=-1,s=null,c=[{op:" + ",type:O.ADD},{op:" - ",type:O.SUBTRACT}];for(let{op:l,type:f}of c){let u=0;for(;u<e.length;){let d=We(e.substring(u),l);if(d===-1)break;let p=u+d;p>i&&(i=p,s={op:l,type:f}),u=p+l.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:J(e.substring(0,i).trim(),t),right:J(e.substring(i+s.op.length).trim(),t)};let a=[" * "," / "," % "];for(let l of a)if(We(e,l)!==-1)throw new E(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:m.UNARY,op:nt.NOT,operand:J(e.substring(1).trim(),t)}:mo(e,t)},We=(e,t)=>{let r=0,n=0;for(;n<=e.length-t.length;){if(e[n]==="(")r++;else if(e[n]===")")r--;else if(r===0&&e.substring(n,n+t.length)===t)return n;n++}return-1},pa=e=>{if(e=e.trim(),e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:m.LITERAL,value:""};if(e==="{}")return{type:m.LITERAL,value:{}};if(e==="[]")return{type:m.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:m.LITERAL,value:t}:{type:m.VARIABLE,path:e}},mo=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return ht(r,t);let o=pa(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return ht(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},ha=(e,t=!1)=>{let r=t?"$each":"$for";try{eo(e)}catch(n){if(n instanceof E&&t){let o=n.message.replace(/\$for/g,"$each");throw new E(o.replace("Parse Error: ",""))}throw n}},po=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new E(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],c=i[2].trim();ha(c,n);let a=c.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let y=n?"$each":"$for";throw new E(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${c}')`)}let l=a[1].trim(),f=a[2].trim(),u,d=null;if(l.includes(",")){let y=l.split(",").map(b=>b.trim());if(y.length!==2)throw new E(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);u=y[0],d=y[1]}else u=l;let p=["this","undefined","null","true","false"];if(p.includes(u))throw new E(`Reserved variable name: ${u}`);if(d&&p.includes(d))throw new E(`Reserved variable name: ${d}`);let h=mo(f,r),g=De(t,r);return{type:m.LOOP,itemVar:u,indexVar:d,iterable:h,body:g,flatten:s!=="nested"}};var ma=(e,t={})=>{let{functions:r={}}=t;return De(e,r)},Ft=ma;var mt={};_s(mt,{now:()=>ga});var ga=()=>Date.now();var ya=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...mt,...n},s=Ft(e,{functions:i}),c={};for(let[a,l]of Object.entries(o))c[a]=Ft(l,{functions:i});return Dr(s,t,{functions:i,partials:c})},se=ya;var ba=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Ia=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Aa=(e,t)=>{if(ba(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression");return J(e,t)}return Ce(e,t)},wa=(e,t={},r={})=>{let n=Ia(r),o={...mt,...n},i=Aa(e,o);return!!$e(i,{functions:o,partials:{}},t,{})},jr=wa;var yt=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return jr(e,t)},wo=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=a=>a,transformActionFirstArgument:c=a=>a}=r;for(let[a,l]of Object.entries(t))a!=="createInitialState"&&(a.startsWith("select")?o[a]=(...f)=>l(s(n),...f):i[a]=(...f)=>{let u;return n=$r(n,p=>{let h=l(c(p),...f);u=h!==void 0&&!de(h)?h:void 0}),u});return{...o,...i}},Bt=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return $r(n,i=>{o.forEach(s=>{t.forEach(c=>{c(i,s)})})})};var Ea=(e,t)=>{if(e.default!==void 0)return e.default;let r=["number","boolean","string","object"];if(!r.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${r.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},ge=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),gt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Eo=e=>{let t=de(e)?ze(e):e;return structuredClone(t)},xa=({characterId:e,resourceCharacter:t,variables:r={}}={})=>{if(!ge(t,"nameVariableId"))return;let n=t.nameVariableId,o=r?.[n];if(typeof o!="string")throw new Error(`Character "${e}" nameVariableId "${n}" must resolve to a string variable`);return o},zt=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0;if(t?.name!==void 0)return t.name;if(r!==void 0)return r;let s=xa({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},Te=e=>ge(e,"computed"),ot=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Te(t[r]))),va=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),Fr=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},Ca=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=va(e),[n,o,...i]=r;if(n==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return Fr(s,i)}return n==="runtime"?Fr(t.runtime,r.slice(1)):Fr(t,r)},Sa=(e,t,r)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(r!==void 0&&t.length!==r)throw new Error(`Computed expression operator "${e}" requires ${r} operand(s)`)},go=(e,t)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(t.length===0)throw new Error(`Computed expression operator "${e}" requires at least one operand`)},_a=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},Ie=(e,t,r,n)=>(Sa(e,t,n),t.map(o=>Ut(o,r))),me=(e,t,r,n)=>{let o=Ie(e,t,r,n);return o.forEach(i=>_a(e,i)),o},Ra=(e,t,r)=>{switch(e){case"var":return Ca(t,r);case"add":{let[n,o]=me(e,t,r,2);return n+o}case"sub":{let[n,o]=me(e,t,r,2);return n-o}case"mul":{let[n,o]=me(e,t,r,2);return n*o}case"div":{let[n,o]=me(e,t,r,2);return n/o}case"mod":{let[n,o]=me(e,t,r,2);return n%o}case"neg":{let[n]=me(e,t,r,1);return-n}case"round":{let[n]=me(e,t,r,1);return Math.round(n)}case"floor":{let[n]=me(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=me(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=me(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=me(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=me(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=Ie(e,t,r,2);return n==o}case"neq":{let[n,o]=Ie(e,t,r,2);return n!=o}case"gt":{let[n,o]=Ie(e,t,r,2);return n>o}case"gte":{let[n,o]=Ie(e,t,r,2);return n>=o}case"lt":{let[n,o]=Ie(e,t,r,2);return n<o}case"lte":{let[n,o]=Ie(e,t,r,2);return n<=o}case"in":{let[n,o]=Ie(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return go(e,t),t.every(n=>!!Ut(n,r));case"or":case"any":return go(e,t),t.some(n=>!!Ut(n,r));case"not":{let[n]=Ie(e,t,r,1);return!n}case"length":{let[n]=Ie(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:gt(n)?Object.keys(n).length:0}case"includes":{let[n,o]=Ie(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return Eo(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},Ut=(e,t={})=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let r=Object.entries(e);if(r.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[n,o]]=r;return Ra(n,o,t)},Oa=(e,t={})=>yt(e,{variables:t.variables,runtime:t.runtime}),La=(e,t)=>{if(!gt(e))throw new Error(`${t} must be an object`);let r=ge(e,"expr"),n=ge(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},Mr=(e,t,r)=>(La(e,t),ge(e,"value")?Eo(e.value):Ut(e.expr,r)),$a=(e,t={},r="unknown")=>{if(!gt(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=ge(e,"expr"),o=ge(e,"value");if(ge(e,"branches")){if(n||o)throw new Error(`Computed variable "${r}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${r}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${r}" branches must not be empty`);if(!gt(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let c=e.branches[s];if(!gt(c))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!ge(c,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(Oa(c.when,t))return Mr(c,`Computed variable "${r}" branch ${s}`,t)}return Mr(e.default,`Computed variable "${r}" default`,t)}if(n===o)throw new Error(`Computed variable "${r}" must contain exactly one of expr, value, or branches`);return Mr(e,`Computed variable "${r}"`,t)},ka=(e,t,r)=>{switch(t){case"number":if(typeof r!="number"||!Number.isFinite(r))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(r)?"array":typeof r}`);return;case"boolean":if(typeof r!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(r)?"array":typeof r}`);return;case"string":if(typeof r!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(r)?"array":typeof r}`);return;case"object":if(r===null||typeof r!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof r}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},bt=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=ot(e,r),i=Object.entries(r).filter(([,u])=>Te(u)).map(([u])=>u),s={},c=[],a=u=>{if(ge(s,u))return s[u];let d=r[u];if(!Te(d))return o[u];let p=c.indexOf(u);if(p>=0){let h=[...c.slice(p),u].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}c.push(u);try{let h=$a(d.computed,f,u);return ka(u,d.type,h),s[u]=h,h}finally{c.pop()}},l=new Proxy({},{get:(u,d)=>{if(typeof d=="string")return a(d)},has:(u,d)=>typeof d=="string"&&(ge(o,d)||i.includes(d)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(u,d)=>{if(!(typeof d!="string"||!ge(o,d)&&!i.includes(d)))return{enumerable:!0,configurable:!0}}}),f={variables:l,runtime:t,resolveVariable:a};return n?(i.forEach(u=>{a(u)}),{...o,...s}):l},Da=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>bt({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),Wt=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(Te(o))return;let i=Ea(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},qt=(e,t)=>{let r=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!r.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${r.join(", ")}`)},Ht=(e,t,r)=>{let n={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=n[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${r}`);if(!Object.values(n).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${r}" of type "${e}". Valid operations: ${o.join(", ")}`)},Ta=2,yo=12,xo=(e=Ta)=>{if(!Number.isInteger(e)||e<0||e>yo)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${yo}.`);return e},Pa=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},Mt=e=>typeof e=="number"&&Number.isFinite(e),zr=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!Mt(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!Mt(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!Mt(r))throw new Error(`Operation "divide" requires value to be a number for variable "${n}".`);if(t==="divide"){if(r===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${n}".`);xo(o.roundTo)}}},Yt=(e,t,r,n={})=>{let o=(s,c,a)=>{let l=s??c;if(!Mt(l))throw new Error(`Operation "${t}" requires ${a} to be a number.`);return l},i=s=>{let c=o(s,void 0,"value");if(c===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return c};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return Pa(o(e,0,"current value")/i(r),xo(n.roundTo));case"increment":return o(e,0,"current value")+o(r,1,"value");case"decrement":return o(e,0,"current value")-o(r,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var vo=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let r=new Date(e),n=o=>String(o).padStart(2,"0");return t.replace("DD",n(r.getDate())).replace("MM",n(r.getMonth()+1)).replace("YYYY",r.getFullYear()).replace("YY",String(r.getFullYear()).slice(-2)).replace("HH",n(r.getHours())).replace("mm",n(r.getMinutes())).replace("ss",n(r.getSeconds()))},Na=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let c=i.character?.sprite;return c&&Object.keys(c).length>0&&(s.sprite=c),Object.keys(s).length>0?s:void 0},n=r(e),o=r(t);return JSON.stringify(n)===JSON.stringify(o)?null:n&&!o?{changeType:"delete",data:e}:o&&!n?{changeType:"add",data:t}:o&&n?{changeType:"update",data:t}:null},bo=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};e.transformId!==void 0&&(t.transformId=e.transformId);for(let r of["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"])e[r]!==void 0&&(t[r]=e[r]);for(let r of["animationName","animationSpeed","loop"])e[r]!==void 0&&(t[r]=e[r]);return t},Io=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},Ao=(e,t)=>t&&!e?{changeType:"add",data:t}:e&&!t?{changeType:"delete",data:e}:e&&t&&JSON.stringify(e)!==JSON.stringify(t)?{changeType:"update",data:t}:null,Va=(e,t)=>{let r={},n=Ao(bo(e),bo(t)),o=Ao(Io(e),Io(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},Wr=(e={},t={})=>{let r={},n=["sfx","voice"],o=c=>{let a=e[c],l=t[c];l&&!a?r[c]={changeType:"add",data:l}:a&&!l?n.includes(c)||(r[c]={changeType:"delete",data:a}):a&&l&&JSON.stringify(a)!==JSON.stringify(l)&&(r[c]={changeType:"update",data:l})},i=Va(e.background,t.background);i&&(r.background=i),o("screen"),o("bgm"),o("voice");let s=Na(e.dialogue,t.dialogue);return s&&(r.dialogue=s),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),r},qr=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,!t.background.resourceId&&!t.background.colorId&&delete t.background);let r=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};r("layout"),r("choice"),r("form"),r("screen"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let n=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(c=>{let a={...c};return delete a.animations,i(a)?a:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return n("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),n("visual",o=>o.resourceId||o.transformId),t},ja=(e,t)=>{if(!e||!t)return;let r=e;for(let n of t.split(".")){if(r==null||!(n in Object(r)))return;r=r[n]}return r},Fa=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let r=e.slice(7),n=ja(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},Ma={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"])},Co=(e,t)=>{let r=e[e.length-1];return r?Ma[r]?.has(t)===!0:!1},Ur=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Ur(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Co(r,n)?o:Ur(o,t,[...r,n])])):Fa(e,t),Br=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Br(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Co(r,n)?o:Br(o,t,[...r,n])])):typeof e=="string"?se(e,t):e,Hr=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let r=Ur(e,t._event);return Br(r,t)};var W=e=>structuredClone(de(e)?ze(e):e),B=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),So=e=>e?.animations?.playback?.continuity==="persistent",k=(e,t)=>B(e??{},t)&&e[t]!==void 0,It=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:W(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Ua=e=>k(e,"opacity")||k(e,"blur"),Lo=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],$o=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Yr=["animationName","animationSpeed","loop"],Ba=e=>Lo.some(t=>k(e,t)),ko=e=>e?.text&&k(e.text,"content")&&k(e.text,"textStyleId"),Do=e=>k(e,"text"),za=(e,t)=>e.resourceId?!0:ko(e)?!t?.text:!1,Wa=(e,t)=>{let r={...W(e),...t};return t.text&&e.text&&(r.text={...W(e.text),...W(t.text)}),r},qa=(e,t)=>{if(Do(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!ko(e)&&!t?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},_o=e=>$o.some(t=>k(e,t)),Ro=e=>Yr.some(t=>k(e,t)),Ha=(e,t,{hasAuthoredTransformId:r=!1}={})=>{if(!t)return e;for(let n of $o)!r&&!k(e,n)&&k(t,n)&&(e[n]=t[n]),B(e,n)&&e[n]===void 0&&delete e[n];return e},To=(e,t,r)=>{let n=e[r];return n?.id===t?.id?n:e.find(o=>o.id===t?.id)},Ya=(e,t)=>{if(!t)return e;for(let r of Lo)!k(e,r)&&k(t,r)&&(e[r]=t[r]),B(e,r)&&e[r]===void 0&&delete e[r];return e},Ga=(e,t)=>(t&&(!k(e,"opacity")&&k(t,"opacity")&&(e.opacity=t.opacity),!k(e,"blur")&&k(t,"blur")&&(e.blur=W(t.blur)),B(e,"opacity")&&e.opacity===void 0&&delete e.opacity,B(e,"blur")&&e.blur===void 0&&delete e.blur),e),Po=(e,t,r=[],{hasPatchFn:n=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,c)=>{let a=To(r,s,c),l=t(s,a),f=Ua(s),u=Ba(s),d=n(s),p=B(s,"animations"),h=W(s);return!l&&(f||u||d)&&a&&(h=o?o(a,h):{...W(a),...h},p||delete h.animations),Ga(Ya(h,a),a)}).filter(s=>t(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},Ka=e=>{if(e){if(e.character&&B(e.character,"name"))return e.character.name;if(B(e,"characterName"))return e.characterName}},No=e=>!!e?.character&&B(e.character,"sprite"),Ja=e=>{let t={},r=!1,n=Ka(e);return n!==void 0&&(t.name=n,r=!0),No(e)&&(t.sprite=W(e.character.sprite),r=!0),r?t:void 0},Oo=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Xa=({dialogueState:e,content:t,append:r=!1})=>{if(!r||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let n=Array.isArray(e.content)?e.content:[];n.length>0?e.initialRevealedContent=n.map(o=>W(o)):delete e.initialRevealedContent,e.content=[...n,...t]},Qa=()=>({}),Za=(e,t)=>{if(!t.screen)return;let r=k(t.screen,"opacity"),n=k(t.screen,"blur"),o=B(t.screen,"animations");if(!r&&!n){o||delete e.screen;return}let i=e.screen,s={};if(r?s.opacity=t.screen.opacity:k(i,"opacity")&&(s.opacity=i.opacity),n?s.blur=W(t.screen.blur):k(i,"blur")&&(s.blur=W(i.blur)),B(s,"opacity")&&s.opacity===void 0&&delete s.opacity,B(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},ec=(e,t)=>{if(t.background){let r=k(t.background,"resourceId"),n=k(t.background,"colorId"),o=k(t.background,"opacity"),i=k(t.background,"blur"),s=k(t.background,"transformId"),c=_o(t.background),a=Ro(t.background),{animationsOnly:l,state:f}=It(t.background,p=>k(p,"resourceId")||k(p,"colorId")||k(p,"opacity")||k(p,"blur")||k(p,"transformId")||_o(p)||Ro(p));if(l){e.background=e.background?{...W(e.background),...f}:f;return}if(!r&&!n&&!o&&!i&&!s&&!c&&!a){delete e.background;return}let u=e.background,d=W(t.background);if(!r&&u?.resourceId){d.resourceId=u.resourceId,!B(d,"transformId")&&u.transformId&&(d.transformId=u.transformId);for(let p of Yr)!k(d,p)&&k(u,p)&&(d[p]=u[p])}Ha(d,u,{hasAuthoredTransformId:s}),!n&&u?.colorId&&(d.colorId=u.colorId),!o&&k(u,"opacity")&&(d.opacity=u.opacity),!i&&k(u,"blur")&&(d.blur=W(u.blur)),B(d,"resourceId")&&d.resourceId===void 0&&delete d.resourceId,B(d,"colorId")&&d.colorId===void 0&&delete d.colorId,B(d,"animations")&&d.animations===void 0&&delete d.animations,B(d,"transformId")&&d.transformId===void 0&&delete d.transformId,B(d,"opacity")&&d.opacity===void 0&&delete d.opacity,B(d,"blur")&&d.blur===void 0&&delete d.blur;for(let p of Yr)B(d,p)&&d[p]===void 0&&delete d[p];if(!d.resourceId&&!d.colorId){delete e.background;return}u?.resourceId===d.resourceId&&u?.transformId===d.transformId&&!B(d,"animations")&&So(u)&&(d.animations=W(u.animations)),e.background=d}else e.background?.animations&&!So(e.background)&&(e.background.animations={})},tc=(e,t)=>{if(!t.dialogue){e.dialogue&&(Oo(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,delete e.dialogue.textSpeed,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let r=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:l,state:f}=It(t.dialogue.ui,u=>!!u.resourceId);l?e.dialogue.ui={...e.dialogue.ui,...f}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let n=t.dialogue.append===!0&&r!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&Xa({dialogueState:e.dialogue,content:t.dialogue.content,append:n}),B(t.dialogue,"textSpeed")?e.dialogue.textSpeed=t.dialogue.textSpeed:delete e.dialogue.textSpeed;let o=B(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=B(t.dialogue,"characterId"),s=Ja(t.dialogue),c=s!==void 0,a=No(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,c?e.dialogue.character=!i&&o&&e.dialogue.character?{...W(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,a||Oo(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let l={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.textSpeed!==void 0&&(l.textSpeed=e.dialogue.textSpeed),e.dialogue.character&&(l.character=W(e.dialogue.character)),e.dialogue.lines.push(l)}},rc=(e,t)=>{if(t.sfx){let r=Array.isArray(t.sfx.items)&&t.sfx.items.length>0,n=Array.isArray(t.sfx.channels)&&t.sfx.channels.length>0;if(!r&&!n){delete e.sfx;return}e.sfx=W(t.sfx)}else e.sfx&&delete e.sfx},nc=(e,t)=>{if(t.bgm){let r=Array.isArray(t.bgm.sounds);if(!t.bgm.resourceId&&!r||r&&t.bgm.sounds.length===0){e.bgm=void 0;return}e.bgm=W(t.bgm),t.bgm.resourceId&&(e.bgm.loop=t.bgm.loop??!0)}},oc=(e,t)=>{if(t.visual){let r=e.visual?.items||[];t.visual.items?.forEach((i,s)=>{qa(i,To(r,i,s))});let{hasValidItems:n,processedItems:o}=Po(t.visual.items,za,r,{hasPatchFn:Do,mergeItemFn:Wa});n?e.visual={items:o}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(r=>r.animations?{...r,animations:{}}:r))},ic=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:r,processedItems:n}=Po(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);r?e.character={items:n}:delete e.character},sc=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},ac=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=It(t.layout,o=>!!o.resourceId);if(r){e.layout=n;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},cc=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=It(t.choice,o=>!!o.resourceId);if(r){e.choice={...e.choice,...n};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},lc=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=It(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=W(t.form)}else e.form&&delete e.form},uc=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},fc=(e,t)=>{if(t.voice){let r=Array.isArray(t.voice.sounds);if(!t.voice.resourceId&&!r||r&&t.voice.sounds.length===0){delete e.voice;return}e.voice=W(t.voice)}else e.voice&&delete e.voice},dc=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},qe=e=>Bt(Qa,[dc,Za,ec,rc,nc,oc,tc,ic,sc,ac,cc,lc,uc,fc])(e);var it=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=se(e,t);return r&&typeof r=="object"?e:r};var pc=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"}}),He=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}),At=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Vo=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"}),Gr=Object.freeze(["dialogueTextSpeed","autoForwardDelay","autoForwardSpeed","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Kr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),hc=(e,t)=>{if(t.startsWith("global.")){let r=t.slice(7);return e?.global?.[r]}if(t.startsWith("context.runtime.")){let r=t.slice(16),n=Array.isArray(e?.contexts)?e.contexts:[];return n[n.length-1]?.runtime?.[r]}},Ye=e=>Object.fromEntries(Object.entries(pc).map(([t,r])=>{let n=hc(e,r.source),o=n!==void 0?n:He[t]??At[t];return[t,o]})),Pe=(e,t)=>Ye(e)[t],jo=(e={})=>Object.fromEntries(Gr.map(t=>[t,e[t]??He[t]]));var st=Object.freeze({VISUAL_BEHIND_BACKGROUND:10,BACKGROUND:20,VISUAL_BEHIND_CHARACTER:30,CHARACTER:40,VISUAL_BEHIND_DIALOGUE:50,DIALOGUE:60,VISUAL_BEHIND_CHOICE:70,CHOICE:80,VISUAL_FOREGROUND:90}),_e=Object.freeze({BEHIND_BACKGROUND:st.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:st.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:st.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:st.VISUAL_BEHIND_CHOICE,FOREGROUND:st.VISUAL_FOREGROUND}),Jr=_e.BEHIND_DIALOGUE,Xr=Object.freeze(Object.values(_e).sort((e,t)=>e-t));var Re={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:vo},mc=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,gc=(e,t)=>{let r=String(t||"").trim();if(!r)return;let n=r.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of n){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},Xt=(e,t,r)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),c=mc.exec(s);if(c){let[,a,l,f]=c,u=gc(t,f);if(!Array.isArray(u))continue;let d=Array.isArray(i[s])?i[s]:[];u.forEach((p,h)=>{let g={...t,[a]:p};l&&(g[l]=h),d.forEach(y=>{let b=Xt(y,g,r),A=se(b,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(Xt(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=Xt(i,t,r)}),n},mn=({animationType:e,animationId:t,animationPath:r})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${r}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},yc=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);if(mn({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n!==void 0){let s=wc(n,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},bc=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return mn({animationType:e.type,animationId:t,animationPath:r}),e.type},Ic=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Ac=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},wc=(e,t="animation.playback")=>{if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`[${t}] playback must be an object.`);if(e.continuity!==void 0&&e.continuity!=="render"&&e.continuity!=="persistent")throw new Error(`[${t}] playback.continuity must be "render" or "persistent".`);if(e.speed!==void 0&&(typeof e.speed!="number"||!Number.isFinite(e.speed)||e.speed<=0))throw new Error(`[${t}] playback.speed must be a finite number greater than 0.`);let r={};return e.continuity!==void 0&&(r.continuity=e.continuity),e.speed!==void 0&&e.speed!==1&&(r.speed=e.speed),Object.keys(r).length>0?r:void 0},Ec=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},Ge=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Xo=e=>e?.playback?.continuity==="persistent",sn=e=>Array.isArray(e)?e.map(sn):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=sn(e[r]),t),{}),Zt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return t.playback&&(delete t.playback.continuity,t.playback.speed===1&&delete t.playback.speed,Object.keys(t.playback).length===0&&delete t.playback),JSON.stringify(sn(t))},Qo=(e=[])=>e.filter(t=>Xo(t)).map(t=>structuredClone(t)),Zo=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,r)=>{let n=typeof r?.duration=="number"&&Number.isFinite(r.duration)?r.duration:0;return t+n},0):0,Qr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,Zo(r)),0),ei=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(Qr(e.tween),Qr(e.prev?.tween),Qr(e.next?.tween),Zo(e.mask?.progress))/Ec(e),Fo=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let r=new Set(t.map(Zt).filter(Boolean));return e.some(n=>{if(!Xo(n))return!1;let o=Zt(n);return o?r.has(o):!1})},Ae=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||Fo({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:Fo({animationInstances:e,activePersistentAnimations:o}),xc=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),vc=(e,t)=>{if(xc(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},Cc=({resources:e,animationId:t,playback:r,instanceId:n,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?yc({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},Sc=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return mn({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},gn=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(Sc(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},an=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(r=>r===null||typeof r!="object"||Array.isArray(r)))throw new Error(`${t} must be an array of objects`);return e},_c=({content:e,path:t,variables:r})=>an(e,t).reduce((n,o)=>{let i=it(o.text,{variables:r});return n+`${i??""}`.length},0),Mo=(e=[])=>{let t=new Map;for(let r of e)r?.id&&t.set(r.id,(t.get(r.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,r])=>r>1).map(([r])=>r))},Gt=(e,t=0,r=new Set)=>{if(!r.has(e?.id))return`character-container-${e.id}`;let n=e?.sprites?.map(({resourceId:o})=>o)||[];return n.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${n.join("-")}`},Kt=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return r},Rc=(e,t={})=>{if(!t?.transformId)return;let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for background`);return r},Oc=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Lc=(e={})=>Oc.some(t=>Ge(e,t)),ti=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.spritesheets?.[t])return"spritesheet-animation";if(e.layouts?.[t])return"container"}},Qt=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},$c=(e={})=>e.textStyles||{},kc=(e={})=>e.images||{},Dc=.5,Tc=(e={},t,r)=>{if(t){if(!e.animations?.[t])throw new Error(`Animation '${t}' not found in spritesheet resource '${r}'`);return t}return Object.keys(e.animations??{})[0]},ri=({id:e,resourceId:t,spritesheet:r,animationName:n,animationSpeed:o,loop:i,transform:s={}}={})=>{let c=Tc(r,n,t),a=c?r.animations?.[c]:void 0;if(!a){console.warn(`Spritesheet animation not found: ${t}`);return}return{id:e,type:"spritesheet-animation",...s,width:r.width,height:r.height,src:r.fileId,atlas:r.jsonData,playback:{frames:a.frames,animationSpeed:o??a.animationSpeed??Dc,loop:i??a.loop??!0}}},ni=({id:e,item:t,resources:r={}}={})=>{let n=r.images?.[t.resourceId];if(n)return{type:"sprite",id:e,src:n.fileId,width:n.width,height:n.height,x:0,y:0};let o=r.spritesheets?.[t.resourceId];if(o)return ri({id:e,resourceId:t.resourceId,spritesheet:o,animationName:t.animationName,animationSpeed:t.animationSpeed,loop:t.loop,transform:{x:0,y:0}});console.warn(`Character sprite resource not found: ${t.resourceId}`)},Pc=(e={})=>e.colors||{},Nc=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,xt=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,ct=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},Zr=(e,t,r)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);return e},en=(e,t,r,n,{minimum:o}={})=>{if(e===void 0)return n;if(typeof e!="number"||!Number.isFinite(e)||o!==void 0&&e<o){let i=o===void 0?"a finite number":`a finite number >= ${o}`;throw new Error(`shadow.${t} for text style "${r}" must be ${i}`)}return e},rr=(e,t)=>{if(typeof e!="string"||!Nc.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(r=>r.repeat(2)).join("")}`:e},Uo=(e,t,r)=>{let n=rr(e,r);if(t===1)return n;let o=Number.parseInt(n.slice(1,3),16),i=Number.parseInt(n.slice(3,5),16),s=Number.parseInt(n.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},Vc=(e={},t)=>{let r=$c(e)?.[t];if(!r)throw new Error(`Text style "${t}" not found`);let n=e.fonts?.[r.fontId];if(!n)throw new Error(`Font "${r.fontId}" not found for text style "${t}"`);let o=e.colors?.[r.colorId];if(!o)throw new Error(`Color "${r.colorId}" not found for text style "${t}"`);let i=Zr(r.colorAlpha,"colorAlpha",t),s={fontFamily:n.fileId,fontSize:r.fontSize??16,fontWeight:r.fontWeight??"400",fontStyle:r.fontStyle??"normal",lineHeight:r.lineHeight??1.2,fill:Uo(o.hex,i,`Color "${r.colorId}" for text style "${t}"`)};if(r.align!==void 0&&(s.align=r.align),r.wordWrap!==void 0&&(s.wordWrap=r.wordWrap),r.breakWords!==void 0&&(s.breakWords=r.breakWords),r.wordWrapWidth!==void 0&&(s.wordWrapWidth=r.wordWrapWidth),r.strokeColorId){let c=e.colors?.[r.strokeColorId];if(!c)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let a=Zr(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=Uo(c.hex,a,`Stroke color "${r.strokeColorId}" for text style "${t}"`)}else if(r.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);if(r.strokeWidth!==void 0&&(s.strokeWidth=r.strokeWidth),r.shadow!==void 0){let c=e.colors?.[r.shadow.colorId];if(!c)throw new Error(`Shadow color "${r.shadow.colorId}" not found for text style "${t}"`);s.shadow={color:rr(c.hex,`Shadow color "${r.shadow.colorId}" for text style "${t}"`),alpha:Zr(r.shadow.alpha,"shadow.alpha",t),blur:en(r.shadow.blur,"blur",t,0,{minimum:0}),offsetX:en(r.shadow.offsetX,"offsetX",t,2),offsetY:en(r.shadow.offsetY,"offsetY",t,2)}}return s},cn=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>cn(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${r}". Use textStyleId instead`);let n={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(n[o]=cn(i,t,xt(r,o)));return e.textStyleId!==void 0&&(ct(e.textStyleId,r,"textStyleId"),n.textStyle=Vc(t,e.textStyleId)),n},yn=(e={},t)=>{let r=Pc(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return rr(r.hex,`Color "${t}"`)},oi=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",tn=(e,t,r)=>{let n=e?.[t];if(!(!n||typeof n!="object"||Array.isArray(n))&&Object.prototype.hasOwnProperty.call(n,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${r}". Use ${oi(`${t}.fill`)} instead`)},jc=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>vt(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;let n={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(n[o]=vt(i,t,xt(r,o)));return e.colorId!==void 0&&(ct(e.colorId,r,"colorId"),n.fill=yn(t,e.colorId)),n},vt=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>vt(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${r}". Use ${oi("fill")} instead`);tn(e,"hover",r),tn(e,"click",r),tn(e,"rightClick",r)}let n={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){n[o]=jc(i,t,xt(r,o));continue}n[o]=vt(i,t,xt(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(ct(e.colorId,r,"colorId"),n.fill=yn(t,e.colorId)),n},rn=(e={},t)=>{let r=kc(e)?.[t];return r||null},ii=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",Bo=(e,t,r,n)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,n))throw new Error(`Inline ${t}.${n} is not allowed in sprite layout elements at "${r}". Use ${ii(`${t}.${n}`)} instead`)},zo=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},ln=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>ln(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${r}". Use ${ii(o)} instead`);Bo(e,"hover",r,"src"),Bo(e,"click",r,"src")}let n={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(n[o]=ln(i,t,xt(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){ct(e.imageId,r,"imageId");let o=rn(t,e.imageId),i=o?.fileId??e.imageId;n.src=i,n.width===void 0&&o?.width!==void 0&&(n.width=o.width),n.height===void 0&&o?.height!==void 0&&(n.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(ct(e.hoverImageId,r,"hoverImageId"),zo(n,"hover",rn(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(ct(e.clickImageId,r,"clickImageId"),zo(n,"click",rn(t,e.clickImageId)?.fileId??e.clickImageId)),n},bn=(e,t={},r="root")=>ln(vt(cn(e,t,r),t,r),t,r),Oe=bn,Je=(e=[])=>e.find(t=>t.id==="story"),Fc="#000000",un="bg-cg-background-color",Mc=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?rr(r?.backgroundColor??Fc,"screen.backgroundColor"):yn(e,t.colorId),si=(e={})=>{if(Ge(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Uc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Wo=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=si(e),n=Uc(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},Bc=(e={})=>{if(Ge(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},zc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},ai=(e={})=>{let t=Bc(e),r=zc(e),n={};return t!==void 0&&(n.alpha=t),r&&(n.blur=r),n},wt=(e={})=>ai(e),Ne=(e={},t={})=>{let r={x:t.x??e.x,y:t.y??e.y,anchorX:t.anchorX??e.anchorX,anchorY:t.anchorY??e.anchorY,rotation:t.rotation??e.rotation,scaleX:t.scaleX??e.scaleX,scaleY:t.scaleY??e.scaleY},n=t.originX??e.originX,o=t.originY??e.originY;return n!==void 0&&(r.originX=n),o!==void 0&&(r.originY=o),r},Wc=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],In=(e={})=>e.text&&Ge(e.text,"content")&&Ge(e.text,"textStyleId"),qo=(e={})=>{if(e.resourceId)return e.resourceId;if(In(e))return"text"},qc=e=>{if(e.text){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!In(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let t of Wc)if(Ge(e.text,t))throw new Error(`Visual item "${e.id}" text.${t} is reserved for the visual item`)}},Hc=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:un,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:Mc({resources:e,background:t,screen:r})};if(n){let i=si(t);i!==void 0&&(o.alpha=i)}return o},Yc=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.spritesheets?.[t]||e.layouts?.[t]):!1,Ho=({resources:e={},resourceId:t,colorId:r})=>{let n=ti(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:Qt({resourceId:t,kind:n})}:r!==void 0?{resourceId:un,targetId:un}:{resourceId:void 0,targetId:void 0}},ci=100,Ke=ci,Gc="channel:bgm",Kc="channel:voice",Jc="default",Xc=e=>String(e).replaceAll("%","%25").replaceAll(":","%3A"),Et=(...e)=>e.map(Xc).join(":"),er=(e,t,r)=>{let n=new Set;e.forEach(({id:o})=>{if(n.has(o)){let i=r?` in ${r}`:"";throw new Error(`Duplicate ${t} id "${o}"${i}.`)}n.add(o)})},Qc=(e,t)=>e*t/ci,li=(e={},t)=>e?.[t]??He[t],An=(e={},t,r=Ke)=>Qc(r,li(e,t)),wn=({id:e,volume:t,muted:r,pan:n,children:o,runtime:i})=>({id:e,type:"audio-channel",volume:t,muted:!!i?.muteAll||(r??!1),pan:n??0,children:o}),Jt=(e,t,r,n)=>e[r]!==void 0?e[r]:t[r]!==void 0?t[r]:n,Zc=["muted","pan","playbackRate","startAt","endAt"],En=({id:e,sound:t,resource:r,defaultLoop:n=!1})=>{let o={id:e,type:"sound",src:r.fileId,loop:Jt(t,r,"loop",n),volume:Jt(t,r,"volume",Ke),startDelayMs:Jt(t,r,"startDelayMs",0)};Zc.forEach(s=>{let c=Jt(t,r,s,void 0);c!==void 0&&(o[s]=c)});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},we=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,confirmDialog:u,form:d,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:b}={})=>{let A={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,autoForwardSpeed:t?.autoForwardSpeed??1,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??c??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},x=ol({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e,runtime:A}),S={variables:e,runtime:A,saveSlots:r,isChoiceVisible:a,isFormVisible:l,canRollback:f,confirmDialog:u,form:d,historyDialogue:p,characters:h};return x&&(S.dialogue=x,S.dialogueLines=x.lines),S},Yo=100,tr=(e,t)=>{if(Array.isArray(e))return e.map(n=>tr(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=tr(r[n],t)}),r.type==="text-revealing"?t(r):r},el=e=>tr(e,t=>({...t,revealEffect:"none"})),tl=e=>tr(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,Yo):Yo;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),Ve=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?el(e):r?tl(e):e,ui=({id:e,screen:t={width:1920,height:1080}})=>({id:e,type:"rect",fill:"transparent",width:t.width,height:t.height,x:0,y:0,click:{payload:{actions:{}}}}),fn=e=>{if(Array.isArray(e))return e.map(fn);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=fn(s);let r=t.click?.payload;if(!r||typeof r!="object"||Array.isArray(r))return t;let n=r.actions,o=n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"nextLine")?{...n.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...r,bypassChoice:!0,...o?{actions:{...n,nextLine:o}}:{}}}}},rl=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),Go="submit",nn=(e,t,r={})=>{let n=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},o=n.actions&&typeof n.actions=="object"?n.actions:{},i=r.replaceActions===!0?t:{...o,...t};return{...e||{},payload:{...n,actions:i}}},dn=(e,t,r={})=>{if(Array.isArray(e))return e.map(l=>dn(l,t,r));if(!e||typeof e!="object")return e;let n=typeof e.type=="string",o=n&&e.formRole===Go,i=n&&r.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},c={};for(let[l,f]of Object.entries(e))c[l]=dn(f,t,l==="children"?s:{});let a=c;if(a.type==="input"&&typeof a.field=="string"){let l=t?.fields?.[a.field];if(l){let f={updateFormField:{formKey:t.key,field:l.id,value:"_event.value"}};a={...a,value:l.value,placeholder:a.placeholder===void 0?l.placeholder:a.placeholder,multiline:a.multiline===void 0?l.multiline:a.multiline,...a.maxLength===void 0&&l.maxLength!==void 0?{maxLength:l.maxLength}:{},change:nn(a.change,f),submit:nn(a.submit,t.submitActions)}}}return a.formRole===Go||i?{...a,click:nn(a.click,t.submitActions,{replaceActions:!0})}:a},pn=(e,t)=>{if(Array.isArray(e))return e.map(n=>pn(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=pn(o,t);for(let n of rl){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form"}})}return r},hn=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0,s=zt({characterId:e,character:t,characterName:r,characters:n,variables:o});return{...i||{},...t||{},name:s}},fi=(e=[],t={},r={})=>e.map(n=>{let o=hn({characterId:n.characterId,character:n.character,characterName:n.characterName,characters:t,variables:r}),i=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(s=>s?.text??"").join(""):"";return{...n,text:i,character:o,characterName:o.name}}),nl=e=>!(!e||e.mode==="adv"&&e.content===void 0),ol=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n,runtime:o}={})=>{if(!t&&!nl(e))return;let i=e.content===void 0?[{text:""}]:an(e.content,"dialogue.content"),s=e.content===void 0?0:_c({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),c=o?.dialogueTextSpeed??He.dialogueTextSpeed,a=e.textSpeed??c,l=(e.lines||[]).map((u,d)=>{let p=an(u.content,`dialogue.lines[${d}].content`),h=hn({characterId:u.characterId,character:u.character,characterName:u.characterName,characters:r,variables:n});return{...u,textSpeed:u.textSpeed??c,content:p.map(g=>({...g,text:it(g.text,{variables:n})})),character:h,characterName:h.name}}),f=hn({characterId:e.characterId,character:e.character,characters:r,variables:n});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:f,textSpeed:a,content:i.map(u=>({...u,text:it(u.text,{variables:n})})),initialRevealedCharacters:s,lines:l}},di=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=se(e,r,{functions:Re});return Oe(Ve(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},on=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),Ko=({renderStateKeyboard:e,keyboard:t,phase:r})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([n,o])=>{let i=e[n]??{},s=r==="keydown"?o?.keydown:o?.keyup;if(r==="keydown"&&s&&typeof s=="object"){e[n]={...i,keydown:{payload:on(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:on(o.keyup)});return}e[n]={...i,[r]:{payload:on(o)}}})},il=(e={},t={})=>{let r={};return Ko({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),Ko({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},Le=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:c})=>{if(!e)return[];let a=[],l=({instanceId:b,targetId:A})=>{let x=Cc({resources:t,animationId:p,playback:h,instanceId:b,targetId:A,animationPath:s});x&&a.push(x)},f=r!=null&&r!==!1,u=n!=null&&n!==!1,d=o&&i&&o===i;vc(e,s);let p=Ic(e),h=Ac(e),g=t?.animations?.[p],y=bc(g,{animationId:p,animationPath:s});if(y==="update")return u&&i?l({instanceId:`${c}-animation-update`,targetId:i}):f&&o&&l({instanceId:`${c}-animation-update`,targetId:o}),a;if(y==="transition"){let b=`${c}-animation-transition`,A=h?.continuity==="persistent"?b:`${c}-animation-in`;if(f&&u&&d)return l({instanceId:b,targetId:i}),a;f&&l({instanceId:`${c}-animation-out`,targetId:o}),u&&l({instanceId:A,targetId:i})}return a},sl=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),al=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:c,variables:a,runtime:l,activePersistentAnimations:f,restoredPersistentAnimations:u,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,saveSlots:A=[]})=>{let{elements:x,animations:S}=e;if(t.background){let P=n===void 0?!0:Ge(n?.background??{},"animations"),N=x.find(ne=>ne.id==="story");if(!N)return e;let w=Rc(o,t.background),M=w||Lc(t.background),F=r?.background?.resourceId,G=r?.background?.colorId,j=t.background.resourceId??(t.background.animations?F:void 0),H=t.background.colorId??(t.background.animations?G:void 0),K=Yc(o,j),X={...t.background,colorId:H};if((H!==void 0||K)&&N.children.push(Hc({resources:o,background:X,screen:i,includeOpacity:!K})),j){let{images:ne={},videos:ce={},spritesheets:q={}}=o,Z=ti(o,j),oe;if(Z==="sprite"?oe=ne[j]:Z==="video"?oe=ce[j]:Z==="spritesheet-animation"&&(oe=q[j]),oe){let v=Z==="video",_=Z==="spritesheet-animation",V={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...w},le={...Wo(t.background,{includeDefaultAlpha:!0}),...Ne(V,t.background)},ee;_?ee=ri({id:Qt({resourceId:j,kind:Z}),resourceId:j,spritesheet:oe,animationName:t.background.animationName,animationSpeed:t.background.animationSpeed,loop:t.background.loop,transform:le}):ee={id:Qt({resourceId:j,kind:Z}),type:v?"video":"sprite",src:oe.fileId,width:oe.width,height:oe.height,...le},v&&(ee.loop=t.background.loop??!1,ee.volume=oe.volume??50),ee&&N.children.push(ee)}}if(j){let{layouts:ne={}}=o,ce=ne[j];if(ce){let q={id:Qt({resourceId:j,kind:"container"}),type:"container",children:ce.elements,...Wo(t.background)};M&&Object.assign(q,Ne({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...w},t.background));let Z=se(q,we({variables:a,runtime:l,saveSlots:A,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,characters:o.characters||{},skipTransitionsAndAnimations:c}),{functions:Re});N.children.push(Oe(Ve(Z,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:c}),o))}}let xe=Ho({resources:o,resourceId:F,colorId:G}),re=Ho({resources:o,resourceId:j,colorId:H}),Q=Le({animationsDef:t.background.animations,resources:o,previousResourceId:xe.resourceId,currentResourceId:re.resourceId,previousTargetId:xe.targetId,currentTargetId:re.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});Ae({animationInstances:Q,isLineCompleted:s,skipTransitionsAndAnimations:c,activePersistentAnimations:f,restoredPersistentAnimations:u,isAuthoredOnCurrentLine:P})&&S.push(...Q)}return e},cl=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:c,animations:a}=e;if(t.character&&n){let l=c.find(h=>h.id==="story");if(!l)return e;let f=t.character.items||[],u=r?.character?.items||[],d=Mo(f),p=Mo(u);for(let h=0;h<f.length;h++){let g=f[h],{transformId:y,sprites:b}=g,A=u.find(j=>j.id===g.id),x=u.findIndex(j=>j.id===g.id),S=A?.sprites&&A.sprites.length>0,P=b&&b.length>0,N=x>=0?Gt(A,x,p):void 0,w=Le({animationsDef:g.animations,resources:n,previousResourceId:N,currentResourceId:P?Gt(g,h,d):void 0,previousTargetId:N,currentTargetId:P?Gt(g,h,d):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&S&&Ae({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...w);continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let M=Gt(g,h,d),F=n.transforms[y];if(!F){console.warn("Transform not found:",y);continue}let G={type:"container",id:M,...Ne(F,g),...wt(g),children:[]};for(let j of b){let H=ni({id:`${M}-${j.id}`,item:j,resources:n});H&&G.children.push(H)}l.children.push(G),Ae({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...w)}}return e},pi=(e,t)=>{if(!Xr.includes(e))throw new Error(`${t} must be one of: ${Xr.join(", ")}.`)},ll=(e,t)=>{let r=!!e.resourceId||In(e),n=e.layer??(r?void 0:t?.layer)??Jr;return pi(n,`Visual item "${e.id}" layer`),n},ul=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:c,activePersistentAnimations:a,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,form:h,saveSlots:g=[],visualLayer:y})=>{let{elements:b,animations:A}=e;if(t.visual&&n){let x=b.find(w=>w.id==="story");if(!x)return e;let S=t.visual.items,P=r?.visual?.items||[],N=we({variables:s,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i});y!==void 0&&pi(y,"visualLayer");for(let w of S){let M=P.find(K=>K.id===w.id),F=ll(w,M);if(y!==void 0&&F!==y)continue;if(qc(w),w.text){let K=Kt(n,w),X={...structuredClone(w.text),id:`visual-${w.id}`,type:"text",...Ne(K,w)};Object.assign(X,wt(w)),x.children.push(Oe(se(X,N,{functions:Re}),n))}if(w.resourceId){let{images:K={},videos:X={},spritesheets:xe={}}=n,re=xe[w.resourceId];if(re){let Q=Kt(n,w),ne=w.animationName;if(ne){let ce=re.animations?.[ne];if(!ce)throw new Error(`Animation '${ne}' not found in spritesheet resource '${w.resourceId}'`);let q=wt(w),Z={id:`visual-${w.id}`,type:"spritesheet-animation",...Ne(Q,w),width:w.width??re.width,height:w.height??re.height,alpha:q.alpha??w.alpha??1,src:re.fileId,atlas:re.jsonData,playback:{frames:ce.frames,animationSpeed:w.animationSpeed??ce.animationSpeed??.5,loop:w.loop??ce.loop??!0}};q.blur&&(Z.blur=q.blur),x.children.push(structuredClone(Z))}}else{let Q=K[w.resourceId]||X[w.resourceId];if(Q){let ne=X[w.resourceId]!==void 0,ce=Kt(n,w),q={id:`visual-${w.id}`,type:ne?"video":"sprite",src:Q.fileId,width:Q.width,height:Q.height,...Ne(ce,w)};Object.assign(q,wt(w)),ne&&(q.loop=Q.loop??!1,q.volume=Q.volume??50),x.children.push(q)}}}if(w.resourceId){let{layouts:K={}}=n,X=K[w.resourceId];if(X){let xe=Kt(n,w),re={id:`visual-${w.id}`,type:"container",children:structuredClone(X.elements),...Ne(xe,w)};Object.assign(re,wt(w));let Q=se(re,N,{functions:Re});x.children.push(Oe(Ve(Q,{isLineCompleted:o,skipMode:f,skipTransitionsAndAnimations:i}),n))}}let G=qo(M),j=qo(w),H=Le({animationsDef:w.animations,resources:n,previousResourceId:G,currentResourceId:j,previousTargetId:G?`visual-${w.id}`:void 0,currentTargetId:j?`visual-${w.id}`:void 0,animationPath:`visual.items[${w.id}].animations`,idPrefix:w.id});Ae({animationInstances:H,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:a})&&A.push(...H)}}return e},at="dialogue-character-sprite",Jo=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,fl=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=Je(e.elements);if(!a)return e;let l=t.dialogue?.character?.sprite,f=r?.dialogue?.character?.sprite,u=Jo(l),d=Jo(f),p=Le({animationsDef:l?.animations,resources:n,previousResourceId:d?at:void 0,currentResourceId:u?at:void 0,previousTargetId:d?at:void 0,currentTargetId:u?at:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!u)return l?.animations&&d&&Ae({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e;let h=n.transforms?.[l.transformId];if(!h)return console.warn("Transform not found:",l.transformId),e;let g={type:"container",id:at,...Ne(h),children:[]};for(let y of l.items){let b=ni({id:`${at}-${y.id}`,item:y,resources:n});b&&g.children.push(b)}return a.children.push(g),Ae({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e},dl=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:f,skipOnlyViewedLines:u,isLineCompleted:d,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:y,saveSlots:b=[]})=>{let{elements:A,animations:x}=e;if(!t.dialogue||o)return e;let S=A.find(N=>N.id==="story");if(!S)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:N={}}=n,w=N[t.dialogue.ui.resourceId];if(w){let M={elements:w.elements},F=we({variables:h,runtime:g,saveSlots:b,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:d,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:f,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:u,skipTransitionsAndAnimations:p}),G={functions:Re},j=Xt(M,F,G),H=se(j,F,G),K=Oe(Ve(H?.elements,{isLineCompleted:d,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(K))for(let X of K)S.children.push(X);else K&&S.children.push(K)}}fl(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let P=Le({animationsDef:t.dialogue.ui?.animations,resources:n,previousResourceId:r?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:r?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return Ae({animationInstances:P,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&x.push(...P),e},pl=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:c,runtime:a,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:b,animations:A}=e;if(t.choice&&n){let x=Je(b);if(!x)return e;let S=n?.layouts[t.choice.resourceId];if(S&&S.elements){let N={elements:S.elements},w=se(N,{...we({variables:c,runtime:a,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:f,isChoiceVisible:u??!!t.choice,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:Re}),M=fn(Oe(Ve(w?.elements,{isLineCompleted:i,skipMode:f,skipTransitionsAndAnimations:s}),n));if(Array.isArray(M))for(let F of M)x.children.push(F);else M&&x.children.push(M)}let P=Le({animationsDef:t.choice.animations,resources:n,previousResourceId:r?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:r?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});Ae({animationInstances:P,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&A.push(...P)}return e},hl=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:c,runtime:a,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:b,animations:A}=e;if(!y?.resourceId||!n)return e;let x=Je(b);if(!x)return e;let S=n?.layouts?.[y.resourceId];if(!S)return console.warn(`Form layout not found: ${y.resourceId}`),e;let P={id:"form-container",type:"container",x:0,y:0,children:S.elements||[]},N={...we({variables:c,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},w=se(P,N,{functions:Re}),M=pn(Oe(Ve(dn(w,y),{isLineCompleted:i,skipMode:f,skipTransitionsAndAnimations:s}),n),y);M&&x.children.push(M);let F=Le({animationsDef:y.animations,resources:n,previousResourceId:r?.form?.resourceId,currentResourceId:y.resourceId,previousTargetId:r?.form?.resourceId?"form-container":void 0,currentTargetId:y.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return Ae({animationInstances:F,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(...F),e},ml=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,saveSlots:d=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=il(h.keyboard,h.keyup);if(g&&Object.keys(g).length>0&&(e.global.keyboard=g),!Array.isArray(h.elements)||h.elements.length===0)return e;let y=Je(e.elements);if(!y)return e;let b={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(di({container:b,resources:r,templateData:we({variables:n,runtime:o,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:c,skipTransitionsAndAnimations:p})),e},gl=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Je(i))return e;let a=t.bgm,l=!Array.isArray(a.sounds),f=l?a.resourceId?[{id:"default",resourceId:a.resourceId,loop:a.loop??!0,volume:a.volume,startDelayMs:a.startDelayMs??0}]:[]:a.sounds,u=[];if(l||er(f,"BGM sound"),f.forEach(p=>{let h=r.sounds?.[p.resourceId];h&&u.push(En({id:Et("bgm",l?"default":p.id),sound:p,resource:h,defaultLoop:!0}))}),u.length===0)return e;let d=we({variables:o,runtime:n}).runtime;s.push(wn({id:Gc,volume:An(d,"musicVolume",l?Ke:a.volume??Ke),muted:a.muted,pan:a.pan,children:u,runtime:d}))}return e},yl=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx,s=!Array.isArray(i.channels),c=s?[{id:Jc,sounds:i.items??[]}]:i.channels;s||er(c,"SFX channel"),c.forEach(a=>{let l=[];s||er(a.sounds,"SFX sound",`SFX channel "${a.id}"`),a.sounds.forEach((f,u)=>{let d=r.sounds?.[f.resourceId];d&&l.push(En({id:s?Et("sfx","default",u,f.id):Et("sfx",a.id,f.id),sound:f,resource:d}))}),l.length!==0&&o.push(wn({id:Et("channel","sfx",a.id),volume:An(n,"soundVolume",a.volume??Ke),muted:a.muted,pan:a.pan,children:l,runtime:n}))})}return e},bl=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},Il=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let c=t.voice,a=!Array.isArray(c.sounds),l=a?c.resourceId?[{id:"default",resourceId:c.resourceId,loop:c.loop??!1,volume:Ke,startDelayMs:c.startDelayMs??0}]:[]:c.sounds,f=[];if(a||er(l,"Voice sound"),l.forEach(d=>{let p=bl(r,n,d.resourceId);p&&f.push(En({id:Et("voice",n,a?"default":d.id),sound:d,resource:p}))}),f.length===0)return e;let u=we({variables:i,runtime:o}).runtime;return s.push(wn({id:Kc,volume:a?c.volume??li(u,"soundVolume"):An(u,"soundVolume",c.volume??Ke),muted:c.muted,pan:c.pan,children:f,runtime:u})),e},Al=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,saveSlots:d=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:b}=e;if(t.layout){let P=Je(y);if(!P)return e;let N=n.layouts[t.layout.resourceId];if(!N)return e;Array.isArray(N.transitions)&&!p&&!h&&gn({animations:b,transitions:N.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let w={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:N.elements||[]};P.children.push(di({container:w,resources:n,templateData:we({variables:o,runtime:i,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:c,skipTransitionsAndAnimations:h}))}let A=r?.layout?.resourceId,x=t.layout?.resourceId,S=Le({animationsDef:t.layout?.animations,resources:n,previousResourceId:A,currentResourceId:x,previousTargetId:A?`layout-${A}`:void 0,currentTargetId:x?`layout-${x}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return Ae({animationInstances:S,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(...S),e},wl=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=t?.screen?.animations;if(!a)return e;let l=r!=null,f=Le({animationsDef:a,resources:n,previousResourceId:l?"story":void 0,currentResourceId:"story",previousTargetId:l?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return Ae({animationInstances:f,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...f),e},El=(e,{presentationState:t})=>{let r=Je(e.elements);return!r||!t?.screen||Object.assign(r,ai(t.screen)),e},xl=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:f,overlayStack:u=[],dialogueHistory:d=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;return u&&u.length>0&&u.forEach((x,S)=>{let P=r.layouts[x.resourceId];if(!P){console.warn(`Overlay layout not found: ${x.resourceId}`);return}Array.isArray(P.transitions)&&(y||gn({animations:A,transitions:P.transitions,defaultTargetId:`overlayStack-${S}`,idPrefix:`overlayStack-${S}`,animationPathPrefix:`overlayStack[${S}]`}));let N={id:`overlayStack-${S}`,type:"container",x:0,y:0,children:[ui({id:`overlayStack-${S}-blocker`,screen:h}),...P.elements||[]]},w=fi(d,r.characters,n),M=we({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:f,historyDialogue:w,characters:r.characters||{},skipTransitionsAndAnimations:y}),F=se(N,M,{functions:Re}),[G,...j]=F.children||[],H=Oe(Ve({...F,children:j},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...H,children:G?[G,...H.children||[]]:H.children})}),e},vl=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,confirmDialog:d,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;if(!d?.resourceId)return e;let x=r.layouts?.[d.resourceId];if(!x)return console.warn(`ConfirmDialog layout not found: ${d.resourceId}`),e;Array.isArray(x.transitions)&&!y&&gn({animations:A,transitions:x.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let S={id:"confirmDialog",type:"container",x:0,y:0,children:[ui({id:"confirmDialog-blocker",screen:h}),...x.elements||[]]},P=fi(p,r.characters,n),N=se(S,we({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,confirmDialog:d,historyDialogue:P,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:Re}),[w,...M]=N.children||[],F=Oe(Ve({...N,children:M},{isLineCompleted:g,skipMode:c,skipTransitionsAndAnimations:y}),r);return b.push({...F,children:w?[w,...F.children||[]]:F.children}),e},Ct=e=>(t,r)=>ul(t,{...r,visualLayer:e}),Cl=Ct(_e.BEHIND_BACKGROUND),Sl=Ct(_e.BEHIND_CHARACTER),_l=Ct(_e.BEHIND_DIALOGUE),Rl=Ct(_e.BEHIND_CHOICE),Ol=Ct(_e.FOREGROUND),hi=e=>Bt(sl,[ml,Cl,al,Sl,cl,_l,dl,Rl,pl,hl,Al,Ol,El,wl,gl,yl,Il,xl,vl])(e);function mi(e,t=""){let r=[],n=e.length,o=0,i=0,s=-1,c=()=>{let a=0,l=0,f;do f=parseInt(e[o++],36),a+=(f&15)<<l,l+=4;while(f&16);return a};for(;o<n;){let a=s+1+c();s=a+c(),r.push([a,s,t?parseInt(t[i++],36):0])}return r}function gi(e,t,r){let n=0,o=t.length-1;for(;n<=o;){let i=n+o>>>1,s=r[i];if(e<t[i])o=i-1;else if(e>s>>>5)n=i+1;else return s&31}return 0}var yi="090001000h1v5g2903000hl2v6jh16ng1s210111110o35aa10u2k1g10l6600152113h2010u1q1r5aq3890o13181214r22k3158q2n1000v100h1k20000001207030001160721k171001h1j11610332010010321210090411021c1c02100o301201412230u1130b100h1j116111420120411001100k11l10051001h1j11611142011000321210072411021d0g10r3000000132120090o200200g1j11f2012031213711271t1001o301001000001121371b1f0c101h1l2011001031212000080a1t1001m40400102101600i11t301006c7i601008b6p41r10101041h3d0004115a1j290p3q223000511010100g1501010302003172030c0010016000e0i6v50n40n5tl12ir33s12t11u11cj30100060700010a90t220000l71i20m7203010241000502rd101004k300000006101027050920g3t22bk1300616g209030207u18c1000t10003010501b2o20000102000004g37070101o921c000640602001mcv3rg20000001o16d0c0m1fg6g2h30m10q55f1vm11c0ma0p1a42nc0ne1a090q3314902021204020112030318250105bb1201110i1021i15101131502141b15120511011k1155132040202510201010603060a1f02040104210b1g3290e0e0kn11vs12j11j3040pp12t80g6v1vmo7319g21g51gh103040n11010040j51i3f01q1h1d0m27p1a0000cs13200523j200010301010100v140018a4q2501010101c08000i1f12601011g3012215110u1a0001015000pcq181000100011000iji5fvc0u91g5bhg20ie0l94lo6002115303121s12240la1tj23h44tj11t45m4ah33q700000l3ep2021a200t220301012040a0i320j2040007f00100r20c100g3208000011531000s520201036020t900207l1101n311000000321210090a12634b910201l22001051020120011020000e1i520701020000n10h5001050000010000010001re0010323010001r11i520701000001q6000000107l600000230004gg12080001lc62027111n1000411230000000000t820321030030r10090n205001380800501020n2050c0001mc00002000000nc006150000i5l1100600010001q753011160000i441111000000rl11019100000c1h201043102n10ltk1f006eoss2b0202gs94r36si2033ku101m373h50b1rqs4113sli1t22m1uh2435070726u13k92rr7m34h380e0m141egl561g1261114k60ga6nn10t33sv13uf1jf0207150qt16t66pr60n23k6bf1f0e1l29g71c1e029j1n30p11ea0k1028139m16rb2v621122i52213040tf1u3b51n17127c0232041d120819052c28220104060306l5g3l4572g130152cqdl2c3o37a5o27u11c32d9m2cu2191obo57eh9gg1tv3",bi="262122424333333393233393339333333333393393bf3b3b3b3b3f3f3bffff33b3bb33ff3f33b3b3333333bffff3b33bb33f33bffff33b3bb33ff3f33b3bbb333b3ff33b333f33b3b3b3b3333b3bf33b3bb39333b33b33b3b3b333b333333b3b33333f3b33b3ffb3f3fff3f3b33f35dc33333f3b3b3b33323333b3bb3b33b3fb3b3333b33333bff3b3f33bfb3b3ff3b3b3b3b3b333b333b3323e22442344444444444444444444444444444444444444444444444444444444444444444444444444444443333333333b3b3bb33333b353bff3b3b3b3f3ff3b3b333bfff3f33333fb3bb3fb3b3bb33232333f333fff333333333b3b3333bb3b39393f3b3fbf33bb3b393b3b3b3333b33b33b3bbb33b33ffff3b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b3fffff3bb39b9b3b33b3bf3f3b33f3b3f93b33b3b3bb33b33b3b3b3333393b3b3b33b39bffb3b332333b333dd3b3333233332333333333333333333333333333444444444444a4444444444444344444444444444444444444444444444444444444444",Ii="0001000000010010000000100000000000000000000000000001000000010014000100000001001000010101100101100000000000000000000100000001111000010000000110101001110111111111000100000021001000010000000100100001000000011010000100000001111000013000000100140001000000010010";var Ai=65535,xn=40960,nr=126976,xi=new Uint8Array(12288),vi=new Uint8Array(3072),Ci=new Uint8Array(2816),Si,_i;{let e=(o,i,s,c,a)=>{let l=i+o.length-1;for(let f=s<i?i:s,u=c>l?l:c;f<=u;f++)o[f-i]=a},t=new Uint32Array(320),r=new Uint32Array(320),n=0;for(let[o,i,s]of mi(yi,bi))e(xi,0,o,i,s),e(vi,xn,o,i,s),e(Ci,nr,o,i,s),i>=65040&&!(o>=nr&&i<=129791)&&(t[n]=o,r[n++]=i<<5|s);Si=t.slice(0,n),_i=r.slice(0,n)}function wi(e){return e<12288?xi[e]:e<xn?e<12336?e>=12330?3:0:e<12443?e===12336||e===12349?4:e>=12441?3:0:e===12951||e===12953?4:0:e<44032?vi[e-xn]:e<55204?(e-44032)%28?8:7:e<57344?e<=55238?e>=55216?13:0:e>=55243&&e<=55291?12:0:e<65024?e===64286?3:0:e<65040?3:e>=nr&&e<129792?Ci[e-nr]:e>=917504?e>921599?0:e>=917536&&e<917632||e>=917760&&e<918e3?3:2:gi(e,Si,_i)}var Ri=Uint8Array.from(Ii,Number);function Ll(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 Ei(e,t,r){switch(t){case 3:return e&24?r===8204?e&6:(e&24)===16||Ll(r)?e&6|16:e&6|8:e&6;case 4:return 2;case 10:return e&1^1;case 14:return(e&2)<<1|e&24;default:return 8}}function*Oi(e){let t=e.length;if(t===0)return;let r=e.codePointAt(0),n=r>Ai?2:1,o=wi(r),i=50200>>o&1?Ei(0,o,r):0,s=0,c=r,a=o;for(;n<t;){r=e.codePointAt(n);let l=r>Ai?2:1,f=wi(r),u=Ri[o<<4|f],d;u===0?d=!0:u===1?d=!1:u===2?d=!(i&1):u===3?d=!(i&4):d=(i&24)!==16,i=50200>>f&1&&(i!==0||f!==3)?Ei(i,f,r):0,d&&(yield{segment:e.slice(s,n),index:s,input:e,_hd:c,_catBegin:a===15?0:a,_catEnd:o===15?0:o},s=n,c=r,a=f),n+=l,o=f}yield{segment:e.slice(s),index:s,input:e,_hd:c,_catBegin:a===15?0:a,_catEnd:o===15?0:o}}function*Li(e){for(let t of Oi(e))yield t.segment}{let e=Oi("_");Ri._keep=[e,e.next()]}var $i=1e3,$l=1,kl=60,Dl=3,Tl=.5,Pl=2e4,Nl=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,Vl=/^\s+$/u,ki,jl=e=>{let t=`${e??""}`.normalize("NFC"),r=globalThis.Intl?.Segmenter;return typeof r!="function"?Array.from(Li(t)):(ki??=new r(void 0,{granularity:"grapheme"}),Array.from(ki.segment(t),({segment:n})=>n))},Fl=e=>jl(e).reduce((t,r)=>Vl.test(r)?t+Tl:Nl.test(r)?t+Dl:t+1,0),Di=({text:e="",baseDelay:t=$i,speed:r=$l}={})=>{let n=Number.isFinite(t)?Math.max(0,t):$i,o=Number.isFinite(r)&&r>0?r:1,i=Fl(e)*kl/o,s=Math.max(n,Pl);return Math.min(n+i,s)};var or={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},ji=1,cr="choice",ir="form",lr=()=>({manual:{...or.manual},auto:{...or.auto},applyMode:or.applyMode}),vn=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...lr()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},T=e=>{let t=de(e)?ze(e):e;return structuredClone(t)},D=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ur=e=>String(e),Fi=()=>({sections:[],resources:[]}),Ml=e=>D(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Fi(),Ul=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Bl=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:Ul(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),zl=()=>({resourceId:void 0}),Wl=e=>{if(!D(e))return e;let t={...e};return Object.prototype.hasOwnProperty.call(t,"requireComplete")&&!Object.prototype.hasOwnProperty.call(t,"requireLineCompleted")&&(t.requireLineCompleted=t.requireComplete),delete t.requireComplete,t},Cn=(e,t)=>{let r=e?.story?.scenes??{};for(let[n,o]of Object.entries(r))if(o?.sections?.[t])return{sceneId:n,section:o.sections[t]};return{sceneId:void 0,section:void 0}},Mi=e=>{let t=e?.story?.scenes??{},r=new Map;for(let[n,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let c=r.get(s);if(c!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${c}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},Ui=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Bi=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==ji)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},ql=(e,t={})=>{let r;try{r=Bi(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:Ui(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},Hl=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,ql(t,r)])),zi=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Mf(r));return t.length>0?t:void 0},Yl=e=>{!D(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!D(t))return;let r=zi(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},Ti=(e,t,r,n="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!D(e))throw new Error(`Malformed ${n}.${t}[${r}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${n}.${t}[${r}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${n}.sections[${r}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},Gl=(e,t="viewedRegistry")=>{if(e===void 0)return Fi();if(!D(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let r=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Ti(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Ti(o,"resources",i,t);return[s.resourceId,s]})))}},Wi=(e,t,r)=>{if(!D(e))throw new Error(`Malformed save slot ${r}.`);let{sectionId:n,lineId:o}=e;if(typeof n!="string"||n.length===0)throw new Error(`Malformed save slot ${r}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${r}: missing lineId.`);let{sceneId:i,section:s}=Cn(t,n);if(!s)throw new Error(`Malformed save slot ${r}: section "${n}" does not exist in projectData.`);if(!s.lines?.some(a=>a.id===o))throw new Error(`Malformed save slot ${r}: line "${o}" does not exist in section "${n}".`);return{sceneId:i,sectionId:n,lineId:o}},Kl=(e,t,r)=>{if(!D(e)||!Array.isArray(e.timeline))return St({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((c,a)=>{if(!D(c))return[];try{let l=Wi(c,r,`rollback.timeline[${a}]`),f=ar({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:c.rollbackPolicy}),u=zi(T(c.executedActions));return u&&(f.executedActions=u),[f]}catch{return[]}});if(n.length===0)return St({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):n.length-1;(o<0||o>=n.length)&&(o=n.length-1);let i=n[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let c=n.findLastIndex(a=>a.sectionId===t.sectionId&&a.lineId===t.lineId);c>=0?o=c:(n.push(ar({sectionId:t.sectionId,lineId:t.lineId})),o=n.length-1)}let s=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),o):0;return{currentIndex:o,isRestoring:!1,replayStartIndex:s,timeline:n}},Jl=(e,t,r)=>{if(!D(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=Rn(t),o=Wi(e.pointers?.read,t,`contexts[${r}].pointers.read`);if(e.variables!==void 0&&!D(e.variables))throw new Error(`Malformed save slot contexts[${r}].variables entry.`);if(e.runtime!==void 0&&!D(e.runtime))throw new Error(`Malformed save slot contexts[${r}].runtime entry.`);let i=e.variables?ot(T(e.variables),t.resources?.variables??{}):{},s=lu({loadedContextRuntime:D(e.runtime)?T(e.runtime):{}}),c={currentPointerMode:"read",pointers:{read:o},configuration:D(e.configuration)?T(e.configuration):{},views:Array.isArray(e.views)?T(e.views):[],bgm:D(e.bgm)?T(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:Kl(e.rollback,o,t)};return s&&(c.runtime=s),c},Xl=(e,t)=>{if(!D(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((r,n)=>Jl(r,t,n))}},Ql=(e,t)=>{if(!D(e))throw new Error("Malformed save slot.");let r=Bi(e.formatVersion);return{...e,formatVersion:r,state:Xl(e.state,t)}},Pi=(e,t,{required:r=!1}={})=>{if(e===void 0){if(r)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let n=T(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},Zl=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Pi(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Pi(e.cancelActions,"cancelActions")}},lt=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},eu=e=>(D(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),ut=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},qi=e=>{if(!(!D(e)||!e.animations))return{animations:T(e.animations)}},tu=(e,t)=>{let r=qi(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},ru=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},nu=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},sr=e=>String(e??""),Hi=(e,t)=>{let r=sr(t);return e?.trim===!0?r.trim():r},ou=e=>D(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>D(t)).map(([t,r])=>[t,{id:t,...T(r)}])):{},iu=(e,t)=>{if(!t||!D(e.global.formDrafts))return;let r=e.global.formDrafts[t];return D(r)?r:void 0},Yi=(e,t)=>{let r=eu(e);D(r[t])||(r[t]={values:{},touched:{},errors:{},submitted:!1});let n=r[t];return D(n.values)||(n.values={}),D(n.touched)||(n.touched={}),D(n.errors)||(n.errors={}),typeof n.submitted!="boolean"&&(n.submitted=!1),n},Sn=(e,t)=>{let r=Hi(e,t);return e?.required===!0&&r.length===0?"required":null},su=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=ae({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:qe(n.slice(0,o+1).map(i=>i.actions||{}))},au=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=ru(t),o=nu(r,n);if(!n||!o)return null;let i=iu(e,o),s=ou(t),c=dr({state:e}),a={},l=[],f={},u=!0;return Object.entries(s).forEach(([d,p])=>{let h=sr(c?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},d)?sr(i.values[d]):h,y=i?.touched?.[d]===!0,b=Sn(p,g),A=i?.submitted||y?b:null,x=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,S={id:d,variableId:p.variableId,value:g,initialValue:h,valid:!b,error:A,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...x!==void 0?{maxLength:x}:{}};b&&(u=!1),a[d]=S,l.push(S),f[d]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:u,submitted:i?.submitted===!0,fields:a,fieldList:l,values:f,submitActions:{submitForm:{formKey:o,actions:T(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:T(t.cancelActions??{})}}}},Xe=[],Ni="line",_n="interaction",ar=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),Rn=e=>{let{contextVariableDefaultValues:t}=Wt(e??{});return T(t)},Gi=()=>({...T(At)}),Ki=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:T(r),hasLoadedValues:!1};if(!D(e))throw new Error(`Malformed ${n}.`);let o=T(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Ji(s,T(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},cu=({loadedGlobalRuntime:e={}})=>Ki({loadedRuntime:e,runtimeIds:Gr,defaults:He,path:"global.runtime"}).runtimeState,lu=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=Ki({loadedRuntime:e,runtimeIds:Kr,defaults:Gi(),path:"context.runtime"});return r?t:void 0},fr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},uu=e=>e.runtime?(Kr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=T(At[t]))}),e.runtime):(e.runtime=Gi(),e.runtime),fu=e=>jo(e.global),du=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:fu(e)}})},pu=e=>Vo[e],hu=(e,t)=>{let r=pu(e);if(r==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(r==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(r==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},Ji=(e,t)=>{if(hu(e,t),e==="autoForwardSpeed"&&t<=0)throw new Error("autoForwardSpeed requires a value greater than 0");return e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t},Xi=(e,t,r)=>{let n=Ji(t,r);if(t in At){let o=fr(e);if(!o)return n;let i=uu(o);return i[t]=n,n}return e.global[t]=n,n},Qi=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:T(e)},configuration:{},views:[],bgm:zl(),variables:Rn(t),rollback:St({pointer:e})}),ft=e=>e?(e.currentPointerMode="read",D(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,mu=(e,{queueRender:t=!0}={})=>{let r=e.contexts?.[e.contexts.length-1],n=r?.pointers?.read;if(!r||!n?.sectionId||!n?.lineId)return null;let o=Qi({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,gu(e,{queueRender:t}),o},gu=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,lt(e),ut(e),e.global.nextLineConfig=lr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},Zi=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},St=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[ar({sectionId:e.sectionId,lineId:e.lineId})]:[]}},et=(e,t={})=>{if(e?.rollback)return Zi(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let r=e?.pointers?.read;return e.rollback=St({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},On=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=et(r);if(n.isRestoring)return;n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1));let o=n.timeline[n.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){n.currentIndex=n.timeline.length-1;return}n.timeline.push(ar(t)),n.currentIndex=n.timeline.length-1},yu=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;if(!r||r.isRestoring||!Array.isArray(r.timeline)||typeof r.currentIndex!="number")return null;let n=Xe[Xe.length-1],o=typeof n?.checkpointIndex=="number"?n.checkpointIndex:r.currentIndex;return o<0||o>=r.timeline.length?null:(typeof n?.checkpointIndex!="number"&&o<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,o+1)),r.timeline[o]??null)},bu=({state:e},t={})=>{let r=t?.source===Ni?Ni:_n,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?(Xe.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Xe.push({checkpointIndex:o.currentIndex,source:r}),e)},Iu=({state:e})=>(Xe.pop(),e),Se=(e,t,r)=>{let o=Xe[Xe.length-1]?.source??_n;if(!Uf(t,o))return;let i=yu(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:T(r)}))},Vi=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:c}of n){let a=e.projectData.resources?.variables?.[o],l=a?.scope,f=a?.type;if(Te(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);qt(l,o),Ht(f,i,o),zr(f,i,s,o,{roundTo:c}),l==="context"&&(r.variables[o]=Yt(r.variables[o],i,s,{roundTo:c}))}},Au=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{Bf(e,r,n)})},wu=(e,t)=>{let{sectionId:r,lineId:n}=t,s=ae({state:e},{sectionId:r})?.lines?.find(c=>c.id===n)?.actions;s&&Object.entries(s).forEach(([c,a])=>{gs(e,c,a)})},es=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=et(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&gr({state:e}),e.global.skipMode&&Qe({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=Rn(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=T(or),e.global.overlayStack=[],lt(e),ut(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let c=i;c<=t;c++)c>i&&vn(e),wu(e,n.timeline[c]),Au(e,n.timeline[c]);let s=ft(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(c=>c?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},Eu=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;Mi(t);let c=t.story.initialSceneId,a=t.story.scenes[c],l=a.initialSectionId,f=a.sections[l],u={sceneId:c,sectionId:l,lineId:f.initialLineId??f.lines[0].id},{globalVariablesDefaultValues:d}=Wt(t),p={...d,...ot(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:Gl(s,"accountViewedRegistry"),nextLineConfig:lr(),saveSlots:Hl(n),overlayStack:[],variables:p,...cu({loadedGlobalRuntime:i})},contexts:[Qi({pointer:u,projectData:t})]}},xu=({state:e})=>e.global.overlayStack||[],vu=({state:e})=>e.global.pendingEffects,ts=({state:e})=>e.global.skipMode,Cu=({state:e})=>e.global.autoMode,rs=({state:e})=>e.global.dialogueUIHidden,ns=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(!r)return[];let{sectionId:n,lineId:o}=r.pointers.read,i=ae({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),c=i.lines.slice(0,s+1),a=[],l={},f=bt({variables:{...e.global?.variables??{},...fr(e)?.variables??{}},runtime:Ye(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let u of c){let d=u.actions||{};if(l=qe([l,d]),!d.dialogue)continue;let p=l.dialogue||{},h=zt({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:f}),g=Bl({sectionId:n,lineId:u.id,content:d.dialogue.append===!0?p.content:d.dialogue.content,dialogueState:p,characterName:h});if(d.dialogue.append===!0&&a.length>0){a[a.length-1]={...a[a.length-1],content:g.content,text:g.text,characterId:g.characterId,character:g.character,characterName:g.characterName};continue}a.push(g)}return a},Su=({state:e})=>e.global.confirmDialog??null,_t=({state:e},{pointer:t}={})=>{let r=t??Ee({state:e})?.pointer,n=su({state:e,pointer:r});return au({state:e,form:n.form,pointer:r})},_u=({state:e},{pointer:t}={})=>!!_t({state:e},{pointer:t}),ye=({state:e},{pointer:t}={})=>{let r=_t({state:e},{pointer:t});if(r)return{source:ir,formId:r.id,formKey:r.key};let n=os({state:e,pointer:t});return n?{source:cr,resourceId:n}:null},Ru=({state:e,registry:t},r)=>{let{sectionId:n,lineId:o}=r,s=(Array.isArray(t?.sections)?t.sections:[]).find(f=>f.sectionId===n);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let c=ae({state:e},{sectionId:n});if(!c||!c.lines||!Array.isArray(c.lines))return s.lastLineId===o;let a=c.lines.findIndex(f=>f.id===s.lastLineId),l=c.lines.findIndex(f=>f.id===o);return a===-1||l===-1?s.lastLineId===o:l<=a},Ou=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},Ln=({state:e},t)=>Ru({state:e,registry:e.global.accountViewedRegistry},t),Lu=({state:e},t)=>Ou({registry:e.global.accountViewedRegistry},t),$u=({state:e})=>e.global.nextLineConfig,os=({state:e,pointer:t}={})=>{let r=t??Ee({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=ae({state:e},{sectionId:n})?.lines||[],c=s.findIndex(l=>l.id===o);if(c<0)return;let a;for(let l of s.slice(0,c+1)){let f=l?.actions;if(f?.cleanAll&&(a=void 0),!f||!Object.prototype.hasOwnProperty.call(f,"choice")){a=void 0;continue}let u=f.choice;if(u?.resourceId){a=u.resourceId;continue}u?.animations||(a=void 0)}return a},is=({state:e})=>!!os({state:e}),ku=({state:e})=>structuredClone(e),ss=({state:e})=>e.global.saveSlots,Du=({state:e},t)=>{let r=t?.slotId,n=ur(r);return e.global.saveSlots[n]},$n=({state:e})=>Ye(e),Tu=({state:e},t)=>Pe(e,t?.runtimeId),dr=({state:e})=>{let t={...e.global?.variables??{},...fr(e)?.variables??{}};return bt({variables:t,runtime:Ye(e),variableConfigs:e.projectData.resources?.variables??{}})},Ee=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},ae=({state:e},t)=>{let{sectionId:r}=t;return Cn(e.projectData,r).section},pr=({state:e})=>{let t=Ee({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=ae({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},as=({state:e})=>{let{sectionId:t,lineId:r}=Ee({state:e}).pointer,o=ae({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===r),c=o.slice(0,i+1).map(l=>{let f=l.actions||{},u={};return Object.keys(f).forEach(d=>{u[d]=f[d]}),u});return qe(c)},Pu=e=>{let t=pr({state:e})?.actions?.dialogue;if(t?.clear===!0||!Array.isArray(t?.content))return"";let r=dr({state:e});return t.content.map(n=>`${it(n?.text,{variables:r})??""}`).join("")},hr=({state:e})=>Di({text:Pu(e),baseDelay:Pe(e,"autoForwardDelay"),speed:Pe(e,"autoForwardSpeed")}),Nu=({state:e})=>{let t=cs({state:e}),n=pr({state:e})?.actions??{},o=qe([t??{},n]);return Wr(t??{},o??{})},Vu=({state:e},{sectionId:t})=>{let r=ae({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},c=qe([o,s]),a=Wr(o,c);n.push({id:i.id,changes:a,presentationState:c}),o=qr(c)}return n},ju=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=Vu({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},cs=({state:e})=>{let{sectionId:t,lineId:r}=Ee({state:e}).pointer,o=ae({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===r);if(i<=0)return null;let c=o.slice(0,i).map(a=>{let l=a.actions||{},f={};return Object.keys(l).forEach(u=>{f[u]=l[u]}),f});return qr(qe(c))},kn=({state:e},{slotsPerPage:t=6}={})=>{let o=(($n({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let c=o+s,a=e.global.saveSlots&&e.global.saveSlots[ur(c)]||{};i.push({...a,slotId:c})}return{saveSlots:i}},Fu=ss,Mu=kn,Uu=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;return!r||!Array.isArray(r.timeline)||typeof r.currentIndex!="number"?!1:r.currentIndex>=0&&r.currentIndex<r.timeline.length-1},Bu=({state:e},t={})=>{let r=as({state:e}),n=cs({state:e}),o=pr({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:T(i)}:o,c=i?.animations&&n===null?{}:n,{sectionId:a}=Ee({state:e}).pointer,{sceneId:l}=Cn(e.projectData,a),f=$n({state:e}),u=t?.activePersistentAnimations??[],d=t?.restoredPersistentAnimations??[],p=_t({state:e}),h=is({state:e}),g=dr({state:e}),{saveSlots:y}=kn({state:e}),b=Uu(e);return hi({presentationState:r,previousPresentationState:c,currentLineActions:s,resources:e.projectData.resources,currentSceneId:l,screen:e.projectData.screen,dialogueUIHidden:f.dialogueUIHidden,autoMode:f.autoMode,skipMode:f.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:bs({state:e}),skipOnlyViewedLines:!f.skipUnseenText,isLineCompleted:f.isLineCompleted,skipTransitionsAndAnimations:!!f.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:ns({state:e}),saveSlots:y,variables:g,runtime:f,activePersistentAnimations:u,restoredPersistentAnimations:d})},zu=({state:e},t)=>(e.global.confirmDialog=Zl(t),e.global.pendingEffects.push({name:"render"}),e),Wu=({state:e})=>(e.global.confirmDialog&&(lt(e),e.global.pendingEffects.push({name:"render"})),e),qu=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Se(e,"pushOverlay",t),e),Hu=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Se(e,"popOverlay",void 0),e),Yu=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),Se(e,"replaceLastOverlay",t),e),Gu=({state:e})=>(e.global.overlayStack=[],lt(e),ut(e),e.global.pendingEffects.push({name:"render"}),Se(e,"clearOverlays",void 0),e),Ku=e=>{e.global.autoMode&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.skipMode&&e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},mr=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,tu(e,r),ut(e);let n=ye({state:e},{pointer:t}),o=n?.source===cr,i=n?.source===ir;return n&&Ku(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},Dn=(e,t,r)=>{t?.source!==cr||r||!e.global.skipMode||e.global.pendingEffects.push({name:"startSkipNextTimer"})},ls=({state:e})=>(ye({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:hr({state:e})}}),e.global.pendingEffects.push({name:"render"})),e),gr=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Ju=({state:e})=>{let t=e.global.autoMode;return ye({state:e})&&!t||(t?gr({state:e}):ls({state:e})),e},us=({state:e})=>(ye({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),Qe=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Xu=({state:e})=>{let t=ts({state:e});return ye({state:e})&&!t||(t?Qe({state:e}):us({state:e})),e},yr=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Se(e,"showDialogueUI",void 0),e),fs=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Se(e,"hideDialogueUI",void 0),e),Qu=({state:e})=>(rs({state:e})?yr({state:e}):fs({state:e}),e),je=(e,t,r)=>(Xi(e,t,r),du(e),e.global.pendingEffects.push({name:"render"}),e),Rt=(e,t,r,n)=>{let o=Xi(e,t,r);return e.global.pendingEffects.push({name:"render"}),Se(e,n,{value:o}),e},Zu=({state:e},t)=>je(e,"dialogueTextSpeed",t?.value),ef=({state:e},t)=>je(e,"autoForwardDelay",t?.value),tf=({state:e},t)=>je(e,"autoForwardSpeed",t?.value),rf=({state:e},t)=>je(e,"skipUnseenText",t?.value),nf=({state:e},t)=>je(e,"skipTransitionsAndAnimations",t?.value),of=({state:e},t)=>je(e,"soundVolume",t?.value),sf=({state:e},t)=>je(e,"musicVolume",t?.value),af=({state:e},t)=>je(e,"muteAll",t?.value),cf=({state:e},t)=>Rt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),lf=({state:e})=>{let t=Pe(e,"saveLoadPagination")+1;return Rt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},uf=({state:e})=>{let t=Pe(e,"saveLoadPagination")-1;return Rt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},ff=({state:e},t)=>Rt(e,"menuPage",t?.value,"setMenuPage"),df=({state:e},t)=>Rt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),pf=({state:e})=>(e.global.pendingEffects=[],e),hf=({state:e},t)=>(e.global.pendingEffects.push(t),e),ds=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!qi(n),i=ae({state:e},{sectionId:t});if(!i)return console.warn(`Section not found: ${t}`),e;let s=i.lines?.[0];if(!s)return console.warn(`Section ${t} has no lines`),e;if(r&&!mu(e,{queueRender:!o}))return e;let c=ye({state:e});r&&e.global.skipMode&&Qe({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let f=ft(a),u=f.read;r||Ze(e,{sectionId:u?.sectionId,lineId:u?.lineId}),a.rollback||et(a,{compatibilityAnchor:!0}),f.read={sectionId:t,lineId:s.id},r?a.rollback=St({pointer:f.read}):On(e,{sectionId:t,lineId:s.id})}let{activeInteraction:l}=mr(e,a?.pointers?.read,{screenTransition:n});return Dn(e,c,l),!r&&e.global.autoMode&&!c&&!l&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e},mf=({state:e},t)=>ds(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),ps=e=>(e.global.accountViewedRegistry=Ml(e.global.accountViewedRegistry),e.global.accountViewedRegistry),Tn=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(r=>({scope:r.scope,path:r.path,op:r.op,value:T(r.value)}))}})},hs=(e,t)=>{Tn(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(r=>({sectionId:r.sectionId,...r.lastLineId===void 0?{}:{lineId:r.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},gf=(e,t,{sectionId:r,lineId:n})=>{if(!r||!n)return!1;let o=D(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===r);if(i){if(i.lastLineId===void 0)return!1;let s=ae({state:e},{sectionId:r});if(s?.lines){let c=s.lines.findIndex(l=>l.id===i.lastLineId),a=s.lines.findIndex(l=>l.id===n);if(c===-1||a>c)return i.lastLineId===n?!1:(i.lastLineId=n,!0)}else return i.lastLineId===n?!1:(i.lastLineId=n,!0);return!1}else return o.sections.push({sectionId:r,lastLineId:n}),!0},Ze=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;gf(e,ps(e),t)&&hs(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},yf=({state:e},t)=>(Ze(e,t),e.global.pendingEffects.push({name:"render"}),e),bf=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=ps(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),hs(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},ms=({state:e},t)=>{let r=Wl(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,c=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;r&&n?(e.global.nextLineConfig={manual:r,auto:n},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(r&&(e.global.nextLineConfig.manual=r),n&&(e.global.nextLineConfig.auto=n),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let a=e.global.nextLineConfig.auto?.enabled,l=ye({state:e});return!c&&!l&&a===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!c&&a===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),Se(e,"setNextLineConfig",t),e},If=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:n}=t,o=t?.savedAt,i=ur(r),s=T(e.contexts);s?.forEach(l=>{ft(l),Zi(l.rollback),Yl(l.rollback)});let c={contexts:s},a={formatVersion:ji,slotId:Ui(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:c};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Af=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=ur(r),o=e.global.saveSlots[n];if(o){let i=Ql(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=lr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,lt(e),ut(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},wf=({state:e},t)=>{let{projectData:r}=t;Mi(r),e.projectData=r;let n=r?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=Wt(r??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...ot(e.global.variables,n)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...ot(s.variables,n)})}),lt(e),ut(e),e.global.pendingEffects.push({name:"render"}),e},Ef=({state:e},t)=>{let{sectionId:r,lineId:n}=t;if(!n)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=r||o.pointers.read?.sectionId;if(r&&!ae({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=ae({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(u=>u.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let a=ye({state:e}),l=ft(o);l.read={sectionId:i,lineId:n};let{activeInteraction:f}=mr(e,l.read);return Dn(e,a,f),e},xf=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return yr({state:e}),e;let r=ye({state:e});if(r?.source===cr&&t?.bypassChoice!==!0||r?.source===ir&&t?._interactionSource!==ir)return e;let n=Ee({state:e})?.pointer,o=n?.sectionId,s=ae({state:e},{sectionId:o})?.lines||[],a=s.findIndex(u=>u.id===n?.lineId)+1,l=t?._advanceImmediately===!0&&a<s.length;if(!e.global.isLineCompleted&&!l){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=n?.lineId;o&&u&&Ze(e,{sectionId:o,lineId:u}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&!r&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:hr({state:e})}});let d=e.global.nextLineConfig;return d?.auto?.enabled&&!r&&d.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:d.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let f=e.contexts[e.contexts.length-1];if(a<s.length){let u=s[a],d=!Pe(e,"skipUnseenText");if(e.global.skipMode&&d&&!Ln({state:e},{sectionId:o,lineId:u.id}))return Qe({state:e}),e;if(f&&!f.rollback&&et(f,{compatibilityAnchor:!0}),f){let g=ft(f),y=g.read?.lineId;y&&o&&Ze(e,{sectionId:o,lineId:y}),g.read={sectionId:o,lineId:u.id}}On(e,{sectionId:o,lineId:u.id}),vn(e);let{activeInteraction:p}=mr(e,{sectionId:o,lineId:u.id});Dn(e,r,p);let h=e.global.nextLineConfig;h?.auto?.enabled&&!p&&h.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:h.auto.delay}})}else e.global.autoMode&&gr({state:e}),e.global.skipMode&&Qe({state:e});return e},vf=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=ye({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:hr({state:e})}});let r=Ee({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&Ze(e,{sectionId:n,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},Cf=({state:e},t)=>ds(e,{sectionId:t?.sectionId,screen:t?.screen}),Sf=({state:e})=>{if(e.global.dialogueUIHidden)return yr({state:e}),e;if(ye({state:e}))return e;let t=Ee({state:e})?.pointer,r=t?.sectionId,n=ae({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],c=i.findIndex(a=>a.id===t?.lineId)+1;if(c<i.length){let a=i[c],l=!Pe(e,"skipUnseenText");if(e.global.skipMode&&l&&!Ln({state:e},{sectionId:r,lineId:a.id}))return Qe({state:e}),e;if(o&&!o.rollback&&et(o,{compatibilityAnchor:!0}),o){let u=ft(o),d=u.read?.lineId;d&&r&&Ze(e,{sectionId:r,lineId:d}),u.read={sectionId:r,lineId:a.id}}On(e,{sectionId:r,lineId:a.id}),vn(e);let{activeInteraction:f}=mr(e,{sectionId:r,lineId:a.id});e.global.nextLineConfig.auto?.enabled&&!f&&e.global.nextLineConfig.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})}else e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},Pn=(e,t={})=>{let r=_t({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},_f=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let r=e.projectData.resources?.variables?.[t.variableId],n=r?.scope,o=r?.type;if(Te(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return qt(n,t.variableId),Ht(o,"set",t.variableId),{variableConfig:r,scope:n}},Rf=(e,t)=>({id:e.id,key:e.key,valid:!0,values:T(t),fields:T(e.fields),fieldList:T(e.fieldList)}),Of=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ee({state:e})?.pointer,r=t?.sectionId,n=t?.lineId;r&&n&&Ze(e,{sectionId:r,lineId:n})},Lf=({state:e},t={})=>{let r=Pn(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=Yi(e,r.key),i=sr(t.value),s=r.fields[n],c=Sn(s,i);return o.values[n]=i,o.touched[n]=!0,c?o.errors[n]=c:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},$f=({state:e},t={})=>{let r=Pn(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=Yi(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([u,d])=>{let p=Object.prototype.hasOwnProperty.call(n.values,u)?n.values[u]:d.value,h=Sn(d,p);n.touched[u]=!0,h&&(i[u]=h),o[u]=Hi(d,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:T(i),form:{id:r.id,key:r.key,values:T(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let c=!1,a=[],l=[];Object.entries(r.fields).forEach(([u,d])=>{let{scope:p}=_f(e,d),h=p==="context"?s.variables:e.global.variables,g=o[u];h[d.variableId]=Yt(h[d.variableId],"set",g),p==="context"&&(c=!0,l.push({variableId:d.variableId,op:"set",value:g})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${d.variableId}`,op:"set",value:T(h[d.variableId])})}),c&&Se(e,"updateVariable",{id:"submitForm",operations:l}),Tn(e,a);let f=Rf(r,o);return Of(e),delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:f}},kf=({state:e},t={})=>{let r=Pn(e,t);return r?(delete e.global.formDrafts?.[r.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:r.id,key:r.key,values:T(r.values),fields:T(r.fields),fieldList:T(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},Df=({state:e},t)=>{let{id:r,operations:n=[]}=t;if(!r)throw new Error("updateVariable requires an id field");if(typeof r!="string"||!/^[a-zA-Z0-9]+$/.test(r))throw new Error(`updateVariable id must be alphanumeric, got: "${r}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],c=[];return n.forEach(({variableId:a,op:l,value:f,roundTo:u})=>{let d=e.projectData.resources?.variables?.[a],p=d?.scope,h=d?.type;if(Te(d))throw new Error(`Cannot update computed variable: ${a}`);if(d?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);qt(p,a),Ht(h,l,a),zr(h,l,f,a,{roundTo:u});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:a,op:l,value:f};u!==void 0&&(y.roundTo=u),c.push(y)}g[a]=Yt(g[a],l,f,{roundTo:u}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:T(g[a])})}),i&&Se(e,"updateVariable",{id:r,operations:c}),Tn(e,s),e.global.pendingEffects.push({name:"render"}),e},Tf=e=>(t,r)=>e({state:t},r),Pf=e=>({variables:bt({variables:{...e.global?.variables??{},...fr(e)?.variables??{}},runtime:Ye(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:Ye(e)}),Nf=e=>{if(!D(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")},Vf=(e,t,r)=>{if(!D(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!D(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==r-1)throw new Error("conditional else branch must be the last branch")},jf=(e,t)=>{Nf(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(Vf(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!yt(n.when,Pf(e)))){Object.entries(n.actions).forEach(([i,s])=>{gs(e,i,s)});return}}},Ff={conditional:{replayLine:jf},updateVariable:{recordSources:[_n],replayLine:Vi,replayRecorded:Vi,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Tf(ms)}},br=e=>Ff[e]??null,Mf=e=>br(e)?.persistInSaveSlot===!0,Uf=(e,t)=>{let r=br(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},Bf=(e,t,r)=>{br(t)?.replayRecorded?.(e,r)},gs=(e,t,r)=>{br(t)?.replayLine?.(e,r)},ys=({state:e},t)=>{let{offset:r}=t;if(r===void 0||typeof r!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let n=e.contexts[e.contexts.length-1];if(!n)return null;let o=n.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+r;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},bs=({state:e})=>ys({state:e},{offset:-1})!==null,zf=({state:e},t)=>{let{offset:r=-1}=t;if(r>=0)throw new Error("rollbackByOffset requires a negative offset");let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let o=et(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:es(e,i)},Wf=({state:e},t)=>{let{sectionId:r,lineId:n}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=et(o,{compatibilityAnchor:!o.rollback}),c=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===r&&a.lineId===n);if(c===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return c===i.currentIndex?e:es(e,c)},Is=e=>{let t=Eu(e);return wo(t,{selectPendingEffects:vu,selectSkipMode:ts,selectAutoMode:Cu,selectIsChoiceVisible:is,selectIsFormVisible:_u,selectActiveInteraction:ye,selectActiveForm:_t,selectDialogueUIHidden:rs,selectDialogueHistory:ns,selectConfirmDialog:Su,selectIsLineAccountViewed:Ln,selectIsResourceAccountViewed:Lu,selectNextLineConfig:$u,selectSystemState:ku,selectSaveSlotMap:ss,selectSaveSlots:Fu,selectSaveSlot:Du,selectRuntime:$n,selectRuntimeValue:Tu,selectAllVariables:dr,selectCurrentPointer:Ee,selectSection:ae,selectCurrentLine:pr,selectPresentationState:as,selectAutoForwardTimerDelay:hr,selectPresentationChanges:Nu,selectSectionLineChanges:ju,selectSaveSlotPage:kn,selectCurrentPageSlots:Mu,selectRenderState:Bu,selectOverlayStack:xu,selectLineIdByOffset:ys,selectCanRollback:bs,startAutoMode:ls,stopAutoMode:gr,toggleAutoMode:Ju,startSkipMode:us,stopSkipMode:Qe,toggleSkipMode:Xu,showDialogueUI:yr,hideDialogueUI:fs,toggleDialogueUI:Qu,setDialogueTextSpeed:Zu,setAutoForwardDelay:ef,setAutoForwardSpeed:tf,setSkipUnseenText:rf,setSkipTransitionsAndAnimations:nf,setSoundVolume:of,setMusicVolume:sf,setMuteAll:af,setSaveLoadPagination:cf,incrementSaveLoadPagination:lf,decrementSaveLoadPagination:uf,setMenuPage:ff,setMenuEntryPoint:df,showConfirmDialog:zu,hideConfirmDialog:Wu,resetStoryAtSection:mf,clearPendingEffects:pf,appendPendingEffect:hf,beginRollbackActionBatch:bu,endRollbackActionBatch:Iu,addViewedLine:yf,addViewedResource:bf,setNextLineConfig:ms,saveSlot:If,loadSlot:Af,updateProjectData:wf,sectionTransition:Cf,jumpToLine:Ef,nextLine:xf,markLineCompleted:vf,rollbackToLine:Wf,rollbackByOffset:zf,pushOverlay:qu,popOverlay:Hu,replaceLastOverlay:Yu,clearOverlays:Gu,updateFormField:Lf,submitForm:$f,cancelForm:kf,updateVariable:Df,nextLineFromSystem:Sf},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var qf="route-engine",Hf="projectPersistence";var ws=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),te=e=>Object.prototype.toString.call(e)==="[object Object]",As="variables.",Yf=(e={})=>{let t=te(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!te(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lineId=="string"?{lineId:r.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!te(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Gf=(e={})=>{let t=te(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!te(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lastLineId=="string"?{lastLineId:r.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!te(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Kf=(e,t)=>{let r=Gf(e),n=Yf(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let c=o.find(a=>a.sectionId===s.sectionId);if(!c){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(c.lastLineId!==void 0){if(s.lineId===void 0){delete c.lastLineId;return}c.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},Es=(e={})=>{let t=te(e)?e:{};return{saveSlots:te(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:te(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:te(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:te(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:te(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Jf=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!te(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(As)?t.path.slice(As.length):null;if(n!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(n.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${r}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:n}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${r}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${r}].`)})},Xf=(e,t)=>{let r={};return Jf(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=Kf(r.accountViewedRegistry??e.accountViewedRegistry,n.value);return}let o=n.scope==="device"?"globalDeviceVariables":"globalAccountVariables";r[o]={...e[o],...r[o],[n.variableId]:n.value}}),r},Nn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},Qf=e=>{let t=Nn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Zf=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},ed=({indexedDB:e,databaseName:t,objectStoreName:r})=>new Promise((n,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(r)||s.createObjectStore(r,{keyPath:"namespace"})},i.onsuccess=()=>{n(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),td=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let a=n.transaction(t,"readonly").objectStore(t).get(r);a.onsuccess=()=>{o(a.result??null)},a.onerror=()=>{i(a.error??new Error(`Failed to read persisted namespace "${r}" from IndexedDB.`))}})},Ot=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let c=o.transaction(t,"readwrite"),a=c.objectStore(t),l=a.get(r),f=!1,u=p=>{f||(f=!0,s(p))},d=()=>{f||(f=!0,i())};l.onerror=()=>{u(l.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},l.onsuccess=()=>{let p=Es(l.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...ws(),...p,...h},y=a.put(g);y.onerror=()=>{u(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},c.oncomplete=()=>{d()},c.onerror=()=>{u(c.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},c.onabort=()=>{u(c.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},rd=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let s=n.transaction(t,"readwrite"),a=s.objectStore(t).delete(r),l=!1,f=d=>{l||(l=!0,i(d))},u=()=>{l||(l=!0,o())};a.onerror=()=>{f(a.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{u()},s.onerror=()=>{f(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{f(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},Vn=(e={})=>{let{indexedDB:t,databaseName:r=qf,objectStoreName:n=Hf,namespace:o}=e,i=Zf(t),s=Qf(o),c=ed({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let a=await td({databasePromise:c,objectStoreName:n,namespace:s});return{...ws(),...Es(a)}},clear:async()=>rd({databasePromise:c,objectStoreName:n,namespace:s}),saveSlots:async a=>Ot({databasePromise:c,objectStoreName:n,namespace:s,patch:{saveSlots:te(a)?a:{}}}),saveGlobalDeviceVariables:async a=>Ot({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:te(a)?a:{}}}),saveGlobalAccountVariables:async a=>Ot({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalAccountVariables:te(a)?a:{}}}),saveGlobalRuntime:async a=>Ot({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalRuntime:te(a)?a:{}}}),applyScopedDataUpdates:async a=>Ot({databasePromise:c,objectStoreName:n,namespace:s,patch:l=>Xf(l,a)})}},nd=Vn;var od=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),id=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),xs="conditional",jn="form",sd=new Set(["submitForm","cancelForm"]),Lt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function Fn(e){let t,r=0,n=null,o=0,i=!1,s=new Map,c=new Map,a=new Map,{handlePendingEffects:l}=e,f=(I=new Map,C=Date.now())=>new Map(Array.from(I.entries()).filter(([,R])=>C<R.expiresAt).map(([R,L])=>[R,{animation:structuredClone(L.animation),startedAt:L.startedAt,expiresAt:L.expiresAt}])),u=(I=new Map)=>Array.from(I.values()).map(C=>structuredClone(C.animation)),d=(I=Date.now())=>{s=new Map(Array.from(s.entries()).filter(([,C])=>I<C.expiresAt))},p=()=>{if(!(o>0||i)){i=!0;try{for(;t.selectPendingEffects().length>0;){let I=[...t.selectPendingEffects()];t.clearPendingEffects();try{l(I)}catch(C){throw t.clearPendingEffects(),I.forEach(R=>{t.appendPendingEffect(R)}),C}}}finally{i=!1}}},h=I=>{o+=1;try{return I()}finally{o-=1,p()}},g=({initialState:I,namespace:C})=>{t=Is(I),r=0,n=Nn(C),o=0,i=!1,s=new Map,c=new Map,a=new Map,t.appendPendingEffect({name:"handleLineActions"}),p()},y=()=>n,b=()=>t.selectPresentationState(),A=()=>t.selectPresentationChanges(),x=I=>t.selectSectionLineChanges(I),S=(I={})=>{r+=1;let C=Date.now();d(C);let R=c.size>0,L=f(s,C),z=R?f(c,C):new Map,ve={...t.selectRenderState({activePersistentAnimations:u(L),restoredPersistentAnimations:u(z)}),id:`render-${r}`};return a.set(ve.id,{builtAt:C,persistentAnimationSessions:new Map([...z.entries(),...L.entries()]),usedRestoredPersistentAnimationSessions:R}),ve},P=(I={})=>S(I),N=(I={})=>S(I),w=I=>{let C=typeof I?.id=="string"&&I.id.length>0?I.id:null,R=C?a.get(C):null;C&&a.delete(C);let L=new Map;Qo(I?.animations).forEach(z=>{let he=Zt(z);if(!he)return;let ve=R?.persistentAnimationSessions?.get(he)??s.get(he),$t=Math.max(0,ei(z)),Bn=ve?.startedAt??R?.builtAt??Date.now();L.set(he,{animation:structuredClone(z),startedAt:Bn,expiresAt:Bn+$t})}),s=L,R?.usedRestoredPersistentAnimationSessions&&(c=new Map)},M=()=>t.selectSystemState(),F=()=>t.selectSaveSlotMap(),G=I=>t.selectSaveSlot(I),j=I=>t.selectSaveSlotPage(I),H=()=>t.selectSkipMode(),K=()=>t.selectAutoMode(),X=()=>t.selectRuntime(),xe=()=>t.selectIsChoiceVisible(),re=()=>t.selectIsFormVisible(),Q=()=>t.selectActiveInteraction(),ne=()=>t.selectPendingEffects().some(I=>I?.name==="handleLineActions"||I?.name==="render"),ce=(I,C,R={})=>{if(!Lt(C)||I!=="nextLine")return C;let L=C;return R.bypassChoice===!0&&(L={...L,bypassChoice:!0}),R.interactionSource===jn&&(L={...L,_interactionSource:jn}),R.advanceConditionalNextLine===!0&&(L={...L,_advanceImmediately:!0}),L},q=(I,C)=>{if(!t[I])return;od.has(I)&&(id.has(I)?c=f(s):c=new Map,s=new Map);let R=t[I](C);return p(),R},Z=(I,C={})=>h(()=>{t.beginRollbackActionBatch({source:C.rollbackSource});try{return I()}finally{t.endRollbackActionBatch({})}}),oe=(I,C,R,L={})=>{if(I===xs)return Z(()=>{let z=_(R),he=Hr({[I]:C},z);ee(he[I],R,L)},L);q(I,C)},v=(I,C)=>{oe(I,C)},_=I=>{if(!I)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(I,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:C,...R}=I,L=t.selectAllVariables?t.selectAllVariables():void 0;return{...R,_event:C,variables:L,runtime:t.selectRuntime?t.selectRuntime():{}}},V=I=>{if(!Lt(I))throw new Error("conditional action payload must be an object");if(!Array.isArray(I.branches))throw new Error("conditional action requires branches array");if(I.branches.length===0)throw new Error("conditional action requires at least one branch")},le=(I,C,R)=>{if(!Lt(I))throw new Error(`conditional branch at index ${C} must be an object`);if(!Lt(I.actions))throw new Error(`conditional branch at index ${C} requires actions object`);if(!Object.prototype.hasOwnProperty.call(I,"when")&&C!==R-1)throw new Error("conditional else branch must be the last branch")},ee=(I,C,R)=>{V(I);for(let L=0;L<I.branches.length;L+=1){let z=I.branches[L];le(z,L,I.branches.length);let he=_(C);if(!(Object.prototype.hasOwnProperty.call(z,"when")&&!yt(z.when,he))){Ar(z.actions,C,{...R,advanceConditionalNextLine:!0});return}}},U=(I,C)=>({...I??{},_form:C}),Fe=(I,C,R,L)=>{let z=q(I,C),he=z?.submitted===!0&&z.valid===!0,ve=z?.cancelled===!0;!he&&!ve||Lt(C.actions)&&Ar(C.actions,U(R,z.form),{...L,interactionSource:jn})},tt=(I,C,R,L)=>{let z=_(R),ve=Hr({[I]:C},z)[I];if(I===xs){ee(ve,R,L);return}let $t=ce(I,ve,L);if(sd.has(I)){Fe(I,$t,R,L);return}q(I,$t)},Ar=(I,C,R)=>{Object.entries(I).forEach(([L,z])=>{tt(L,z,C,R)})},Un=(I,C,R={})=>Z(()=>Ar(I,C,R),R);return{init:g,handleAction:oe,handleInternalAction:v,handleActions:Un,selectRenderState:P,prepareRenderState:N,commitRenderState:w,selectPresentationState:b,selectPresentationChanges:A,selectSectionLineChanges:x,selectSystemState:M,selectSaveSlotMap:F,selectSaveSlot:G,selectSaveSlotPage:j,selectSaveSlots:F,selectRuntime:X,selectIsChoiceVisible:xe,selectIsFormVisible:re,selectActiveInteraction:Q,selectHasPendingRenderWork:ne,handleLineActions:()=>{let I=t.selectCurrentLine();return I?.actions?(Un(I.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:y}}var Mn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},ad=80,Cs=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{if(e.selectHasPendingRenderWork?.())return;let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},cd=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&Cs({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},ld=({engine:e,ticker:t,autoTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n.delay??1e3;r.getElapsed()>=c&&(t.remove(i),r.setCallback(null),r.setElapsed(0),Ir(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},ud=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},fd=({engine:e,ticker:t,skipTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n?.delay??ad;r.getElapsed()>=c&&(r.setElapsed(0),Ir(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},dd=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},pd=({engine:e,ticker:t,nextLineConfigTimerState:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n.delay??1e3;r.getElapsed()>=c&&(r.setElapsed(0),Ir(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},hd=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},md=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},gd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},yd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},bd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},Id=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},vs={render:Cs,saveSlots:md,saveGlobalDeviceVariables:gd,saveGlobalAccountVariables:yd,saveGlobalRuntime:bd,applyScopedDataUpdates:Id,handleLineActions:cd,startAutoNextTimer:ld,clearAutoNextTimer:ud,startSkipNextTimer:fd,clearSkipNextTimer:dd,nextLineConfigTimer:pd,clearNextLineConfigTimer:hd},Ad=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Ir=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},wd=(e=[])=>{let t=new Set,r=[];for(let n=e.length-1;n>=0;n-=1){let o=e[n];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!Ad.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},Ed=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:c})=>{let a=Mn(),l=Mn(),f=Mn(),u=s??null,d=Promise.resolve(),p=null,h=null,g=!1,y=0,b=v=>{if(o){o(v);return}console.error("RouteEngine persistence write failed.",v)},A=()=>{if(u)return u;let v=e();return u=Vn({indexedDB:i,namespace:c??v?.getNamespace?.()}),u},x=v=>{d=d.catch(()=>{}).then(()=>{let _=A();return v(_)}).catch(_=>{b(_)})},S=v=>{let _=typeof v?.id=="string"&&v.id.length>0?v.id:null;y+=1,p=_,g=!1},P=()=>y,N=(v={})=>{if(v?.aborted===!0)return!1;let _=typeof v?.id=="string"&&v.id.length>0?v.id:null;return _?_!==p||_===h?!1:(h=_,!0):p!==null||g?!1:(g=!0,!0)},w=(v,_={})=>{if(v!=="renderComplete"||!N(_))return!1;let V=e();return Ir(V,"markLineCompleted",{}),!0},M=new Set(["updateFormField","submitForm","cancelForm"]),F=new Set(["updateVariable"]),G=v=>typeof v?.selectActiveInteraction=="function"?v.selectActiveInteraction():typeof v?.selectIsChoiceVisible=="function"&&v.selectIsChoiceVisible()?{source:"choice"}:null,j=v=>v?._formKey??v?.formKey,H=(v,_)=>j(v)===_?.formKey,K=(v,_)=>!v||typeof v!="object"||Array.isArray(v)?!1:v._interactionSource===_?.source,X=(v,_)=>K(v,_)?_.source==="form"?H(v,_):!0:!1,xe=(v,_)=>!v||typeof v!="object"||Array.isArray(v)||_?.source!=="form"?!1:H(v,_),re=(v={})=>Object.keys(v).some(_=>M.has(_)),Q=(v={},_)=>Object.entries(v).some(([V,le])=>M.has(V)&&xe(le,_)),ne=(v={})=>Object.keys(v).length>0&&Object.keys(v).every(_=>F.has(_)),ce=(v={},_)=>{let V=v?.actions;return _?.source==="form"?!V||typeof V!="object"||Array.isArray(V)?!1:Q(V,_)?!0:re(V)?!1:ne(V):X(v,_)?!0:!V||typeof V!="object"||Array.isArray(V)?!1:Object.values(V).some(le=>X(le,_))},q=(v,_={})=>{if(!_?.actions)return!1;let V=G(v);return!V||V.source==="choice"?!1:!ce(_,V)},Z=({preprocessPayload:v,onEvent:_}={})=>async(V,le={})=>{let ee=e();if(q(ee,le))return _?.(V,le);let U=await v?.(V,le)??le;if(q(ee,U))return _?.(V,U);if(w(V,U),U?.actions){let Fe=U?._event?{_event:U._event}:U?.event?{_event:U.event}:void 0,tt;U?.bypassChoice===!0?tt={bypassChoice:!0}:U?._interactionSource&&(tt={interactionSource:U._interactionSource}),tt?ee.handleActions(U.actions,Fe,tt):ee.handleActions(U.actions,Fe)}return _?.(V,U)},oe=v=>{let _=e(),V=wd(v),le=V.some(U=>U.name==="handleLineActions");V.forEach(U=>{if(!vs[U.name]&&!n)throw new Error(`Unhandled pending effect "${U.name}".`)});let ee={engine:_,routeGraphics:t,ticker:r,autoTimer:a,skipTimer:l,nextLineConfigTimerState:f,trackRenderDispatch:S,getRenderDispatchCount:P,enqueuePersistenceWrite:x};for(let U of V){if(le&&U.name==="render")continue;let Fe=vs[U.name];if(Fe){Fe(ee,U.payload);continue}n(U,ee)}};return oe.handleRouteGraphicsEvent=w,oe.createRouteGraphicsEventHandler=Z,oe},xd=Ed;var vd=(e,t={})=>{let{resources:r={}}=t;return bn(e,r)};var rh=Fn;export{Jr as DEFAULT_VISUAL_LAYER,st as RENDER_LAYER,_e as VISUAL_LAYER,xd as createEffectsHandler,nd as createIndexedDbPersistence,rh as default,Da as resolveComputedVariables,vd as resolveLayoutReferences};
|
|
1
|
+
var Xs=Object.defineProperty;var Qs=(e,t)=>{for(var n in t)Xs(e,n,{get:t[n],enumerable:!0})};var io=Symbol.for("immer-nothing"),eo=Symbol.for("immer-draftable"),he=Symbol.for("immer-state");function ge(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var ot=Object.getPrototypeOf;function se(e){return!!e&&!!e[he]}function ze(e){return e?so(e)||Array.isArray(e)||!!e[eo]||!!e.constructor?.[eo]||qt(e)||Wt(e):!1}var Zs=Object.prototype.constructor.toString();function so(e){if(!e||typeof e!="object")return!1;let t=ot(e);if(t===null)return!0;let n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return n===Object?!0:typeof n=="function"&&Function.toString.call(n)===Zs}function Vn(e){return se(e)||ge(15,e),e[he].base_}function Mt(e,t){zt(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function zt(e){let t=e[he];return t?t.type_:Array.isArray(e)?1:qt(e)?2:Wt(e)?3:0}function Ln(e,t){return zt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function ao(e,t,n){let r=zt(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function ea(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function qt(e){return e instanceof Map}function Wt(e){return e instanceof Set}function Ue(e){return e.copy_||e.base_}function $n(e,t){if(qt(e))return new Map(e);if(Wt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=so(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[he];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let s=o[i],l=r[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(r[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(ot(e),r)}else{let r=ot(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function jn(e,t=!1){return Ht(e)||se(e)||!ze(e)||(zt(e)>1&&(e.set=e.add=e.clear=e.delete=ta),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>jn(r,!0))),e}function ta(){ge(2)}function Ht(e){return Object.isFrozen(e)}var na={};function qe(e){let t=na[e];return t||ge(0,e),t}var bt;function co(){return bt}function ra(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function to(e,t){t&&(qe("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Tn(e){Dn(e),e.drafts_.forEach(oa),e.drafts_=null}function Dn(e){e===bt&&(bt=e.parent_)}function no(e){return bt=ra(bt,e)}function oa(e){let t=e[he];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function ro(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[he].modified_&&(Tn(t),ge(4)),ze(e)&&(e=Bt(t,e),t.parent_||Ut(t,e)),t.patches_&&qe("Patches").generateReplacementPatches_(n[he].base_,e,t.patches_,t.inversePatches_)):e=Bt(t,n,[]),Tn(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==io?e:void 0}function Bt(e,t,n){if(Ht(t))return t;let r=t[he];if(!r)return Mt(t,(o,i)=>oo(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Ut(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let o=r.copy_,i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Mt(i,(l,a)=>oo(e,r,o,l,a,n,s)),Ut(e,o,!1),n&&e.patches_&&qe("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function oo(e,t,n,r,o,i,s){if(se(o)){let l=i&&t&&t.type_!==3&&!Ln(t.assigned_,r)?i.concat(r):void 0,a=Bt(e,o,l);if(ao(n,r,a),se(a))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(ze(o)&&!Ht(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Bt(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&Ut(e,o)}}function Ut(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&jn(t,n)}function ia(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:co(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=Fn;n&&(o=[r],i=It);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var Fn={get(e,t){if(t===he)return e;let n=Ue(e);if(!Ln(n,t))return sa(e,n,t);let r=n[t];return e.finalized_||!ze(r)?r:r===On(e.base_,t)?(kn(e),e.copy_[t]=Pn(r,e)):r},has(e,t){return t in Ue(e)},ownKeys(e){return Reflect.ownKeys(Ue(e))},set(e,t,n){let r=lo(Ue(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=On(Ue(e),t),i=o?.[he];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(ea(n,o)&&(n!==void 0||Ln(e.base_,t)))return!0;kn(e),Nn(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return On(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,kn(e),Nn(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=Ue(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ge(11)},getPrototypeOf(e){return ot(e.base_)},setPrototypeOf(){ge(12)}},It={};Mt(Fn,(e,t)=>{It[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});It.deleteProperty=function(e,t){return It.set.call(this,e,t,void 0)};It.set=function(e,t,n){return Fn.set.call(this,e[0],t,n,e[0])};function On(e,t){let n=e[he];return(n?Ue(n):e)[t]}function sa(e,t,n){let r=lo(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function lo(e,t){if(!(t in e))return;let n=ot(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=ot(n)}}function Nn(e){e.modified_||(e.modified_=!0,e.parent_&&Nn(e.parent_))}function kn(e){e.copy_||(e.copy_=$n(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var aa=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){let i=n;n=t;let s=this;return function(a=i,...c){return s.produce(a,u=>n.call(this,u,...c))}}typeof n!="function"&&ge(6),r!==void 0&&typeof r!="function"&&ge(7);let o;if(ze(t)){let i=no(this),s=Pn(t,void 0),l=!0;try{o=n(s),l=!1}finally{l?Tn(i):Dn(i)}return to(i,r),ro(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===io&&(o=void 0),this.autoFreeze_&&jn(o,!0),r){let i=[],s=[];qe("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ge(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,a=>t(a,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){ze(e)||ge(8),se(e)&&(e=We(e));let t=no(this),n=Pn(e,void 0);return n[he].isManual_=!0,Dn(t),n}finishDraft(e,t){let n=e&&e[he];(!n||!n.isManual_)&&ge(9);let{scope_:r}=n;return to(r,t),ro(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){let o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));let r=qe("Patches").applyPatches_;return se(e)?r(e,t):this.produce(e,o=>r(o,t))}};function Pn(e,t){let n=qt(e)?qe("MapSet").proxyMap_(e,t):Wt(e)?qe("MapSet").proxySet_(e,t):ia(e,t);return(t?t.scope_:co()).drafts_.push(n),n}function We(e){return se(e)||ge(10,e),uo(e)}function uo(e){if(!ze(e)||Ht(e))return e;let t=e[he],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=$n(e,t.scope_.immer_.useStrictShallowCopy_)}else n=$n(e,!0);return Mt(n,(r,o)=>{ao(n,r,uo(o))}),t&&(t.finalized_=!1),n}var me=new aa,Mn=me.produce,up=me.produceWithPatches.bind(me),dp=me.setAutoFreeze.bind(me),fp=me.setUseStrictShallowCopy.bind(me),pp=me.applyPatches.bind(me),hp=me.createDraft.bind(me),mp=me.finishDraft.bind(me);var m={LITERAL:0,VARIABLE:1,INTERPOLATION:2,FUNCTION:3,BINARY:4,UNARY:5,CONDITIONAL:6,LOOP:7,OBJECT:8,ARRAY:9,PARTIAL:10,PATH_REFERENCE:11},k={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},it={NOT:0};var v=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},pe=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Bn=e=>{if(!e||e.trim()==="")throw new v("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new v(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${n}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let n of t)if(e.trim().endsWith(n))throw new v(`Incomplete comparison expression - missing right operand (got: '${e}')`)},fo=e=>{if(e.trim().endsWith(" in"))throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new v(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);let r=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of r){if(!o)throw new v(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new v(`Invalid loop syntax (got: '$for ${e}')`)}};var po=(e,t,n=!1)=>{if(t===null)return new pe(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new pe(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new pe(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new pe(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},ho=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new pe(`Unknown function '${e}' (${n})`)};var ca=(e,t,n={})=>{let r={},o={};n&&typeof n=="object"&&(n.functions!==void 0||n.partials!==void 0?(r=n.functions||{},o=n.partials||{}):typeof n=="object"&&(r=n));let s=L(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},L=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return K(e.var,n,r);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return K(e.path,n,r);if(e.type===m.INTERPOLATION)return ua(e.parts,t,n,r);switch(e.type){case m.FUNCTION:return go(e,t,n,r);case m.BINARY:return yo(e,t,n,r);case m.UNARY:return bo(e,t,n,r);case m.CONDITIONAL:return fa(e,t,n,r);case m.LOOP:return ya(e,t,n,r);case m.OBJECT:return Ia(e,t,n,r);case m.ARRAY:return Aa(e,t,n,r);case m.PARTIAL:return wa(e,t,n,r);case m.PATH_REFERENCE:return Ea(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},mo=new Map,la=e=>{let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(i==="]"){if(r&&n){let s=n.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let l=s.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:s});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},K=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=mo.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=la(a.trim());r.push(...c)}mo.set(e,r)}let o=t;for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="property"&&s.value in n){o=n[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},ua=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},go=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw ho(e.name,o);let s=e.args.map(l=>L(l,t,n,r));return i(...s)},Le=(e,t,n,r)=>{if(e.var&&!e.type)return K(e.var,n,r);switch(e.type){case m.VARIABLE:return K(e.path,n,r);case m.LITERAL:return e.value;case m.BINARY:return yo(e,t,n,r);case m.UNARY:return bo(e,t,n,r);case m.FUNCTION:return go(e,t,n,r);default:return L(e,t,n,r)}},yo=(e,t,n,r)=>{if(e.op===k.AND||e.op===k.OR){let s=Le(e.left,t,n,r),l=Le(e.right,t,n,r);switch(e.op){case k.AND:return s&&l;case k.OR:return s||l}}let o=L(e.left,t,n,r),i=L(e.right,t,n,r);switch(e.op){case k.EQ:return o==i;case k.NEQ:return o!=i;case k.GT:return o>i;case k.LT:return o<i;case k.GTE:return o>=i;case k.LTE:return o<=i;case k.IN:return Array.isArray(i)?i.includes(o):!1;case k.ADD:if(typeof o!="number"||typeof i!="number")throw new pe(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case k.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new pe(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},bo=(e,t,n,r)=>{let o=e.op===it.NOT?Le(e.operand,t,n,r):L(e.operand,t,n,r);if(e.op===it.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},da=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(K(o.path,n,r)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?L(a.parsedKey,t,n,r):a.key,u=a.value;if(u.type===m.LITERAL)l[c]=u.value;else if(u.type===m.VARIABLE)l[c]=K(u.path,n,r);else if(u.type===m.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===m.VARIABLE){let p=K(f.path,n,r);d.push(p!=null?String(p):"")}else{let p=L(f,t,n,r);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=L(u,t,n,r)}return l}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?L(a.parsedKey,t,n,r):a.key,u=a.value;if(u.type===m.LITERAL)l[c]=u.value;else if(u.type===m.VARIABLE)l[c]=K(u.path,n,r);else if(u.type===m.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===m.VARIABLE){let p=K(f.path,n,r);d.push(p!=null?String(p):"")}else{let p=L(f,t,n,r);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=L(u,t,n,r)}return l}}}return null},fa=(e,t,n,r)=>{let o=da(e,t,n,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||Le(s,t,n,r))return L(e.bodies[i],t,n,r)}return Io},pa=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===m.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===m.VARIABLE){let o=n.conditions[0].path,i=n.bodies[0];if(o.startsWith(r+".")){let s=o.substring(r.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let a of i.properties)if(a.parsedKey)return null;let l=[];for(let a=0;a<t.length;a++){let c=t[a];if(c[s]){let u={};for(let d of i.properties){let f=d.key,p=d.value;if(p.type===m.LITERAL)u[f]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===r)u[f]=c;else if(h.startsWith(r+".")){let g=h.substring(r.length+1);u[f]=c[g]}else return null}else if(p.type===m.INTERPOLATION){let h=[],g=!0;for(let b of p.parts)if(typeof b=="string")h.push(b);else if(b.type===m.VARIABLE){let A=b.path;if(A===r)h.push(c!=null?String(c):"");else if(A.startsWith(r+".")){let w=A.substring(r.length+1),C=c[w];h.push(C!=null?String(C):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[f]=h.join("")}else return null}l.push(u)}}return l}}}return null},ha=(e,t)=>{let n=e.body,r=e.itemVar,o=pa(e,t);if(o!==null)return o;if(n.type===m.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let l of n.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of n.properties){let a=l.key,c=l.value;if(c.type===m.LITERAL)i.push({key:a,type:"literal",value:c.value});else if(c.type===m.VARIABLE){let u=c.path;if(u===r)i.push({key:a,type:"item"});else if(u.startsWith(r+".")){let d=u.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:a,type:"prop",prop:d});else{s=!1;break}}else{s=!1;break}}else if(c.type===m.INTERPOLATION&&c.parts.length===1){let u=c.parts[0];if(u.type===m.VARIABLE){let d=u.path;if(d===r)i.push({key:a,type:"item_string"});else if(d.startsWith(r+".")){let f=d.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:a,type:"prop_string",prop:f});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let l=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let a=0;a<t.length;a++){let c=t[a];l[a]={id:c.id,title:c.title!=null?String(c.title):"",completed:c.completed}}else for(let a=0;a<t.length;a++){let c=t[a],u={};for(let d of i)if(d.type==="literal")u[d.key]=d.value;else if(d.type==="item")u[d.key]=c;else if(d.type==="prop")u[d.key]=c[d.prop];else if(d.type==="item_string")u[d.key]=c!=null?String(c):"";else if(d.type==="prop_string"){let f=c[d.prop];u[d.key]=f!=null?String(f):""}l[a]=u}return l}}return null},ma=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let l=e.itemVar,a=e.indexVar;for(let c=0;c<o.length;c++){let u=o[c],d={},f={...r,[l]:u,...a&&{[a]:c}};f.__paths__||(f.__paths__=r.__paths__||{});let p=e.iterable.path||"";if(r&&r.__paths__&&p){let h=p.split("."),g=h[0];g in r.__paths__&&(p=r.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}f.__paths__={...f.__paths__,[l]:`${p}[${c}]`,...a&&{[a]:c}};for(let h of s.properties){let g=h.parsedKey?L(h.parsedKey,t,n,f):h.key,b=h.value;if(b.type===m.LITERAL)d[g]=b.value;else if(b.type===m.VARIABLE){let A=b.path;if(A===l)d[g]=u;else if(A===a)d[g]=c;else if(A.startsWith(l+".")){let w=A.substring(l.length+1);!w.includes(".")&&!w.includes("[")?d[g]=u[w]:d[g]=K(A,n,{...r,[l]:u,...a&&{[a]:c}})}else d[g]=K(A,n,{...r,[l]:u,...a&&{[a]:c}})}else if(b.type===m.INTERPOLATION){let A=[];for(let w of b.parts)if(typeof w=="string")A.push(w);else if(w.type===m.VARIABLE){let C=w.path,R;if(C===l)R=u;else if(C===a)R=c;else if(C.startsWith(l+".")){let P=C.substring(l.length+1);!P.includes(".")&&!P.includes("[")?R=u[P]:R=K(C,n,{...r,[l]:u,...a&&{[a]:c}})}else R=K(C,n,{...r,[l]:u,...a&&{[a]:c}});A.push(R!=null?String(R):"")}else{let C={...r,[l]:u,...a&&{[a]:c}},R=L(w,t,n,C);A.push(R!=null?String(R):"")}d[g]=A.join("")}else{let A={...r,[l]:u,...a&&{[a]:c}};d[g]=L(b,t,n,A)}}i.push(d)}return i}return null},ga=(e,t,n)=>{let r=e.body;if(r.type===m.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===m.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===m.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===m.OBJECT&&s.properties.length===2){let l=s.properties[0],a=s.properties[1];if(l.key==="id"&&l.value.type===m.VARIABLE&&l.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===m.CONDITIONAL){let c=[];for(let u=0;u<t.length;u++){let d=t[u];if(d.visible){let f={id:d.id};d.highlighted?(f.highlight=!0,f.message=`This item is highlighted: ${d.name}`):(f.highlight=!1,f.message=d.name),c.push(f)}}return c}}}}return null},ya=(e,t,n,r)=>{let o=L(e.iterable,t,n,r);if(!Array.isArray(o)){let c,u=!1;if(e.iterable.type===m.FUNCTION){u=!0;let f=e.iterable.args.map(p=>p.type===m.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===m.VARIABLE?p.path:p.type===m.FUNCTION?`${p.name}(...)`:"?").join(", ");c=`${e.iterable.name}(${f})`}else c=e.iterable.path||"undefined";let d=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${c}`;throw po(d,o,u)}if(!e.indexVar){let c=ga(e,o,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=ha(e,o);if(c!==null)return c}let i=ma(e,t,n,r,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(r&&r.__paths__&&l){let c=l.split("."),u=c[0];u in r.__paths__&&(l=r.__paths__[u],c.length>1&&(l+="."+c.slice(1).join(".")))}let a=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(c=>c.type===m.OBJECT&&c.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let c=0;c<o.length;c++){let u=e.indexVar?{...r,[e.itemVar]:o[c],[e.indexVar]:c}:{...r,[e.itemVar]:o[c]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${c}]`},e.indexVar&&(u.__paths__[e.indexVar]=c);let d=L(e.body,t,n,u);if(Array.isArray(d)&&d.length===1&&!a){let f=d[0];s.push(f===void 0?{}:f)}else s.push(d===void 0?{}:d)}return s},ba=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let l={},a={},c=!0;for(let u of s.properties){let d=u.parsedKey?L(u.parsedKey,t,n,r):u.key,f=u.value;if(f.type===m.LITERAL)a[d]=f.value;else if(f.type===m.VARIABLE)a[d]=K(f.path,n,r);else if(f.type===m.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=K(h.path,n,r);p.push(g!=null?String(g):"")}else{c=!1;break}if(!c)break;a[d]=p.join("")}else if(f.type===m.OBJECT&&f.properties.length<=5){let p={};for(let h of f.properties){let g=h.key,b=h.value;if(b.type===m.LITERAL)p[g]=b.value;else if(b.type===m.VARIABLE)p[g]=K(b.path,n,r);else if(b.type===m.INTERPOLATION){let A=[];for(let w of b.parts)if(typeof w=="string")A.push(w);else if(w.type===m.VARIABLE){let C=K(w.path,n,r);A.push(C!=null?String(C):"")}else{c=!1;break}if(!c)break;p[g]=A.join("")}else{c=!1;break}}if(!c)break;a[d]=p}else{c=!1;break}}if(c)return l[i]=a,l}}return null},Ia=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!Le(e.whenCondition,o,n,r))return;let i=ba(e,t,n,r);if(i!==null)return i;if(e.fast){let c={};for(let u of e.properties){let d=u.parsedKey?L(u.parsedKey,t,n,r):u.key,f=u.value;if(f.type===m.LITERAL)c[d]=f.value;else if(f.type===m.VARIABLE)c[d]=K(f.path,n,r);else if(f.type===m.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=K(h.path,n,r);p.push(g!=null?String(g):"")}else{let g=L(h,t,n,r);p.push(g!=null?String(g):"")}c[d]=p.join("")}else c[d]=L(f,t,n,r)}return c}let s={},l=null,a=!1;for(let c of e.properties)if(!c.key.startsWith("$if ")&&!c.key.match(/^\$if\s+\w+.*:?$/)&&!c.key.startsWith("$elif")&&!c.key.startsWith("$else")&&!c.key.startsWith("$for ")){a=!0;break}for(let c of e.properties)if(c.key.startsWith("$if ")||c.key.match(/^\$if\s+\w+.*:?$/)){let u=L(c.value,t,n,r);if(!a&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(c.key.startsWith("$for ")){if(e.properties.length===1)return L(c.value,t,n,r)}else{let u=c.value;if(u&&u.type===m.OBJECT&&u.properties){let d=u.properties.find(f=>f.key.startsWith("$for "));if(d){let f=L(d.value,t,n,r);f!==void 0&&(s[c.key]=f)}else{let f=L(c.value,t,n,r);f!==void 0&&(s[c.key]=f)}}else{let d=c.parsedKey?L(c.parsedKey,t,n,r):c.key,f=L(c.value,t,n,r);f!==void 0&&(s[d]=f)}}return s},Io={},Aa=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=L(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,n,r);s!==Io&&s!==void 0&&o.push(s)}return o},wa=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},a=t.functions||t;if(s&&!Le(s,a,n,r))return;if(!l[o])throw new pe(`Partial '${o}' is not defined`);let c=r._partialStack||[];if(c.includes(o))throw new pe(`Circular partial reference detected: ${o}`);let u=l[o],d=n,f={...r,_partialStack:[...c,o]};if(r){d={...n};for(let p of Object.keys(r))p.startsWith("_")||(d[p]=r[p])}if(i){let p=L(i,t,n,r);d={...d,...p}}return L(u,t,d,f)},Ea=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),s=i[0],l=i.slice(1);if(!r||!(s in r))throw new pe(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(s in r.__paths__))throw new pe(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=r.__paths__[s];if(typeof a=="number"){if(l.length>0)throw new pe(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return l.length>0&&(a+="."+l.join(".")),a};var Un=ca;var xa=/\$\{([^}]*)\}/g,va=/#\{([^}]*)\}/g,wo=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=Ca(o,t);return{isFunction:!0,type:m.FUNCTION,name:r,args:i}},Ca=(e,t={})=>e.trim()?Sa(e).map(r=>_a(r.trim(),t)):[],Sa=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],a=s>0?e[s-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,n+=l):o&&l===i&&a!=="\\"?(o=!1,i="",n+=l):!o&&l==="("?(r++,n+=l):!o&&l===")"?(r--,n+=l):!o&&l===","&&r===0?(t.push(n),n=""):n+=l}return n&&t.push(n),t},_a=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:m.LITERAL,value:parseFloat(e)};if(e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};let n=wo(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:l,type:a}of o){let c=0;for(;c<r.length;){let u=He(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 Q(r,t)}catch{return{type:m.VARIABLE,path:r}}return{type:m.VARIABLE,path:r}},Eo=/^\w+\(.*\)$/,Ra=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Oa=e=>{if(!(!e||e.trim()===""||Eo.test(e))&&Ra.test(e))throw e.includes("?")&&e.includes(":")?new v(`Complex expressions not supported in variable replacements - consider calculating the value in your data instead. Offending expression: "${e}"`):e.includes("||")||e.includes("&&")||e.includes("??")?new v(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new v(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Ao=e=>{let t=e.trim();if(Eo.test(t))throw new v(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new v(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new v(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new v(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("?")&&t.includes(":"))throw new v(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:m.PATH_REFERENCE,path:t}},At=(e,t={})=>{let n=e.trim();Oa(n);let r=wo(n,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};if(n.includes("[")&&!/[\s+\-*/%|&?:]/.test(n)){let o=0;for(let i of n)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:n}},zn=(e,t={})=>{let n=e,r=[];(e.includes("\\${")||e.includes("\\#{"))&&(n=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),n=n.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),n=n.replace(/\\(\$\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${r.length}__`;return r.push(u),d}),n=n.replace(/\\(#\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${r.length}__`;return r.push(u),d}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...n.matchAll(xa)],i=[...n.matchAll(va)],s=[...o.map(c=>({match:c,type:"variable"})),...i.map(c=>({match:c,type:"pathref"}))].sort((c,u)=>c.match.index-u.match.index);if(s.length===0){let c=n;for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);return{type:m.LITERAL,value:c}}if(s.length===1&&s[0].match[0]===n&&r.length===0){let{match:c,type:u}=s[0];try{return u==="variable"?At(c[1],t):Ao(c[1])}catch(d){if(d.message==="Invalid array index syntax")return{type:m.LITERAL,value:n};throw d}}let l=[],a=0;for(let{match:c,type:u}of s){let[d,f]=c,p=c.index;if(p>a){let h=n.substring(a,p);for(let g=0;g<r.length;g++)h=h.replace(`__ESCAPED_${g}__`,r[g]);h&&l.push(h)}try{let h;u==="variable"?h=At(f.trim(),t):h=Ao(f.trim()),l.push(h)}catch(h){if(h.message==="Invalid array index syntax")l.push(d);else throw h}a=p+d.length}if(a<n.length){let c=n.substring(a);for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);c&&l.push(c)}return{type:m.INTERPOLATION,parts:l}};var Hn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Co=e=>Object.keys(e),ae=e=>e.join("."),$e=(e,t,n)=>{let r=Co(e).filter(o=>!t.has(o));if(r.length>0)throw new v(`Unexpected key '${r[0]}' in condition JSON at '${ae(n)}'`)},Te=(e,t)=>typeof e=="string"?zn(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?La(e,t):$a(e,t):{type:m.LITERAL,value:e},ka=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new v("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new v("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new v("Empty $each body not allowed");if(n.$partial!==void 0)throw new v("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},La=(e,t)=>{let n=[],r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let a=ka(i),c=Object.keys(a);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let u=vo(c[0],a[c[0]],t,!0);n.push(u),r=!0;continue}}catch(a){throw a instanceof v?a:new v(a.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let a=vo(l[0],i[l[0]],t);n.push(a),r=!0;continue}}let s=Te(i,t);n.push(s),(s.type===m.FUNCTION||s.type===m.CONDITIONAL||s.type===m.LOOP||s.type===m.PARTIAL||s.type===m.OBJECT&&!s.fast||s.type===m.ARRAY&&!s.fast)&&(r=!0)}return{type:m.ARRAY,items:n,fast:!r}},$a=(e,t)=>{let n=[],r=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new v("$partial value must be a string");if(e.$partial.trim()==="")throw new v("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],c=[];for(let[A]of i)for(let w of a)if(A===w||A.startsWith(w+" ")||A.startsWith(w+"#")){c.push(w);break}if(c.length>0)throw new v(`Cannot use $partial with ${c.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:d,...f}=e,p={},h=!1;for(let[A,w]of Object.entries(f)){let C=A;(A.startsWith("\\$")||A.startsWith("$$"))&&(C=A.slice(1)),p[C]=w,h=!0}let g=null;if(h&&(g=Te(p,t),g.type===m.OBJECT)){let A=!1;for(let w of g.properties)if(w.value.type===m.VARIABLE||w.value.type===m.INTERPOLATION||w.value.type===m.FUNCTION||w.value.type===m.CONDITIONAL||w.value.type===m.OBJECT&&!w.value.fast||w.value.type===m.ARRAY&&!w.value.fast){A=!0;break}A&&(g.fast=!1)}let b={type:m.PARTIAL,name:u,data:g};return d!==void 0&&(b.whenCondition=xo(d,t)),b}for(let[a,c]of i)if(a==="$when"){if(o!==null)throw new v("Multiple '$when' directives on the same object are not allowed");if(c==null)throw new v("Missing condition expression after '$when'");o=xo(c,t),r=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new v("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[a,c]=i[s];if(a==="$when"){s++;continue}if(a==="$each")throw new v("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let u=Ta(i,s,t);n.push({key:a,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let u=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",d=u?`:${u}`:"";throw new v(`$for loops must be inside arrays - use '- $for${d} item in items:' instead of '$for${d} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(a.startsWith("$elif ")||a.startsWith("$else"))throw new v(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new v("Missing condition expression after '$if'");{let u=Te(c,t);(u.type===m.FUNCTION||u.type===m.CONDITIONAL||u.type===m.PARTIAL||u.type===m.OBJECT&&!u.fast||u.type===m.ARRAY&&!u.fast)&&(r=!0);let d=zn(a,t),f={key:a,value:u};(d.type!==m.LITERAL||d.value!==a)&&(f.parsedKey=d),n.push(f),s++}}}let l={type:m.OBJECT,properties:n,fast:!r};return o&&(l.whenCondition=o),l},Ta=(e,t,n={})=>{let r=[],o=[],i=t,[s,l]=e[i],a=null,c;if(s.startsWith("$if#")){let d=s.match(/^\$if#(\w+)\s+(.+)$/);if(d)a=d[1],c=d[2];else throw new v(`Invalid conditional syntax: ${s}`)}else c=s.substring(4),c.endsWith(":")&&(c=c.slice(0,-1).trim());Bn(c);let u=Q(c,n);for(r.push(u),o.push(Te(l,n)),i++;i<e.length;){let[d,f]=e[i],p=!1,h;if(a?d.startsWith(`$elif#${a} `)?(h=d.substring(`$elif#${a} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(d===`$else#${a}`||d===`$else#${a}:`)&&(p=!0,h=null):d.startsWith("$elif ")?(h=d.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(d==="$else"||d==="$else:")&&(p=!0,h=null),p){if(h===null)r.push(null);else{Bn(h);let g=Q(h,n);r.push(g)}if(o.push(Te(f,n)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:r,bodies:o,id:a},nextIndex:i}},qn={eq:k.EQ,neq:k.NEQ,gt:k.GT,gte:k.GTE,lt:k.LT,lte:k.LTE,in:k.IN,add:k.ADD,sub:k.SUBTRACT},Wn={all:k.AND,any:k.OR},Da=new Set(["var","literal","call","not",...Object.keys(qn),...Object.keys(Wn)]),Na=(e,t,n)=>{if(!Array.isArray(e))throw new v(`Condition JSON operator '${t}' at '${ae(n)}' requires an array`);if(e.length!==2)throw new v(`Condition JSON operator '${t}' at '${ae(n)}' requires exactly 2 operands`);return e},Pa=(e,t,n,r,o)=>{if(!Array.isArray(e))throw new v(`Condition JSON operator '${t}' at '${ae(o)}' requires an array`);if(e.length===0)throw new v(`Condition JSON operator '${t}' at '${ae(o)}' requires at least 1 condition`);return e.map((s,l)=>ve(s,r,[...o,l])).reduce((s,l)=>({type:m.BINARY,op:n,left:s,right:l}))},Va=(e,t,n)=>{let r,o;if(typeof e.call=="string")r=e.call,o=e.args??[],$e(e,new Set(["call","args"]),n);else if(Hn(e.call))r=e.call.name,o=e.call.args??[],$e(e,new Set(["call"]),n),$e(e.call,new Set(["name","args"]),[...n,"call"]);else throw new v(`Condition JSON call at '${ae(n)}' requires a function name`);if(typeof r!="string"||r.trim()==="")throw new v(`Condition JSON call at '${ae(n)}' requires a non-empty function name`);if(!/^\w+$/.test(r))throw new v(`Invalid condition JSON function name '${r}' at '${ae(n)}'`);if(!Array.isArray(o))throw new v(`Condition JSON call '${r}' at '${ae(n)}' requires args to be an array`);return{type:m.FUNCTION,name:r,args:o.map((i,s)=>ve(i,t,[...n,"args",s]))}},ve=(e,t={},n=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:m.LITERAL,value:e};if(Array.isArray(e))throw new v(`Condition JSON array at '${ae(n)}' must be wrapped in an operator or { literal: [...] }`);if(!Hn(e))throw new v(`Invalid condition JSON value at '${ae(n)}'`);let r=Co(e);if(r.length===0)throw new v(`Condition JSON object at '${ae(n)}' must contain an operator`);let o=r.filter(s=>Da.has(s));if(o.length===0)throw new v(`Unknown condition JSON operator '${r[0]}' at '${ae(n)}'`);if(o.length>1)throw new v(`Condition JSON at '${ae(n)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if($e(e,new Set(["var"]),n),typeof e.var!="string"||e.var.trim()==="")throw new v(`Condition JSON var at '${ae(n)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return $e(e,new Set(["literal"]),n),{type:m.LITERAL,value:e.literal};if(i==="call")return Va(e,t,n);if(i==="not")return $e(e,new Set(["not"]),n),{type:m.UNARY,op:it.NOT,operand:ve(e.not,t,[...n,"not"])};if(i in Wn)return $e(e,new Set([i]),n),Pa(e[i],i,Wn[i],t,[...n,i]);if(i in qn){$e(e,new Set([i]),n);let s=Na(e[i],i,[...n,i]);return{type:m.BINARY,op:qn[i],left:ve(s[0],t,[...n,i,0]),right:ve(s[1],t,[...n,i,1])}}throw new v(`Unknown condition JSON operator '${i}' at '${ae(n)}'`)},xo=(e,t={})=>{if(e==null)throw new v("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new v("Empty condition expression after '$when'");return Q(e,t)}return Hn(e)||Array.isArray(e)?ve(e,t):{type:m.LITERAL,value:e}},Q=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let c=e.slice(1,-1),u=0,d=!0;for(let f=0;f<c.length;f++)if(c[f]==="("?u++:c[f]===")"&&u--,u<0){d=!1;break}if(d&&u===0)return Q(c,t)}let n=He(e,"||");if(n!==-1)return{type:m.BINARY,op:k.OR,left:Q(e.substring(0,n).trim(),t),right:Q(e.substring(n+2).trim(),t)};let r=He(e,"&&");if(r!==-1)return{type:m.BINARY,op:k.AND,left:Q(e.substring(0,r).trim(),t),right:Q(e.substring(r+2).trim(),t)};let o=[{op:">=",type:k.GTE},{op:"<=",type:k.LTE},{op:"==",type:k.EQ},{op:"!=",type:k.NEQ},{op:">",type:k.GT},{op:"<",type:k.LT},{op:" in ",type:k.IN}];for(let{op:c,type:u}of o){let d=He(e,c);if(d!==-1)return{type:m.BINARY,op:u,left:Q(e.substring(0,d).trim(),t),right:Q(e.substring(d+c.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:k.ADD},{op:" - ",type:k.SUBTRACT}];for(let{op:c,type:u}of l){let d=0;for(;d<e.length;){let f=He(e.substring(d),c);if(f===-1)break;let p=d+f;p>i&&(i=p,s={op:c,type:u}),d=p+c.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:Q(e.substring(0,i).trim(),t),right:Q(e.substring(i+s.op.length).trim(),t)};let a=[" * "," / "," % "];for(let c of a)if(He(e,c)!==-1)throw new v(`Arithmetic operations are not allowed in conditionals: "${c}"`);return e.startsWith("!")?{type:m.UNARY,op:it.NOT,operand:Q(e.substring(1).trim(),t)}:So(e,t)},He=(e,t)=>{let n=0,r=0;for(;r<=e.length-t.length;){if(e[r]==="(")n++;else if(e[r]===")")n--;else if(n===0&&e.substring(r,r+t.length)===t)return r;r++}return-1},ja=e=>{if(e=e.trim(),e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:m.LITERAL,value:""};if(e==="{}")return{type:m.LITERAL,value:{}};if(e==="[]")return{type:m.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:m.LITERAL,value:t}:{type:m.VARIABLE,path:e}},So=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return At(n,t);let o=ja(n);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:m.VARIABLE,path:n};try{return At(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Fa=(e,t=!1)=>{let n=t?"$each":"$for";try{fo(e)}catch(r){if(r instanceof v&&t){let o=r.message.replace(/\$for/g,"$each");throw new v(o.replace("Parse Error: ",""))}throw r}},vo=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let b=r?"$each":"$for";throw new v(`Invalid loop syntax (got: '${e.replace("$for",b)}')`)}let s=i[1],l=i[2].trim();Fa(l,r);let a=l.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let b=r?"$each":"$for";throw new v(`Invalid loop syntax - missing 'in' keyword (got: '${b} ${l}')`)}let c=a[1].trim(),u=a[2].trim(),d,f=null;if(c.includes(",")){let b=c.split(",").map(A=>A.trim());if(b.length!==2)throw new v(`Invalid loop variables: ${c}. Expected format: "item" or "item, index"`);d=b[0],f=b[1]}else d=c;let p=["this","undefined","null","true","false"];if(p.includes(d))throw new v(`Reserved variable name: ${d}`);if(f&&p.includes(f))throw new v(`Reserved variable name: ${f}`);let h=So(u,n),g=Te(t,n);return{type:m.LOOP,itemVar:d,indexVar:f,iterable:h,body:g,flatten:s!=="nested"}};var Ma=(e,t={})=>{let{functions:n={}}=t;return Te(e,n)},Yt=Ma;var wt={};Qs(wt,{now:()=>Ba});var Ba=()=>Date.now();var Ua=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...wt,...r},s=Yt(e,{functions:i}),l={};for(let[a,c]of Object.entries(o))l[a]=Yt(c,{functions:i});return Un(s,t,{functions:i,partials:l})},ce=Ua;var za=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",qa=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Wa=(e,t)=>{if(za(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new v("Empty condition expression");return Q(e,t)}return ve(e,t)},Ha=(e,t={},n={})=>{let r=qa(n),o={...wt,...r},i=Wa(e,o);return!!Le(i,{functions:o,partials:{}},t,{})},Yn=Ha;var xt=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return Yn(e,t)},$o=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=a=>a,transformActionFirstArgument:l=a=>a}=n;for(let[a,c]of Object.entries(t))a!=="createInitialState"&&(a.startsWith("select")?o[a]=(...u)=>c(s(r),...u):i[a]=(...u)=>{let d;return r=Mn(r,p=>{let h=c(l(p),...u);d=h!==void 0&&!se(h)?h:void 0}),d});return{...o,...i}},Jt=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return Mn(r,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var Ya=(e,t)=>{if(e.default!==void 0)return e.default;let n=["number","boolean","string","object"];if(!n.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${n.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},be=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),Et=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),To=e=>{let t=se(e)?We(e):e;return structuredClone(t)},Ga=({characterId:e,resourceCharacter:t,variables:n={}}={})=>{if(!be(t,"nameVariableId"))return;let r=t.nameVariableId,o=n?.[r];if(typeof o!="string")throw new Error(`Character "${e}" nameVariableId "${r}" must resolve to a string variable`);return o},Xt=({characterId:e,character:t,characterName:n,characters:r={},variables:o={}}={})=>{let i=e?r?.[e]:void 0;if(t?.name!==void 0)return t.name;if(n!==void 0)return n;let s=Ga({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},De=e=>be(e,"computed"),st=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([n])=>!De(t[n]))),Ka=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),Gn=(e,t)=>{let n=e;for(let r of t){if(n==null)return;n=n[r]}return n},Ja=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let n=Ka(e),[r,o,...i]=n;if(r==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return Gn(s,i)}return r==="runtime"?Gn(t.runtime,n.slice(1)):Gn(t,n)},Xa=(e,t,n)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(n!==void 0&&t.length!==n)throw new Error(`Computed expression operator "${e}" requires ${n} operand(s)`)},_o=(e,t)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(t.length===0)throw new Error(`Computed expression operator "${e}" requires at least one operand`)},Qa=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},we=(e,t,n,r)=>(Xa(e,t,r),t.map(o=>Kt(o,n))),ye=(e,t,n,r)=>{let o=we(e,t,n,r);return o.forEach(i=>Qa(e,i)),o},Za=(e,t,n)=>{switch(e){case"var":return Ja(t,n);case"add":{let[r,o]=ye(e,t,n,2);return r+o}case"sub":{let[r,o]=ye(e,t,n,2);return r-o}case"mul":{let[r,o]=ye(e,t,n,2);return r*o}case"div":{let[r,o]=ye(e,t,n,2);return r/o}case"mod":{let[r,o]=ye(e,t,n,2);return r%o}case"neg":{let[r]=ye(e,t,n,1);return-r}case"round":{let[r]=ye(e,t,n,1);return Math.round(r)}case"floor":{let[r]=ye(e,t,n,1);return Math.floor(r)}case"ceil":{let[r]=ye(e,t,n,1);return Math.ceil(r)}case"min":{let[r,o]=ye(e,t,n,2);return Math.min(r,o)}case"max":{let[r,o]=ye(e,t,n,2);return Math.max(r,o)}case"clamp":{let[r,o,i]=ye(e,t,n,3);return Math.min(i,Math.max(o,r))}case"eq":{let[r,o]=we(e,t,n,2);return r==o}case"neq":{let[r,o]=we(e,t,n,2);return r!=o}case"gt":{let[r,o]=we(e,t,n,2);return r>o}case"gte":{let[r,o]=we(e,t,n,2);return r>=o}case"lt":{let[r,o]=we(e,t,n,2);return r<o}case"lte":{let[r,o]=we(e,t,n,2);return r<=o}case"in":{let[r,o]=we(e,t,n,2);return Array.isArray(o)?o.includes(r):!1}case"and":case"all":return _o(e,t),t.every(r=>!!Kt(r,n));case"or":case"any":return _o(e,t),t.some(r=>!!Kt(r,n));case"not":{let[r]=we(e,t,n,1);return!r}case"length":{let[r]=we(e,t,n,1);return typeof r=="string"||Array.isArray(r)?r.length:Et(r)?Object.keys(r).length:0}case"includes":{let[r,o]=we(e,t,n,2);return typeof r=="string"||Array.isArray(r)?r.includes(o):!1}case"literal":return To(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},Kt=(e,t={})=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let n=Object.entries(e);if(n.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[r,o]]=n;return Za(r,o,t)},ec=(e,t={})=>xt(e,{variables:t.variables,runtime:t.runtime}),tc=(e,t)=>{if(!Et(e))throw new Error(`${t} must be an object`);let n=be(e,"expr"),r=be(e,"value");if(n===r)throw new Error(`${t} must contain exactly one of expr or value`)},Kn=(e,t,n)=>(tc(e,t),be(e,"value")?To(e.value):Kt(e.expr,n)),nc=(e,t={},n="unknown")=>{if(!Et(e))throw new Error(`Computed variable "${n}" computed must be an object`);let r=be(e,"expr"),o=be(e,"value");if(be(e,"branches")){if(r||o)throw new Error(`Computed variable "${n}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${n}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${n}" branches must not be empty`);if(!Et(e.default))throw new Error(`Computed variable "${n}" requires default`);for(let s=0;s<e.branches.length;s+=1){let l=e.branches[s];if(!Et(l))throw new Error(`Computed variable "${n}" branch ${s} must be an object`);if(!be(l,"when"))throw new Error(`Computed variable "${n}" branch ${s} requires when`);if(ec(l.when,t))return Kn(l,`Computed variable "${n}" branch ${s}`,t)}return Kn(e.default,`Computed variable "${n}" default`,t)}if(r===o)throw new Error(`Computed variable "${n}" must contain exactly one of expr, value, or branches`);return Kn(e,`Computed variable "${n}"`,t)},rc=(e,t,n)=>{switch(t){case"number":if(typeof n!="number"||!Number.isFinite(n))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(n)?"array":typeof n}`);return;case"boolean":if(typeof n!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(n)?"array":typeof n}`);return;case"string":if(typeof n!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(n)?"array":typeof n}`);return;case"object":if(n===null||typeof n!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof n}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},vt=({variables:e={},runtime:t={},variableConfigs:n={},eager:r=!0}={})=>{let o=st(e,n),i=Object.entries(n).filter(([,d])=>De(d)).map(([d])=>d),s={},l=[],a=d=>{if(be(s,d))return s[d];let f=n[d];if(!De(f))return o[d];let p=l.indexOf(d);if(p>=0){let h=[...l.slice(p),d].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}l.push(d);try{let h=nc(f.computed,u,d);return rc(d,f.type,h),s[d]=h,h}finally{l.pop()}},c=new Proxy({},{get:(d,f)=>{if(typeof f=="string")return a(f)},has:(d,f)=>typeof f=="string"&&(be(o,f)||i.includes(f)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(d,f)=>{if(!(typeof f!="string"||!be(o,f)&&!i.includes(f)))return{enumerable:!0,configurable:!0}}}),u={variables:c,runtime:t,resolveVariable:a};return r?(i.forEach(d=>{a(d)}),{...o,...s}):c},oc=({variables:e={},runtime:t={},variableConfigs:n,projectData:r}={})=>vt({variables:e,runtime:t,variableConfigs:n??r?.resources?.variables??{},eager:!0}),Qt=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{if(De(o))return;let i=Ya(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},Zt=(e,t)=>{let n=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!n.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${n.join(", ")}`)},en=(e,t,n)=>{let r={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=r[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${n}`);if(!Object.values(r).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${n}" of type "${e}". Valid operations: ${o.join(", ")}`)},ic=2,Ro=12,Do=(e=ic)=>{if(!Number.isInteger(e)||e<0||e>Ro)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${Ro}.`);return e},sc=(e,t)=>{let n=10**t;return Math.round((e+Number.EPSILON)*n)/n},Gt=e=>typeof e=="number"&&Number.isFinite(e),Qn=(e,t,n,r,o={})=>{if(e==="number"){if(t==="set"&&!Gt(n))throw new Error(`Operation "set" requires value to be a number for variable "${r}".`);if(t==="multiply"&&!Gt(n))throw new Error(`Operation "multiply" requires value to be a number for variable "${r}".`);if(t==="divide"&&!Gt(n))throw new Error(`Operation "divide" requires value to be a number for variable "${r}".`);if(t==="divide"){if(n===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${r}".`);Do(o.roundTo)}}},tn=(e,t,n,r={})=>{let o=(s,l,a)=>{let c=s??l;if(!Gt(c))throw new Error(`Operation "${t}" requires ${a} to be a number.`);return c},i=s=>{let l=o(s,void 0,"value");if(l===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return l};switch(t){case"set":return n;case"multiply":return o(e,1,"current value")*o(n,void 0,"value");case"divide":return sc(o(e,0,"current value")/i(n),Do(r.roundTo));case"increment":return o(e,0,"current value")+o(n,1,"value");case"decrement":return o(e,0,"current value")-o(n,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var No=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let n=new Date(e),r=o=>String(o).padStart(2,"0");return t.replace("DD",r(n.getDate())).replace("MM",r(n.getMonth()+1)).replace("YYYY",n.getFullYear()).replace("YY",String(n.getFullYear()).slice(-2)).replace("HH",r(n.getHours())).replace("mm",r(n.getMinutes())).replace("ss",r(n.getSeconds()))},ac=(e,t)=>{let n=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let l=i.character?.sprite;return l&&Object.keys(l).length>0&&(s.sprite=l),Object.keys(s).length>0?s:void 0},r=n(e),o=n(t);return JSON.stringify(r)===JSON.stringify(o)?null:r&&!o?{changeType:"delete",data:e}:o&&!r?{changeType:"add",data:t}:o&&r?{changeType:"update",data:t}:null},Oo=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};e.transformId!==void 0&&(t.transformId=e.transformId);for(let n of["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"])e[n]!==void 0&&(t[n]=e[n]);for(let n of["animationName","animationSpeed","loop"])e[n]!==void 0&&(t[n]=e[n]);return t},ko=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},Lo=(e,t)=>t&&!e?{changeType:"add",data:t}:e&&!t?{changeType:"delete",data:e}:e&&t&&JSON.stringify(e)!==JSON.stringify(t)?{changeType:"update",data:t}:null,cc=(e,t)=>{let n={},r=Lo(Oo(e),Oo(t)),o=Lo(ko(e),ko(t));return r&&(n.resource=r),o&&(n.color=o),Object.keys(n).length>0?n:null},Zn=(e={},t={})=>{let n={},r=["sfx","voice"],o=l=>{let a=e[l],c=t[l];c&&!a?n[l]={changeType:"add",data:c}:a&&!c?r.includes(l)||(n[l]={changeType:"delete",data:a}):a&&c&&JSON.stringify(a)!==JSON.stringify(c)&&(n[l]={changeType:"update",data:c})},i=cc(e.background,t.background);i&&(n.background=i),o("screen"),o("bgm"),o("voice");let s=ac(e.dialogue,t.dialogue);return s&&(n.dialogue=s),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},er=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,!t.background.resourceId&&!t.background.colorId&&delete t.background);let n=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};n("layout"),n("choice"),n("form"),n("screen"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let r=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(l=>{let a={...l};return delete a.animations,i(a)?a:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return r("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),r("visual",o=>o.resourceId||o.transformId),t},lc=(e,t)=>{if(!e||!t)return;let n=e;for(let r of t.split(".")){if(n==null||!(r in Object(n)))return;n=n[r]}return n},uc=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let n=e.slice(7),r=lc(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},dc={conditional:new Set(["branches"]),updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"]),form:new Set(["submitActions","cancelActions"]),submitForm:new Set(["actions"]),cancelForm:new Set(["actions"])},Po=(e,t)=>{let n=e[e.length-1];return n?dc[n]?.has(t)===!0:!1},Jn=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Jn(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Po(n,r)?o:Jn(o,t,[...n,r])])):uc(e,t),Xn=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Xn(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Po(n,r)?o:Xn(o,t,[...n,r])])):typeof e=="string"?ce(e,t):e,tr=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let n=Jn(e,t._event);return Xn(n,t)};var Y=e=>structuredClone(se(e)?We(e):e),q=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Vo=e=>e?.animations?.playback?.continuity==="persistent",D=(e,t)=>q(e??{},t)&&e[t]!==void 0,Ct=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:Y(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},fc=e=>D(e,"opacity")||D(e,"blur"),Bo=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Uo=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],nr=["animationName","animationSpeed","loop"],pc=e=>Bo.some(t=>D(e,t)),zo=e=>e?.text&&D(e.text,"content")&&D(e.text,"textStyleId"),qo=e=>D(e,"text"),hc=(e,t)=>e.resourceId?!0:zo(e)?!t?.text:!1,mc=(e,t)=>{let n={...Y(e),...t};return t.text&&e.text&&(n.text={...Y(e.text),...Y(t.text)}),n},gc=(e,t)=>{if(qo(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!zo(e)&&!t?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},jo=e=>Uo.some(t=>D(e,t)),Fo=e=>nr.some(t=>D(e,t)),yc=(e,t,{hasAuthoredTransformId:n=!1}={})=>{if(!t)return e;for(let r of Uo)!n&&!D(e,r)&&D(t,r)&&(e[r]=t[r]),q(e,r)&&e[r]===void 0&&delete e[r];return e},Wo=(e,t,n)=>{let r=e[n];return r?.id===t?.id?r:e.find(o=>o.id===t?.id)},bc=(e,t)=>{if(!t)return e;for(let n of Bo)!D(e,n)&&D(t,n)&&(e[n]=t[n]),q(e,n)&&e[n]===void 0&&delete e[n];return e},Ic=(e,t)=>(t&&(!D(e,"opacity")&&D(t,"opacity")&&(e.opacity=t.opacity),!D(e,"blur")&&D(t,"blur")&&(e.blur=Y(t.blur)),q(e,"opacity")&&e.opacity===void 0&&delete e.opacity,q(e,"blur")&&e.blur===void 0&&delete e.blur),e),Ho=(e,t,n=[],{hasPatchFn:r=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,l)=>{let a=Wo(n,s,l),c=t(s,a),u=fc(s),d=pc(s),f=r(s),p=q(s,"animations"),h=Y(s);return!c&&(u||d||f)&&a&&(h=o?o(a,h):{...Y(a),...h},p||delete h.animations),Ic(bc(h,a),a)}).filter(s=>t(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},Ac=e=>{if(e){if(e.character&&q(e.character,"name"))return e.character.name;if(q(e,"characterName"))return e.characterName}},Yo=e=>!!e?.character&&q(e.character,"sprite"),wc=e=>{let t={},n=!1,r=Ac(e);return r!==void 0&&(t.name=r,n=!0),Yo(e)&&(t.sprite=Y(e.character.sprite),n=!0),n?t:void 0},Mo=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Ec=({dialogueState:e,content:t,append:n=!1})=>{if(!n||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let r=Array.isArray(e.content)?e.content:[];r.length>0?e.initialRevealedContent=r.map(o=>Y(o)):delete e.initialRevealedContent,e.content=[...r,...t]},xc=()=>({}),vc=(e,t)=>{if(!t.screen)return;let n=D(t.screen,"opacity"),r=D(t.screen,"blur"),o=q(t.screen,"animations");if(!n&&!r){o||delete e.screen;return}let i=e.screen,s={};if(n?s.opacity=t.screen.opacity:D(i,"opacity")&&(s.opacity=i.opacity),r?s.blur=Y(t.screen.blur):D(i,"blur")&&(s.blur=Y(i.blur)),q(s,"opacity")&&s.opacity===void 0&&delete s.opacity,q(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},Cc=(e,t)=>{if(t.background){let n=D(t.background,"resourceId"),r=D(t.background,"colorId"),o=D(t.background,"opacity"),i=D(t.background,"blur"),s=D(t.background,"transformId"),l=jo(t.background),a=Fo(t.background),{animationsOnly:c,state:u}=Ct(t.background,p=>D(p,"resourceId")||D(p,"colorId")||D(p,"opacity")||D(p,"blur")||D(p,"transformId")||jo(p)||Fo(p));if(c){e.background=e.background?{...Y(e.background),...u}:u;return}if(!n&&!r&&!o&&!i&&!s&&!l&&!a){delete e.background;return}let d=e.background,f=Y(t.background);if(!n&&d?.resourceId){f.resourceId=d.resourceId,!q(f,"transformId")&&d.transformId&&(f.transformId=d.transformId);for(let p of nr)!D(f,p)&&D(d,p)&&(f[p]=d[p])}yc(f,d,{hasAuthoredTransformId:s}),!r&&d?.colorId&&(f.colorId=d.colorId),!o&&D(d,"opacity")&&(f.opacity=d.opacity),!i&&D(d,"blur")&&(f.blur=Y(d.blur)),q(f,"resourceId")&&f.resourceId===void 0&&delete f.resourceId,q(f,"colorId")&&f.colorId===void 0&&delete f.colorId,q(f,"animations")&&f.animations===void 0&&delete f.animations,q(f,"transformId")&&f.transformId===void 0&&delete f.transformId,q(f,"opacity")&&f.opacity===void 0&&delete f.opacity,q(f,"blur")&&f.blur===void 0&&delete f.blur;for(let p of nr)q(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&&!q(f,"animations")&&Vo(d)&&(f.animations=Y(d.animations)),e.background=f}else e.background?.animations&&!Vo(e.background)&&(e.background.animations={})},Sc=(e,t)=>{if(!t.dialogue){e.dialogue&&(Mo(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,delete e.dialogue.textSpeed,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let n=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:c,state:u}=Ct(t.dialogue.ui,d=>!!d.resourceId);c?e.dialogue.ui={...e.dialogue.ui,...u}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let r=t.dialogue.append===!0&&n!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&Ec({dialogueState:e.dialogue,content:t.dialogue.content,append:r}),q(t.dialogue,"textSpeed")?e.dialogue.textSpeed=t.dialogue.textSpeed:delete e.dialogue.textSpeed;let o=q(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=q(t.dialogue,"characterId"),s=wc(t.dialogue),l=s!==void 0,a=Yo(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!r&&delete e.dialogue.characterId,l?e.dialogue.character=!i&&o&&e.dialogue.character?{...Y(e.dialogue.character),...s}:s:(i||!o&&!r)&&delete e.dialogue.character,a||Mo(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let c={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.textSpeed!==void 0&&(c.textSpeed=e.dialogue.textSpeed),e.dialogue.character&&(c.character=Y(e.dialogue.character)),e.dialogue.lines.push(c)}},_c=(e,t)=>{if(t.sfx){let n=Array.isArray(t.sfx.items)&&t.sfx.items.length>0,r=Array.isArray(t.sfx.channels)&&t.sfx.channels.length>0;if(!n&&!r){delete e.sfx;return}e.sfx=Y(t.sfx)}else e.sfx&&delete e.sfx},Rc=(e,t)=>{if(t.bgm){let n=Array.isArray(t.bgm.sounds);if(!t.bgm.resourceId&&!n||n&&t.bgm.sounds.length===0){e.bgm=void 0;return}e.bgm=Y(t.bgm),t.bgm.resourceId&&(e.bgm.loop=t.bgm.loop??!0)}},Oc=(e,t)=>{if(t.visual){let n=e.visual?.items||[];t.visual.items?.forEach((i,s)=>{gc(i,Wo(n,i,s))});let{hasValidItems:r,processedItems:o}=Ho(t.visual.items,hc,n,{hasPatchFn:qo,mergeItemFn:mc});r?e.visual={items:o}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},kc=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:n,processedItems:r}=Ho(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);n?e.character={items:r}:delete e.character},Lc=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},$c=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=Ct(t.layout,o=>!!o.resourceId);if(n){e.layout=r;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},Tc=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=Ct(t.choice,o=>!!o.resourceId);if(n){e.choice={...e.choice,...r};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},Dc=(e,t)=>{if(t.form){let{animationsOnly:n,state:r}=Ct(t.form,o=>!!o.resourceId);if(n){e.form={...e.form,...r};return}if(!t.form.resourceId){delete e.form;return}e.form=Y(t.form)}else e.form&&delete e.form},Nc=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},Pc=(e,t)=>{if(t.voice){let n=Array.isArray(t.voice.sounds);if(!t.voice.resourceId&&!n||n&&t.voice.sounds.length===0){delete e.voice;return}e.voice=Y(t.voice)}else e.voice&&delete e.voice},Vc=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},Ye=e=>Jt(xc,[Vc,vc,Cc,_c,Rc,Oc,Sc,kc,Lc,$c,Tc,Dc,Nc,Pc])(e);var at=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=ce(e,t);return n&&typeof n=="object"?e:n};var jc=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},autoForwardSpeed:{source:"global.autoForwardSpeed"},skipUnseenText:{source:"global.skipUnseenText"},skipTransitionsAndAnimations:{source:"global.skipTransitionsAndAnimations"},soundVolume:{source:"global.soundVolume"},musicVolume:{source:"global.musicVolume"},muteAll:{source:"global.muteAll"},saveLoadPagination:{source:"context.runtime.saveLoadPagination"},menuPage:{source:"context.runtime.menuPage"},menuEntryPoint:{source:"context.runtime.menuEntryPoint"},autoMode:{source:"global.autoMode"},skipMode:{source:"global.skipMode"},dialogueUIHidden:{source:"global.dialogueUIHidden"},isLineCompleted:{source:"global.isLineCompleted"}}),Ge=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,autoForwardSpeed:1,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),St=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Go=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"}),rr=Object.freeze(["dialogueTextSpeed","autoForwardDelay","autoForwardSpeed","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),or=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Fc=(e,t)=>{if(t.startsWith("global.")){let n=t.slice(7);return e?.global?.[n]}if(t.startsWith("context.runtime.")){let n=t.slice(16),r=Array.isArray(e?.contexts)?e.contexts:[];return r[r.length-1]?.runtime?.[n]}},Ke=e=>Object.fromEntries(Object.entries(jc).map(([t,n])=>{let r=Fc(e,n.source),o=r!==void 0?r:Ge[t]??St[t];return[t,o]})),Ne=(e,t)=>Ke(e)[t],Ko=(e={})=>Object.fromEntries(rr.map(t=>[t,e[t]??Ge[t]]));var ct=Object.freeze({VISUAL_BEHIND_BACKGROUND:10,BACKGROUND:20,VISUAL_BEHIND_CHARACTER:30,CHARACTER:40,VISUAL_BEHIND_DIALOGUE:50,DIALOGUE:60,VISUAL_BEHIND_CHOICE:70,CHOICE:80,VISUAL_FOREGROUND:90}),_e=Object.freeze({BEHIND_BACKGROUND:ct.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:ct.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:ct.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:ct.VISUAL_BEHIND_CHOICE,FOREGROUND:ct.VISUAL_FOREGROUND}),ir=_e.BEHIND_DIALOGUE,sr=Object.freeze(Object.values(_e).sort((e,t)=>e-t));var Re={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:No},Mc=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,Bc=(e,t)=>{let n=String(t||"").trim();if(!n)return;let r=n.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of r){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},sn=(e,t,n)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),l=Mc.exec(s);if(l){let[,a,c,u]=l,d=Bc(t,u);if(!Array.isArray(d))continue;let f=Array.isArray(i[s])?i[s]:[];d.forEach((p,h)=>{let g={...t,[a]:p};c&&(g[c]=h),f.forEach(b=>{let A=sn(b,g,n),w=ce(A,g,n);Array.isArray(w)?o.push(...w):o.push(w)})});continue}}o.push(sn(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=sn(i,t,n)}),r},xr=({animationType:e,animationId:t,animationPath:n})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${n}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},Uc=({id:e,targetId:t,animation:n,playback:r,animationPath:o="animation"})=>{let i=structuredClone(n);if(xr({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,r!==void 0){let s=Hc(r,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},zc=(e,{animationId:t="animation",animationPath:n="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return xr({animationType:e.type,animationId:t,animationPath:n}),e.type},qc=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Wc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Hc=(e,t="animation.playback")=>{if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`[${t}] playback must be an object.`);if(e.continuity!==void 0&&e.continuity!=="render"&&e.continuity!=="persistent")throw new Error(`[${t}] playback.continuity must be "render" or "persistent".`);if(e.speed!==void 0&&(typeof e.speed!="number"||!Number.isFinite(e.speed)||e.speed<=0))throw new Error(`[${t}] playback.speed must be a finite number greater than 0.`);let n={};return e.continuity!==void 0&&(n.continuity=e.continuity),e.speed!==void 0&&e.speed!==1&&(n.speed=e.speed),Object.keys(n).length>0?n:void 0},Yc=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},Je=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),ci=e=>e?.playback?.continuity==="persistent",hr=e=>Array.isArray(e)?e.map(hr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,n)=>(t[n]=hr(e[n]),t),{}),cn=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return t.playback&&(delete t.playback.continuity,t.playback.speed===1&&delete t.playback.speed,Object.keys(t.playback).length===0&&delete t.playback),JSON.stringify(hr(t))},li=(e=[])=>e.filter(t=>ci(t)).map(t=>structuredClone(t)),ui=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,n)=>{let r=typeof n?.duration=="number"&&Number.isFinite(n.duration)?n.duration:0;return t+r},0):0,ar=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,n)=>Math.max(t,ui(n)),0),di=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(ar(e.tween),ar(e.prev?.tween),ar(e.next?.tween),ui(e.mask?.progress))/Yc(e),Jo=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let n=new Set(t.map(cn).filter(Boolean));return e.some(r=>{if(!ci(r))return!1;let o=cn(r);return o?n.has(o):!1})},Ee=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:n,activePersistentAnimations:r,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||n?!1:i&&!t||Jo({animationInstances:e,activePersistentAnimations:r})?!0:i?!1:Jo({animationInstances:e,activePersistentAnimations:o}),Gc=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Kc=(e,t)=>{if(Gc(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},Jc=({resources:e,animationId:t,playback:n,instanceId:r,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?Uc({id:r,targetId:o,animation:s,playback:n,animationPath:i}):null},Xc=(e,{defaultTargetId:t,defaultId:n,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return xr({animationType:o.type,animationId:o.id??n,animationPath:r}),o.id??=n,o.targetId??=t,o},vr=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r,animationPathPrefix:o=r})=>{t.forEach((i,s)=>{e.push(Xc(i,{defaultTargetId:n,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},mr=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(n=>n===null||typeof n!="object"||Array.isArray(n)))throw new Error(`${t} must be an array of objects`);return e},Qc=({content:e,path:t,variables:n})=>mr(e,t).reduce((r,o)=>{let i=at(o.text,{variables:n});return r+`${i??""}`.length},0),Xo=(e=[])=>{let t=new Map;for(let n of e)n?.id&&t.set(n.id,(t.get(n.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,n])=>n>1).map(([n])=>n))},nn=(e,t=0,n=new Set)=>{if(!n.has(e?.id))return`character-container-${e.id}`;let r=e?.sprites?.map(({resourceId:o})=>o)||[];return r.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${r.join("-")}`},rn=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return n},Zc=(e,t={})=>{if(!t?.transformId)return;let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for background`);return n},el=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],tl=(e={})=>el.some(t=>Je(e,t)),fi=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.spritesheets?.[t])return"spritesheet-animation";if(e.layouts?.[t])return"container"}},an=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},nl=(e={})=>e.textStyles||{},rl=(e={})=>e.images||{},ol=.5,il=(e={},t,n)=>{if(t){if(!e.animations?.[t])throw new Error(`Animation '${t}' not found in spritesheet resource '${n}'`);return t}return Object.keys(e.animations??{})[0]},pi=({id:e,resourceId:t,spritesheet:n,animationName:r,animationSpeed:o,loop:i,transform:s={}}={})=>{let l=il(n,r,t),a=l?n.animations?.[l]:void 0;if(!a){console.warn(`Spritesheet animation not found: ${t}`);return}return{id:e,type:"spritesheet-animation",...s,width:n.width,height:n.height,src:n.fileId,atlas:n.jsonData,playback:{frames:a.frames,animationSpeed:o??a.animationSpeed??ol,loop:i??a.loop??!0}}},hi=({id:e,item:t,resources:n={}}={})=>{let r=n.images?.[t.resourceId];if(r)return{type:"sprite",id:e,src:r.fileId,width:r.width,height:r.height,x:0,y:0};let o=n.spritesheets?.[t.resourceId];if(o)return pi({id:e,resourceId:t.resourceId,spritesheet:o,animationName:t.animationName,animationSpeed:t.animationSpeed,loop:t.loop,transform:{x:0,y:0}});console.warn(`Character sprite resource not found: ${t.resourceId}`)},sl=(e={})=>e.colors||{},al=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Ot=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,ut=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},cr=(e,t,n)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);return e},lr=(e,t,n,r,{minimum:o}={})=>{if(e===void 0)return r;if(typeof e!="number"||!Number.isFinite(e)||o!==void 0&&e<o){let i=o===void 0?"a finite number":`a finite number >= ${o}`;throw new Error(`shadow.${t} for text style "${n}" must be ${i}`)}return e},dn=(e,t)=>{if(typeof e!="string"||!al.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(n=>n.repeat(2)).join("")}`:e},Qo=(e,t,n)=>{let r=dn(e,n);if(t===1)return r;let o=Number.parseInt(r.slice(1,3),16),i=Number.parseInt(r.slice(3,5),16),s=Number.parseInt(r.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},cl=(e={},t)=>{let n=nl(e)?.[t];if(!n)throw new Error(`Text style "${t}" not found`);let r=e.fonts?.[n.fontId];if(!r)throw new Error(`Font "${n.fontId}" not found for text style "${t}"`);let o=e.colors?.[n.colorId];if(!o)throw new Error(`Color "${n.colorId}" not found for text style "${t}"`);let i=cr(n.colorAlpha,"colorAlpha",t),s={fontFamily:r.fileId,fontSize:n.fontSize??16,fontWeight:n.fontWeight??"400",fontStyle:n.fontStyle??"normal",lineHeight:n.lineHeight??1.2,fill:Qo(o.hex,i,`Color "${n.colorId}" for text style "${t}"`)};if(n.align!==void 0&&(s.align=n.align),n.wordWrap!==void 0&&(s.wordWrap=n.wordWrap),n.breakWords!==void 0&&(s.breakWords=n.breakWords),n.wordWrapWidth!==void 0&&(s.wordWrapWidth=n.wordWrapWidth),n.strokeColorId){let l=e.colors?.[n.strokeColorId];if(!l)throw new Error(`Stroke color "${n.strokeColorId}" not found for text style "${t}"`);let a=cr(n.strokeAlpha,"strokeAlpha",t);s.strokeColor=Qo(l.hex,a,`Stroke color "${n.strokeColorId}" for text style "${t}"`)}else if(n.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);if(n.strokeWidth!==void 0&&(s.strokeWidth=n.strokeWidth),n.shadow!==void 0){let l=e.colors?.[n.shadow.colorId];if(!l)throw new Error(`Shadow color "${n.shadow.colorId}" not found for text style "${t}"`);s.shadow={color:dn(l.hex,`Shadow color "${n.shadow.colorId}" for text style "${t}"`),alpha:cr(n.shadow.alpha,"shadow.alpha",t),blur:lr(n.shadow.blur,"blur",t,0,{minimum:0}),offsetX:lr(n.shadow.offsetX,"offsetX",t,2),offsetY:lr(n.shadow.offsetY,"offsetY",t,2)}}return s},gr=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>gr(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${n}". Use textStyleId instead`);let r={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(r[o]=gr(i,t,Ot(n,o)));return e.textStyleId!==void 0&&(ut(e.textStyleId,n,"textStyleId"),r.textStyle=cl(t,e.textStyleId)),r},Cr=(e={},t)=>{let n=sl(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return dn(n.hex,`Color "${t}"`)},mi=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",ur=(e,t,n)=>{let r=e?.[t];if(!(!r||typeof r!="object"||Array.isArray(r))&&Object.prototype.hasOwnProperty.call(r,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${n}". Use ${mi(`${t}.fill`)} instead`)},ll=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>kt(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;let r={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(r[o]=kt(i,t,Ot(n,o)));return e.colorId!==void 0&&(ut(e.colorId,n,"colorId"),r.fill=Cr(t,e.colorId)),r},kt=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>kt(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${n}". Use ${mi("fill")} instead`);ur(e,"hover",n),ur(e,"click",n),ur(e,"rightClick",n)}let r={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){r[o]=ll(i,t,Ot(n,o));continue}r[o]=kt(i,t,Ot(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(ut(e.colorId,n,"colorId"),r.fill=Cr(t,e.colorId)),r},dr=(e={},t)=>{let n=rl(e)?.[t];return n||null},gi=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",Zo=(e,t,n,r)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,r))throw new Error(`Inline ${t}.${r} is not allowed in sprite layout elements at "${n}". Use ${gi(`${t}.${r}`)} instead`)},ei=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},yr=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>yr(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${n}". Use ${gi(o)} instead`);Zo(e,"hover",n,"src"),Zo(e,"click",n,"src")}let r={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(r[o]=yr(i,t,Ot(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){ut(e.imageId,n,"imageId");let o=dr(t,e.imageId),i=o?.fileId??e.imageId;r.src=i,r.width===void 0&&o?.width!==void 0&&(r.width=o.width),r.height===void 0&&o?.height!==void 0&&(r.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(ut(e.hoverImageId,n,"hoverImageId"),ei(r,"hover",dr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(ut(e.clickImageId,n,"clickImageId"),ei(r,"click",dr(t,e.clickImageId)?.fileId??e.clickImageId)),r},Sr=(e,t={},n="root")=>yr(kt(gr(e,t,n),t,n),t,n),Oe=Sr,Qe=(e=[])=>e.find(t=>t.id==="story"),ul="#000000",br="bg-cg-background-color",dl=({resources:e={},background:t={},screen:n})=>t?.colorId===void 0?dn(n?.backgroundColor??ul,"screen.backgroundColor"):Cr(e,t.colorId),yi=(e={})=>{if(Je(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},fl=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},ti=(e={},{includeDefaultAlpha:t=!1}={})=>{let n=yi(e),r=fl(e),o={};return(t||n!==void 0)&&(o.alpha=n??1),r&&(o.blur=r),o},pl=(e={})=>{if(Je(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},hl=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},bi=(e={})=>{let t=pl(e),n=hl(e),r={};return t!==void 0&&(r.alpha=t),n&&(r.blur=n),r},_t=(e={})=>bi(e),Pe=(e={},t={})=>{let n={x:t.x??e.x,y:t.y??e.y,anchorX:t.anchorX??e.anchorX,anchorY:t.anchorY??e.anchorY,rotation:t.rotation??e.rotation,scaleX:t.scaleX??e.scaleX,scaleY:t.scaleY??e.scaleY},r=t.originX??e.originX,o=t.originY??e.originY;return r!==void 0&&(n.originX=r),o!==void 0&&(n.originY=o),n},ml=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],_r=(e={})=>e.text&&Je(e.text,"content")&&Je(e.text,"textStyleId"),ni=(e={})=>{if(e.resourceId)return e.resourceId;if(_r(e))return"text"},gl=e=>{if(e.text){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!_r(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let t of ml)if(Je(e.text,t))throw new Error(`Visual item "${e.id}" text.${t} is reserved for the visual item`)}},yl=({resources:e,background:t,screen:n={width:1920,height:1080},includeOpacity:r=!1})=>{let o={id:br,type:"rect",x:0,y:0,width:n?.width??1920,height:n?.height??1080,fill:dl({resources:e,background:t,screen:n})};if(r){let i=yi(t);i!==void 0&&(o.alpha=i)}return o},bl=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.spritesheets?.[t]||e.layouts?.[t]):!1,ri=({resources:e={},resourceId:t,colorId:n})=>{let r=fi(e,t);return t&&(r||n===void 0)?{resourceId:t,targetId:an({resourceId:t,kind:r})}:n!==void 0?{resourceId:br,targetId:br}:{resourceId:void 0,targetId:void 0}},Ii=100,Xe=Ii,Il="channel:bgm",Al="channel:voice",wl="default",El=e=>String(e).replaceAll("%","%25").replaceAll(":","%3A"),Rt=(...e)=>e.map(El).join(":"),ln=(e,t,n)=>{let r=new Set;e.forEach(({id:o})=>{if(r.has(o)){let i=n?` in ${n}`:"";throw new Error(`Duplicate ${t} id "${o}"${i}.`)}r.add(o)})},xl=(e,t)=>e*t/Ii,Ai=(e={},t)=>e?.[t]??Ge[t],Rr=(e={},t,n=Xe)=>xl(n,Ai(e,t)),Or=({id:e,volume:t,muted:n,pan:r,children:o,runtime:i})=>({id:e,type:"audio-channel",volume:t,muted:!!i?.muteAll||(n??!1),pan:r??0,children:o}),on=(e,t,n,r)=>e[n]!==void 0?e[n]:t[n]!==void 0?t[n]:r,vl=["muted","pan","playbackRate","startAt","endAt"],kr=({id:e,sound:t,resource:n,defaultLoop:r=!1})=>{let o={id:e,type:"sound",src:n.fileId,loop:on(t,n,"loop",r),volume:on(t,n,"volume",Xe),startDelayMs:on(t,n,"startDelayMs",0)};vl.forEach(s=>{let l=on(t,n,s,void 0);l!==void 0&&(o[s]=l)});let i=o.startAt??0;if(o.endAt!==void 0&&o.endAt!==null&&o.endAt<i)throw new Error(`Sound "${e}" endAt (${o.endAt}) must be greater than or equal to startAt (${i}).`);return o},xe=({variables:e,runtime:t,saveSlots:n=[],dialogueState:r,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,confirmDialog:d,form:f,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:b,skipTransitionsAndAnimations:A}={})=>{let w={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,autoForwardSpeed:t?.autoForwardSpeed??1,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??l??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},C=Ol({dialogueState:r,includeInactiveAdvDialogue:o,characters:h,variables:e,runtime:w}),R={variables:e,runtime:w,saveSlots:n,isChoiceVisible:a,isFormVisible:c,canRollback:u,confirmDialog:d,form:f,historyDialogue:p,characters:h};return C&&(R.dialogue=C,R.dialogueLines=C.lines),R},oi=100,un=(e,t)=>{if(Array.isArray(e))return e.map(r=>un(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=un(n[r],t)}),n.type==="text-revealing"?t(n):n},Cl=e=>un(e,t=>({...t,revealEffect:"none"})),Sl=e=>un(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,oi):oi;return{...t,speed:r,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:r}:{}}}),Ve=(e,{isLineCompleted:t=!1,skipMode:n=!1,skipTransitionsAndAnimations:r=!1}={})=>t||r?Cl(e):n?Sl(e):e,wi=({id:e,screen:t={width:1920,height:1080}})=>({id:e,type:"rect",fill:"transparent",width:t.width,height:t.height,x:0,y:0,click:{payload:{actions:{}}}}),Ir=e=>{if(Array.isArray(e))return e.map(Ir);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Ir(s);let n=t.click?.payload;if(!n||typeof n!="object"||Array.isArray(n))return t;let r=n.actions,o=r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"nextLine")?{...r.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...n,bypassChoice:!0,...o?{actions:{...r,nextLine:o}}:{}}}}},_l=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),ii="submit",fr=(e,t,n={})=>{let r=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},o=r.actions&&typeof r.actions=="object"?r.actions:{},i=n.replaceActions===!0?t:{...o,...t};return{...e||{},payload:{...r,actions:i}}},Ar=(e,t,n={})=>{if(Array.isArray(e))return e.map(c=>Ar(c,t,n));if(!e||typeof e!="object")return e;let r=typeof e.type=="string",o=r&&e.formRole===ii,i=r&&n.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},l={};for(let[c,u]of Object.entries(e))l[c]=Ar(u,t,c==="children"?s:{});let a=l;if(a.type==="input"&&typeof a.field=="string"){let c=t?.fields?.[a.field];if(c){let u={updateFormField:{formKey:t.key,field:c.id,value:"_event.value"}};a={...a,value:c.value,placeholder:a.placeholder===void 0?c.placeholder:a.placeholder,multiline:a.multiline===void 0?c.multiline:a.multiline,...a.maxLength===void 0&&c.maxLength!==void 0?{maxLength:c.maxLength}:{},change:fr(a.change,u),submit:fr(a.submit,t.submitActions)}}}return a.formRole===ii||i?{...a,click:fr(a.click,t.submitActions,{replaceActions:!0})}:a},wr=(e,t)=>{if(Array.isArray(e))return e.map(r=>wr(r,t));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e))n[r]=wr(o,t);for(let r of _l){let o=n[r]?.payload;!o||typeof o!="object"||Array.isArray(o)||(n[r]={...n[r],payload:{...o,_interactionSource:"form"}})}return n},Er=({characterId:e,character:t,characterName:n,characters:r={},variables:o={}}={})=>{let i=e?r?.[e]:void 0,s=Xt({characterId:e,character:t,characterName:n,characters:r,variables:o});return{...i||{},...t||{},name:s}},Ei=(e=[],t={},n={})=>e.map(r=>{let o=Er({characterId:r.characterId,character:r.character,characterName:r.characterName,characters:t,variables:n}),i=typeof r.text=="string"?r.text:Array.isArray(r.content)?r.content.map(s=>s?.text??"").join(""):"";return{...r,text:i,character:o,characterName:o.name}}),Rl=e=>!(!e||e.mode==="adv"&&e.content===void 0),Ol=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:n={},variables:r,runtime:o}={})=>{if(!t&&!Rl(e))return;let i=e.content===void 0?[{text:""}]:mr(e.content,"dialogue.content"),s=e.content===void 0?0:Qc({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:r}),l=o?.dialogueTextSpeed??Ge.dialogueTextSpeed,a=e.textSpeed??l,c=(e.lines||[]).map((d,f)=>{let p=mr(d.content,`dialogue.lines[${f}].content`),h=Er({characterId:d.characterId,character:d.character,characterName:d.characterName,characters:n,variables:r});return{...d,textSpeed:d.textSpeed??l,content:p.map(g=>({...g,text:at(g.text,{variables:r})})),character:h,characterName:h.name}}),u=Er({characterId:e.characterId,character:e.character,characters:n,variables:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:u,textSpeed:a,content:i.map(d=>({...d,text:at(d.text,{variables:r})})),initialRevealedCharacters:s,lines:c}},xi=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=ce(e,n,{functions:Re});return Oe(Ve(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},pr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),si=({renderStateKeyboard:e,keyboard:t,phase:n})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([r,o])=>{let i=e[r]??{},s=n==="keydown"?o?.keydown:o?.keyup;if(n==="keydown"&&s&&typeof s=="object"){e[r]={...i,keydown:{payload:pr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[r].keyup={payload:pr(o.keyup)});return}e[r]={...i,[n]:{payload:pr(o)}}})},kl=(e={},t={})=>{let n={};return si({renderStateKeyboard:n,keyboard:e,phase:"keydown"}),si({renderStateKeyboard:n,keyboard:t,phase:"keyup"}),Object.keys(n).length>0?n:void 0},ke=({animationsDef:e,resources:t,previousResourceId:n,currentResourceId:r,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l})=>{if(!e)return[];let a=[],c=({instanceId:A,targetId:w})=>{let C=Jc({resources:t,animationId:p,playback:h,instanceId:A,targetId:w,animationPath:s});C&&a.push(C)},u=n!=null&&n!==!1,d=r!=null&&r!==!1,f=o&&i&&o===i;Kc(e,s);let p=qc(e),h=Wc(e),g=t?.animations?.[p],b=zc(g,{animationId:p,animationPath:s});if(b==="update")return d&&i?c({instanceId:`${l}-animation-update`,targetId:i}):u&&o&&c({instanceId:`${l}-animation-update`,targetId:o}),a;if(b==="transition"){let A=`${l}-animation-transition`,w=h?.continuity==="persistent"?A:`${l}-animation-in`;if(u&&d&&f)return c({instanceId:A,targetId:i}),a;u&&c({instanceId:`${l}-animation-out`,targetId:o}),d&&c({instanceId:w,targetId:i})}return a},Ll=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),$l=(e,{presentationState:t,previousPresentationState:n,currentLineActions:r,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:a,runtime:c,activePersistentAnimations:u,restoredPersistentAnimations:d,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:b,form:A,saveSlots:w=[]})=>{let{elements:C,animations:R}=e;if(t.background){let P=r===void 0?!0:Je(r?.background??{},"animations"),V=C.find(re=>re.id==="story");if(!V)return e;let E=Zc(o,t.background),M=E||tl(t.background),B=n?.background?.resourceId,J=n?.background?.colorId,F=t.background.resourceId??(t.background.animations?B:void 0),H=t.background.colorId??(t.background.animations?J:void 0),G=bl(o,F),Z={...t.background,colorId:H};if((H!==void 0||G)&&V.children.push(yl({resources:o,background:Z,screen:i,includeOpacity:!G})),F){let{images:re={},videos:de={},spritesheets:X={}}=o,oe=fi(o,F),ie;if(oe==="sprite"?ie=re[F]:oe==="video"?ie=de[F]:oe==="spritesheet-animation"&&(ie=X[F]),ie){let S=oe==="video",O=oe==="spritesheet-animation",j={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...E},fe={...ti(t.background,{includeDefaultAlpha:!0}),...Pe(j,t.background)},te;O?te=pi({id:an({resourceId:F,kind:oe}),resourceId:F,spritesheet:ie,animationName:t.background.animationName,animationSpeed:t.background.animationSpeed,loop:t.background.loop,transform:fe}):te={id:an({resourceId:F,kind:oe}),type:S?"video":"sprite",src:ie.fileId,width:ie.width,height:ie.height,...fe},S&&(te.loop=t.background.loop??!1,te.volume=ie.volume??50),te&&V.children.push(te)}}if(F){let{layouts:re={}}=o,de=re[F];if(de){let X={id:an({resourceId:F,kind:"container"}),type:"container",children:de.elements,...ti(t.background)};M&&Object.assign(X,Pe({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...E},t.background));let oe=ce(X,xe({variables:a,runtime:c,saveSlots:w,dialogueState:t.dialogue,isLineCompleted:s,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:b,form:A,characters:o.characters||{},skipTransitionsAndAnimations:l}),{functions:Re});V.children.push(Oe(Ve(oe,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:l}),o))}}let Se=ri({resources:o,resourceId:B,colorId:J}),ue=ri({resources:o,resourceId:F,colorId:H}),ee=ke({animationsDef:t.background.animations,resources:o,previousResourceId:Se.resourceId,currentResourceId:ue.resourceId,previousTargetId:Se.targetId,currentTargetId:ue.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});Ee({animationInstances:ee,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:u,restoredPersistentAnimations:d,isAuthoredOnCurrentLine:P})&&R.push(...ee)}return e},Tl=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:a}=e;if(t.character&&r){let c=l.find(h=>h.id==="story");if(!c)return e;let u=t.character.items||[],d=n?.character?.items||[],f=Xo(u),p=Xo(d);for(let h=0;h<u.length;h++){let g=u[h],{transformId:b,sprites:A}=g,w=d.find(F=>F.id===g.id),C=d.findIndex(F=>F.id===g.id),R=w?.sprites&&w.sprites.length>0,P=A&&A.length>0,V=C>=0?nn(w,C,p):void 0,E=ke({animationsDef:g.animations,resources:r,previousResourceId:V,currentResourceId:P?nn(g,h,f):void 0,previousTargetId:V,currentTargetId:P?nn(g,h,f):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!A&&!b&&R&&Ee({animationInstances:E,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...E);continue}if(g.animations&&!A&&!b)continue;if(!A||A.length===0||!b){console.warn("Character item missing sprites or transformId:",g);continue}let M=nn(g,h,f),B=r.transforms[b];if(!B){console.warn("Transform not found:",b);continue}let J={type:"container",id:M,...Pe(B,g),..._t(g),children:[]};for(let F of A){let H=hi({id:`${M}-${F.id}`,item:F,resources:r});H&&J.children.push(H)}c.children.push(J),Ee({animationInstances:E,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...E)}}return e},vi=(e,t)=>{if(!sr.includes(e))throw new Error(`${t} must be one of: ${sr.join(", ")}.`)},Dl=(e,t)=>{let n=!!e.resourceId||_r(e),r=e.layer??(n?void 0:t?.layer)??ir;return vi(r,`Visual item "${e.id}" layer`),r},Nl=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:l,activePersistentAnimations:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,saveSlots:g=[],visualLayer:b})=>{let{elements:A,animations:w}=e;if(t.visual&&r){let C=A.find(E=>E.id==="story");if(!C)return e;let R=t.visual.items,P=n?.visual?.items||[],V=xe({variables:s,runtime:l,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,characters:r.characters||{},skipTransitionsAndAnimations:i});b!==void 0&&vi(b,"visualLayer");for(let E of R){let M=P.find(G=>G.id===E.id),B=Dl(E,M);if(b!==void 0&&B!==b)continue;if(gl(E),E.text){let G=rn(r,E),Z={...structuredClone(E.text),id:`visual-${E.id}`,type:"text",...Pe(G,E)};Object.assign(Z,_t(E)),C.children.push(Oe(ce(Z,V,{functions:Re}),r))}if(E.resourceId){let{images:G={},videos:Z={},spritesheets:Se={}}=r,ue=Se[E.resourceId];if(ue){let ee=rn(r,E),re=E.animationName;if(re){let de=ue.animations?.[re];if(!de)throw new Error(`Animation '${re}' not found in spritesheet resource '${E.resourceId}'`);let X=_t(E),oe={id:`visual-${E.id}`,type:"spritesheet-animation",...Pe(ee,E),width:E.width??ue.width,height:E.height??ue.height,alpha:X.alpha??E.alpha??1,src:ue.fileId,atlas:ue.jsonData,playback:{frames:de.frames,animationSpeed:E.animationSpeed??de.animationSpeed??.5,loop:E.loop??de.loop??!0}};X.blur&&(oe.blur=X.blur),C.children.push(structuredClone(oe))}}else{let ee=G[E.resourceId]||Z[E.resourceId];if(ee){let re=Z[E.resourceId]!==void 0,de=rn(r,E),X={id:`visual-${E.id}`,type:re?"video":"sprite",src:ee.fileId,width:ee.width,height:ee.height,...Pe(de,E)};Object.assign(X,_t(E)),re&&(X.loop=ee.loop??!1,X.volume=ee.volume??50),C.children.push(X)}}}if(E.resourceId){let{layouts:G={}}=r,Z=G[E.resourceId];if(Z){let Se=rn(r,E),ue={id:`visual-${E.id}`,type:"container",children:structuredClone(Z.elements),...Pe(Se,E)};Object.assign(ue,_t(E));let ee=ce(ue,V,{functions:Re});C.children.push(Oe(Ve(ee,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),r))}}let J=ni(M),F=ni(E),H=ke({animationsDef:E.animations,resources:r,previousResourceId:J,currentResourceId:F,previousTargetId:J?`visual-${E.id}`:void 0,currentTargetId:F?`visual-${E.id}`:void 0,animationPath:`visual.items[${E.id}].animations`,idPrefix:E.id});Ee({animationInstances:H,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:a})&&w.push(...H)}}return e},lt="dialogue-character-sprite",ai=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,Pl=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=Qe(e.elements);if(!a)return e;let c=t.dialogue?.character?.sprite,u=n?.dialogue?.character?.sprite,d=ai(c),f=ai(u),p=ke({animationsDef:c?.animations,resources:r,previousResourceId:f?lt:void 0,currentResourceId:d?lt:void 0,previousTargetId:f?lt:void 0,currentTargetId:d?lt:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!d)return c?.animations&&f&&Ee({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e;let h=r.transforms?.[c.transformId];if(!h)return console.warn("Transform not found:",c.transformId),e;let g={type:"container",id:lt,...Pe(h),children:[]};for(let b of c.items){let A=hi({id:`${lt}-${b.id}`,item:b,resources:r});A&&g.children.push(A)}return a.children.push(g),Ee({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e},Vl=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,skipOnlyViewedLines:d,isLineCompleted:f,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:b,saveSlots:A=[]})=>{let{elements:w,animations:C}=e;if(!t.dialogue||o)return e;let R=w.find(V=>V.id==="story");if(!R)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:V={}}=r,E=V[t.dialogue.ui.resourceId];if(E){let M={elements:E.elements},B=xe({variables:h,runtime:g,saveSlots:A,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:f,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,characters:r.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:d,skipTransitionsAndAnimations:p}),J={functions:Re},F=sn(M,B,J),H=ce(F,B,J),G=Oe(Ve(H?.elements,{isLineCompleted:f,skipMode:s,skipTransitionsAndAnimations:p}),r);if(Array.isArray(G))for(let Z of G)R.children.push(Z);else G&&R.children.push(G)}}Pl(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:b});let P=ke({animationsDef:t.dialogue.ui?.animations,resources:r,previousResourceId:n?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:n?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return Ee({animationInstances:P,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:b})&&C.push(...P),e},jl=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:b=[]})=>{let{elements:A,animations:w}=e;if(t.choice&&r){let C=Qe(A);if(!C)return e;let R=r?.layouts[t.choice.resourceId];if(R&&R.elements){let V={elements:R.elements},E=ce(V,{...xe({variables:l,runtime:a,saveSlots:b,dialogueState:t.dialogue,isLineCompleted:i,autoMode:c,skipMode:u,isChoiceVisible:d??!!t.choice,isFormVisible:f,canRollback:p,form:h,characters:r.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:Re}),M=Ir(Oe(Ve(E?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r));if(Array.isArray(M))for(let B of M)C.children.push(B);else M&&C.children.push(M)}let P=ke({animationsDef:t.choice.animations,resources:r,previousResourceId:n?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:n?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});Ee({animationInstances:P,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&w.push(...P)}return e},Fl=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:b})=>{let{elements:A,animations:w}=e;if(!b?.resourceId||!r)return e;let C=Qe(A);if(!C)return e;let R=r?.layouts?.[b.resourceId];if(!R)return console.warn(`Form layout not found: ${b.resourceId}`),e;let P={id:"form-container",type:"container",x:0,y:0,children:R.elements||[]},V={...xe({variables:l,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,characters:r.characters||{},skipTransitionsAndAnimations:s,form:b}),form:b},E=ce(P,V,{functions:Re}),M=wr(Oe(Ve(Ar(E,b),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r),b);M&&C.children.push(M);let B=ke({animationsDef:b.animations,resources:r,previousResourceId:n?.form?.resourceId,currentResourceId:b.resourceId,previousTargetId:n?.form?.resourceId?"form-container":void 0,currentTargetId:b.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return Ee({animationInstances:B,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&w.push(...B),e},Ml=(e,{presentationState:t,resources:n={},variables:r,runtime:o,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,saveSlots:f=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=n.controls?.[t.control.resourceId];if(!h)return e;let g=kl(h.keyboard,h.keyup);if(g&&Object.keys(g).length>0&&(e.global.keyboard=g),!Array.isArray(h.elements)||h.elements.length===0)return e;let b=Qe(e.elements);if(!b)return e;let A={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return b.children.push(xi({container:A,resources:n,templateData:xe({variables:r,runtime:o,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,characters:n.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:l,skipTransitionsAndAnimations:p})),e},Bl=(e,{presentationState:t,resources:n,runtime:r,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&n){if(!Qe(i))return e;let a=t.bgm,c=!Array.isArray(a.sounds),u=c?a.resourceId?[{id:"default",resourceId:a.resourceId,loop:a.loop??!0,volume:a.volume,startDelayMs:a.startDelayMs??0}]:[]:a.sounds,d=[];if(c||ln(u,"BGM sound"),u.forEach(p=>{let h=n.sounds?.[p.resourceId];h&&d.push(kr({id:Rt("bgm",c?"default":p.id),sound:p,resource:h,defaultLoop:!0}))}),d.length===0)return e;let f=xe({variables:o,runtime:r}).runtime;s.push(Or({id:Il,volume:Rr(f,"musicVolume",c?Xe:a.volume??Xe),muted:a.muted,pan:a.pan,children:d,runtime:f}))}return e},Ul=(e,{presentationState:t,resources:n,runtime:r})=>{let{audio:o}=e;if(t.sfx&&n){let i=t.sfx,s=!Array.isArray(i.channels),l=s?[{id:wl,sounds:i.items??[]}]:i.channels;s||ln(l,"SFX channel"),l.forEach(a=>{let c=[];s||ln(a.sounds,"SFX sound",`SFX channel "${a.id}"`),a.sounds.forEach((u,d)=>{let f=n.sounds?.[u.resourceId];f&&c.push(kr({id:s?Rt("sfx","default",d,u.id):Rt("sfx",a.id,u.id),sound:u,resource:f}))}),c.length!==0&&o.push(Or({id:Rt("channel","sfx",a.id),volume:Rr(r,"soundVolume",a.volume??Xe),muted:a.muted,pan:a.pan,children:c,runtime:r}))})}return e},zl=(e,t,n)=>{if(!(!t||!n))return e?.voices?.[t]?.[n]},ql=(e,{presentationState:t,resources:n,currentSceneId:r,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let l=t.voice,a=!Array.isArray(l.sounds),c=a?l.resourceId?[{id:"default",resourceId:l.resourceId,loop:l.loop??!1,volume:Xe,startDelayMs:l.startDelayMs??0}]:[]:l.sounds,u=[];if(a||ln(c,"Voice sound"),c.forEach(f=>{let p=zl(n,r,f.resourceId);p&&u.push(kr({id:Rt("voice",r,a?"default":f.id),sound:f,resource:p}))}),u.length===0)return e;let d=xe({variables:i,runtime:o}).runtime;return s.push(Or({id:Al,volume:a?l.volume??Ai(d,"soundVolume"):Rr(d,"soundVolume",l.volume??Xe),muted:l.muted,pan:l.pan,children:u,runtime:d})),e},Wl=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,saveSlots:f=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:b,animations:A}=e;if(t.layout){let P=Qe(b);if(!P)return e;let V=r.layouts[t.layout.resourceId];if(!V)return e;Array.isArray(V.transitions)&&!p&&!h&&vr({animations:A,transitions:V.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let E={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:V.elements||[]};P.children.push(xi({container:E,resources:r,templateData:xe({variables:o,runtime:i,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,characters:r.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:l,skipTransitionsAndAnimations:h}))}let w=n?.layout?.resourceId,C=t.layout?.resourceId,R=ke({animationsDef:t.layout?.animations,resources:r,previousResourceId:w,currentResourceId:C,previousTargetId:w?`layout-${w}`:void 0,currentTargetId:C?`layout-${C}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return Ee({animationInstances:R,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&A.push(...R),e},Hl=(e,{currentLineActions:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=t?.screen?.animations;if(!a)return e;let c=n!=null,u=ke({animationsDef:a,resources:r,previousResourceId:c?"story":void 0,currentResourceId:"story",previousTargetId:c?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return Ee({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...u),e},Yl=(e,{presentationState:t})=>{let n=Qe(e.elements);return!n||!t?.screen||Object.assign(n,bi(t.screen)),e},Gl=(e,{presentationState:t,resources:n={},variables:r,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,overlayStack:d=[],dialogueHistory:f=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:b})=>{let{elements:A,animations:w}=e;return d&&d.length>0&&d.forEach((C,R)=>{let P=n.layouts[C.resourceId];if(!P){console.warn(`Overlay layout not found: ${C.resourceId}`);return}Array.isArray(P.transitions)&&(b||vr({animations:w,transitions:P.transitions,defaultTargetId:`overlayStack-${R}`,idPrefix:`overlayStack-${R}`,animationPathPrefix:`overlayStack[${R}]`}));let V={id:`overlayStack-${R}`,type:"container",x:0,y:0,children:[wi({id:`overlayStack-${R}-blocker`,screen:h}),...P.elements||[]]},E=Ei(f,n.characters,r),M=xe({variables:r,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,historyDialogue:E,characters:n.characters||{},skipTransitionsAndAnimations:b}),B=ce(V,M,{functions:Re}),[J,...F]=B.children||[],H=Oe(Ve({...B,children:F},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:b}),n);A.push({...H,children:J?[J,...H.children||[]]:H.children})}),e},Kl=(e,{presentationState:t,resources:n={},variables:r,runtime:o,saveSlots:i=[],autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,confirmDialog:f,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:b})=>{let{elements:A,animations:w}=e;if(!f?.resourceId)return e;let C=n.layouts?.[f.resourceId];if(!C)return console.warn(`ConfirmDialog layout not found: ${f.resourceId}`),e;Array.isArray(C.transitions)&&!b&&vr({animations:w,transitions:C.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let R={id:"confirmDialog",type:"container",x:0,y:0,children:[wi({id:"confirmDialog-blocker",screen:h}),...C.elements||[]]},P=Ei(p,n.characters,r),V=ce(R,xe({variables:r,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,confirmDialog:f,historyDialogue:P,characters:n.characters||{},skipTransitionsAndAnimations:b}),{functions:Re}),[E,...M]=V.children||[],B=Oe(Ve({...V,children:M},{isLineCompleted:g,skipMode:l,skipTransitionsAndAnimations:b}),n);return A.push({...B,children:E?[E,...B.children||[]]:B.children}),e},Lt=e=>(t,n)=>Nl(t,{...n,visualLayer:e}),Jl=Lt(_e.BEHIND_BACKGROUND),Xl=Lt(_e.BEHIND_CHARACTER),Ql=Lt(_e.BEHIND_DIALOGUE),Zl=Lt(_e.BEHIND_CHOICE),eu=Lt(_e.FOREGROUND),Ci=e=>Jt(Ll,[Ml,Jl,$l,Xl,Tl,Ql,Vl,Zl,jl,Fl,Wl,eu,Yl,Hl,Bl,Ul,ql,Gl,Kl])(e);function Si(e,t=""){let n=[],r=e.length,o=0,i=0,s=-1,l=()=>{let a=0,c=0,u;do u=parseInt(e[o++],36),a+=(u&15)<<c,c+=4;while(u&16);return a};for(;o<r;){let a=s+1+l();s=a+l(),n.push([a,s,t?parseInt(t[i++],36):0])}return n}function _i(e,t,n){let r=0,o=t.length-1;for(;r<=o;){let i=r+o>>>1,s=n[i];if(e<t[i])o=i-1;else if(e>s>>>5)r=i+1;else return s&31}return 0}var Ri="090001000h1v5g2903000hl2v6jh16ng1s210111110o35aa10u2k1g10l6600152113h2010u1q1r5aq3890o13181214r22k3158q2n1000v100h1k20000001207030001160721k171001h1j11610332010010321210090411021c1c02100o301201412230u1130b100h1j116111420120411001100k11l10051001h1j11611142011000321210072411021d0g10r3000000132120090o200200g1j11f2012031213711271t1001o301001000001121371b1f0c101h1l2011001031212000080a1t1001m40400102101600i11t301006c7i601008b6p41r10101041h3d0004115a1j290p3q223000511010100g1501010302003172030c0010016000e0i6v50n40n5tl12ir33s12t11u11cj30100060700010a90t220000l71i20m7203010241000502rd101004k300000006101027050920g3t22bk1300616g209030207u18c1000t10003010501b2o20000102000004g37070101o921c000640602001mcv3rg20000001o16d0c0m1fg6g2h30m10q55f1vm11c0ma0p1a42nc0ne1a090q3314902021204020112030318250105bb1201110i1021i15101131502141b15120511011k1155132040202510201010603060a1f02040104210b1g3290e0e0kn11vs12j11j3040pp12t80g6v1vmo7319g21g51gh103040n11010040j51i3f01q1h1d0m27p1a0000cs13200523j200010301010100v140018a4q2501010101c08000i1f12601011g3012215110u1a0001015000pcq181000100011000iji5fvc0u91g5bhg20ie0l94lo6002115303121s12240la1tj23h44tj11t45m4ah33q700000l3ep2021a200t220301012040a0i320j2040007f00100r20c100g3208000011531000s520201036020t900207l1101n311000000321210090a12634b910201l22001051020120011020000e1i520701020000n10h5001050000010000010001re0010323010001r11i520701000001q6000000107l600000230004gg12080001lc62027111n1000411230000000000t820321030030r10090n205001380800501020n2050c0001mc00002000000nc006150000i5l1100600010001q753011160000i441111000000rl11019100000c1h201043102n10ltk1f006eoss2b0202gs94r36si2033ku101m373h50b1rqs4113sli1t22m1uh2435070726u13k92rr7m34h380e0m141egl561g1261114k60ga6nn10t33sv13uf1jf0207150qt16t66pr60n23k6bf1f0e1l29g71c1e029j1n30p11ea0k1028139m16rb2v621122i52213040tf1u3b51n17127c0232041d120819052c28220104060306l5g3l4572g130152cqdl2c3o37a5o27u11c32d9m2cu2191obo57eh9gg1tv3",Oi="262122424333333393233393339333333333393393bf3b3b3b3b3f3f3bffff33b3bb33ff3f33b3b3333333bffff3b33bb33f33bffff33b3bb33ff3f33b3bbb333b3ff33b333f33b3b3b3b3333b3bf33b3bb39333b33b33b3b3b333b333333b3b33333f3b33b3ffb3f3fff3f3b33f35dc33333f3b3b3b33323333b3bb3b33b3fb3b3333b33333bff3b3f33bfb3b3ff3b3b3b3b3b333b333b3323e22442344444444444444444444444444444444444444444444444444444444444444444444444444444443333333333b3b3bb33333b353bff3b3b3b3f3ff3b3b333bfff3f33333fb3bb3fb3b3bb33232333f333fff333333333b3b3333bb3b39393f3b3fbf33bb3b393b3b3b3333b33b33b3bbb33b33ffff3b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b3fffff3bb39b9b3b33b3bf3f3b33f3b3f93b33b3b3bb33b33b3b3b3333393b3b3b33b39bffb3b332333b333dd3b3333233332333333333333333333333333333444444444444a4444444444444344444444444444444444444444444444444444444444",ki="0001000000010010000000100000000000000000000000000001000000010014000100000001001000010101100101100000000000000000000100000001111000010000000110101001110111111111000100000021001000010000000100100001000000011010000100000001111000013000000100140001000000010010";var Li=65535,Lr=40960,fn=126976,Di=new Uint8Array(12288),Ni=new Uint8Array(3072),Pi=new Uint8Array(2816),Vi,ji;{let e=(o,i,s,l,a)=>{let c=i+o.length-1;for(let u=s<i?i:s,d=l>c?c:l;u<=d;u++)o[u-i]=a},t=new Uint32Array(320),n=new Uint32Array(320),r=0;for(let[o,i,s]of Si(Ri,Oi))e(Di,0,o,i,s),e(Ni,Lr,o,i,s),e(Pi,fn,o,i,s),i>=65040&&!(o>=fn&&i<=129791)&&(t[r]=o,n[r++]=i<<5|s);Vi=t.slice(0,r),ji=n.slice(0,r)}function $i(e){return e<12288?Di[e]:e<Lr?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?Ni[e-Lr]:e<55204?(e-44032)%28?8:7:e<57344?e<=55238?e>=55216?13:0:e>=55243&&e<=55291?12:0:e<65024?e===64286?3:0:e<65040?3:e>=fn&&e<129792?Pi[e-fn]:e>=917504?e>921599?0:e>=917536&&e<917632||e>=917760&&e<918e3?3:2:_i(e,Vi,ji)}var Fi=Uint8Array.from(ki,Number);function tu(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 Ti(e,t,n){switch(t){case 3:return e&24?n===8204?e&6:(e&24)===16||tu(n)?e&6|16:e&6|8:e&6;case 4:return 2;case 10:return e&1^1;case 14:return(e&2)<<1|e&24;default:return 8}}function*Mi(e){let t=e.length;if(t===0)return;let n=e.codePointAt(0),r=n>Li?2:1,o=$i(n),i=50200>>o&1?Ti(0,o,n):0,s=0,l=n,a=o;for(;r<t;){n=e.codePointAt(r);let c=n>Li?2:1,u=$i(n),d=Fi[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)?Ti(i,u,n):0,f&&(yield{segment:e.slice(s,r),index:s,input:e,_hd:l,_catBegin:a===15?0:a,_catEnd:o===15?0:o},s=r,l=n,a=u),r+=c,o=u}yield{segment:e.slice(s),index:s,input:e,_hd:l,_catBegin:a===15?0:a,_catEnd:o===15?0:o}}function*Bi(e){for(let t of Mi(e))yield t.segment}{let e=Mi("_");Fi._keep=[e,e.next()]}var Ui=1e3,nu=1,ru=60,ou=3,iu=.5,su=2e4,au=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,cu=/^\s+$/u,zi,lu=e=>{let t=`${e??""}`.normalize("NFC"),n=globalThis.Intl?.Segmenter;return typeof n!="function"?Array.from(Bi(t)):(zi??=new n(void 0,{granularity:"grapheme"}),Array.from(zi.segment(t),({segment:r})=>r))},uu=e=>lu(e).reduce((t,n)=>cu.test(n)?t+iu:au.test(n)?t+ou:t+1,0),qi=({text:e="",baseDelay:t=Ui,speed:n=nu}={})=>{let r=Number.isFinite(t)?Math.max(0,t):Ui,o=Number.isFinite(n)&&n>0?n:1,i=uu(e)*ru/o,s=Math.max(r,su);return Math.min(r+i,s)};var pn={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Ki=1,$r=1,ft="choice",je="form",gn=()=>({manual:{...pn.manual},auto:{...pn.auto},applyMode:pn.applyMode}),Tr=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...gn()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},N=e=>{let t=se(e)?We(e):e;return structuredClone(t)},$=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Tt=e=>String(e),Ji=()=>({sections:[],resources:[]}),du=e=>$(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Ji(),fu=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",pu=({sectionId:e,lineId:t,content:n,dialogueState:r,characterName:o})=>({sectionId:e,lineId:t,content:n,text:fu(n),characterId:r.characterId,character:{...r.character||{},name:o},characterName:o}),hu=()=>({resourceId:void 0}),mu=e=>{if(!$(e))return e;let t={...e};return Object.prototype.hasOwnProperty.call(t,"requireComplete")&&!Object.prototype.hasOwnProperty.call(t,"requireLineCompleted")&&(t.requireLineCompleted=t.requireComplete),delete t.requireComplete,t},pt=(e,t)=>{let n=e?.story?.scenes??{};for(let[r,o]of Object.entries(n))if(o?.sections?.[t])return{sceneId:r,section:o.sections[t]};return{sceneId:void 0,section:void 0}},Xi=e=>{let t=e?.story?.scenes??{},n=new Map;for(let[r,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let l=n.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${r}". Section IDs must be globally unique.`);n.set(s,r)}}},Qi=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Zi=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Ki)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},gu=(e,t={})=>{let n;try{n=Zi(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:Qi(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},yu=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,gu(t,n)])),es=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:n})=>If(n));return t.length>0?t:void 0},bu=e=>{!$(e)||!Array.isArray(e.timeline)||(e.returnabilityVersion=$r,e.timeline.forEach(t=>{if(!$(t))return;typeof t.returnable!="boolean"&&delete t.returnable;let n=es(t.executedActions);if(n){t.executedActions=n;return}delete t.executedActions}))},Wi=(e,t,n,r="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!$(e))throw new Error(`Malformed ${r}.${t}[${n}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${r}.${t}[${n}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${r}.sections[${n}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},Iu=(e,t="viewedRegistry")=>{if(e===void 0)return Ji();if(!$(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let n=e.sections??[],r=e.resources??[];return{sections:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Wi(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Wi(o,"resources",i,t);return[s.resourceId,s]})))}},ts=(e,t,n)=>{if(!$(e))throw new Error(`Malformed save slot ${n}.`);let{sectionId:r,lineId:o}=e;if(typeof r!="string"||r.length===0)throw new Error(`Malformed save slot ${n}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${n}: missing lineId.`);let{sceneId:i,section:s}=pt(t,r);if(!s)throw new Error(`Malformed save slot ${n}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(a=>a.id===o))throw new Error(`Malformed save slot ${n}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},ns=(e,t)=>e?.sectionId===t?.sectionId&&e?.lineId===t?.lineId,Au=(e,t)=>{let{section:n}=pt(e,t?.sectionId);return n?.lines?.find(r=>r.id===t?.lineId)},wu=(e,t)=>{let{section:n}=pt(e,t?.sectionId),r=n?.lines?.findIndex(i=>i.id===t?.lineId);if(typeof r!="number"||r<0)return null;let o=n.lines[r+1];return o?{sectionId:t.sectionId,lineId:o.id}:null},rs=(e,t,n)=>{if(typeof t?.sectionId!="string")return!1;let{section:r}=pt(e,t.sectionId);return ns({sectionId:t.sectionId,lineId:r?.lines?.[0]?.id},n)},Eu=new Set(["jumpToLine","rollbackByOffset","rollbackToLine","sectionTransition","resetStoryAtSection"]),dt={always:"always",maybe:"maybe",never:"never"},xu=e=>{if(!Object.prototype.hasOwnProperty.call(e??{},"when"))return dt.always;let t=e.when,n;if(t===null||typeof t=="boolean"||typeof t=="number")n=t;else if($(t)&&Object.keys(t).length===1&&Object.prototype.hasOwnProperty.call(t,"literal"))n=t.literal;else return dt.maybe;return n?dt.always:dt.never},os=(e,t)=>{if(!Array.isArray(e?.branches))return!1;for(let n of e.branches){let r=xu(n);if(r!==dt.never){if(t(n))return!0;if(r===dt.always)return!1}}return!1},is=e=>os(e,t=>Object.entries(t?.actions??{}).some(([n,r])=>n==="conditional"?is(r):Eu.has(n))),ss=(e,t,n)=>os(t,r=>Object.entries(r?.actions??{}).some(([o,i])=>o==="sectionTransition"?rs(e,i,n):o==="conditional"?ss(e,i,n):!1)),vu=(e,t,n)=>{if(!t)return!0;let r=Au(n,e)?.actions;if(!$(r))return!0;if(rs(n,r.sectionTransition,t))return!1;let o=r.conditional;return o?!(ss(n,o,t)||!(r.choice?.resourceId||r.form?.resourceId)&&!is(o)&&ns(wu(n,e),t)):!0},Cu=(e,t,n)=>{if(!$(e)||!Array.isArray(e.timeline))return $t({pointer:t,replayStartIndex:1});let r=new WeakSet,o=e.timeline.flatMap((c,u)=>{if(!$(c))return[];try{let d=ts(c,n,`rollback.timeline[${u}]`),f=mn({sectionId:d.sectionId,lineId:d.lineId,rollbackPolicy:c.rollbackPolicy,returnable:c.returnable});typeof c.returnable=="boolean"&&r.add(f);let p=es(N(c.executedActions));return p&&(f.executedActions=p),[f]}catch{return[]}});if(o.length===0)return $t({pointer:t,replayStartIndex:1});e.returnabilityVersion!==$r&&o.forEach((c,u)=>{!r.has(c)&&!vu(c,o[u+1],n)&&(c.returnable=!1)});let s=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):o.length-1;(s<0||s>=o.length)&&(s=o.length-1);let l=o[s];if(l?.sectionId!==t.sectionId||l?.lineId!==t.lineId){let c=o.findLastIndex(u=>u.sectionId===t.sectionId&&u.lineId===t.lineId);c>=0?s=c:(o.push(mn({sectionId:t.sectionId,lineId:t.lineId})),s=o.length-1)}let a=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),s):0;return{currentIndex:s,isRestoring:!1,replayStartIndex:a,timeline:o}},Su=(e,t,n)=>{if(!$(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=Pr(t),o=ts(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!$(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);if(e.runtime!==void 0&&!$(e.runtime))throw new Error(`Malformed save slot contexts[${n}].runtime entry.`);let i=e.variables?st(N(e.variables),t.resources?.variables??{}):{},s=Fu({loadedContextRuntime:$(e.runtime)?N(e.runtime):{}}),l={currentPointerMode:"read",pointers:{read:o},configuration:$(e.configuration)?N(e.configuration):{},views:Array.isArray(e.views)?N(e.views):[],bgm:$(e.bgm)?N(e.bgm):{resourceId:void 0},variables:{...r,...i},rollback:Cu(e.rollback,o,t)};return s&&(l.runtime=s),l},_u=(e,t)=>{if(!$(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((n,r)=>Su(n,t,r))}},Ru=(e,t)=>{if(!$(e))throw new Error("Malformed save slot.");let n=Zi(e.formatVersion);return{...e,formatVersion:n,state:_u(e.state,t)}},Hi=(e,t,{required:n=!1}={})=>{if(e===void 0){if(n)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let r=N(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},Ou=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Hi(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Hi(e.cancelActions,"cancelActions")}},ht=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},ku=e=>($(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),mt=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},as=e=>{if(!(!$(e)||!e.animations))return{animations:N(e.animations)}},Lu=(e,t)=>{let n=as(t);if(n){e.global.pendingScreenTransition=n;return}delete e.global.pendingScreenTransition},$u=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},Tu=(e,t)=>{let n=e?.sectionId,r=e?.lineId;if(!(!n||!r||!t))return`${n}:${r}:${t}`},hn=e=>String(e??""),cs=(e,t)=>{let n=hn(t);return e?.trim===!0?n.trim():n},Du=e=>$(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>$(t)).map(([t,n])=>[t,{id:t,...N(n)}])):{},Nu=(e,t)=>{if(!t||!$(e.global.formDrafts))return;let n=e.global.formDrafts[t];return $(n)?n:void 0},ls=(e,t)=>{let n=ku(e);$(n[t])||(n[t]={values:{},touched:{},errors:{},submitted:!1});let r=n[t];return $(r.values)||(r.values={}),$(r.touched)||(r.touched={}),$(r.errors)||(r.errors={}),typeof r.submitted!="boolean"&&(r.submitted=!1),r},Dr=(e,t)=>{let n=cs(e,t);return e?.required===!0&&n.length===0?"required":null},Pu=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let r=le({state:e},{sectionId:t.sectionId})?.lines||[],o=r.findIndex(i=>i.id===t.lineId);return o<0?{}:Ye(r.slice(0,o+1).map(i=>i.actions||{}))},Vu=({state:e,form:t,pointer:n})=>{if(!t?.resourceId)return null;let r=$u(t),o=Tu(n,r);if(!r||!o)return null;let i=Nu(e,o),s=Du(t),l=bn({state:e}),a={},c=[],u={},d=!0;return Object.entries(s).forEach(([f,p])=>{let h=hn(l?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},f)?hn(i.values[f]):h,b=i?.touched?.[f]===!0,A=Dr(p,g),w=i?.submitted||b?A:null,C=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,R={id:f,variableId:p.variableId,value:g,initialValue:h,valid:!A,error:w,touched:b,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...C!==void 0?{maxLength:C}:{}};A&&(d=!1),a[f]=R,c.push(R),u[f]=g}),{id:r,key:o,resourceId:t.resourceId,animations:t.animations,valid:d,submitted:i?.submitted===!0,fields:a,fieldList:c,values:u,submitActions:{submitForm:{formKey:o,actions:N(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:N(t.cancelActions??{})}}}},Ze=[],Yi="line",Nr="interaction",mn=({sectionId:e,lineId:t,rollbackPolicy:n,returnable:r})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free",...typeof r=="boolean"?{returnable:r}:{}}),Pr=e=>{let{contextVariableDefaultValues:t}=Qt(e??{});return N(t)},us=()=>({...N(St)}),ds=({loadedRuntime:e,runtimeIds:t,defaults:n={},path:r})=>{if(e===void 0)return{runtimeState:N(n),hasLoadedValues:!1};if(!$(e))throw new Error(`Malformed ${r}.`);let o=N(n),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=fs(s,N(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},ju=({loadedGlobalRuntime:e={}})=>ds({loadedRuntime:e,runtimeIds:rr,defaults:Ge,path:"global.runtime"}).runtimeState,Fu=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:n}=ds({loadedRuntime:e,runtimeIds:or,defaults:us(),path:"context.runtime"});return n?t:void 0},yn=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Mu=e=>e.runtime?(or.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=N(St[t]))}),e.runtime):(e.runtime=us(),e.runtime),Bu=e=>Ko(e.global),Uu=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Bu(e)}})},zu=e=>Go[e],qu=(e,t)=>{let n=zu(e);if(n==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(n==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(n==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},fs=(e,t)=>{if(qu(e,t),e==="autoForwardSpeed"&&t<=0)throw new Error("autoForwardSpeed requires a value greater than 0");return e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t},ps=(e,t,n)=>{let r=fs(t,n);if(t in St){let o=yn(e);if(!o)return r;let i=Mu(o);return i[t]=r,r}return e.global[t]=r,r},hs=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:N(e)},configuration:{},views:[],bgm:hu(),variables:Pr(t),rollback:$t({pointer:e})}),gt=e=>e?(e.currentPointerMode="read",$(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Wu=(e,{queueRender:t=!0}={})=>{let n=e.contexts?.[e.contexts.length-1],r=n?.pointers?.read;if(!n||!r?.sectionId||!r?.lineId)return null;let o=hs({pointer:r,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,Hu(e,{queueRender:t}),o},Hu=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,ht(e),mt(e),e.global.nextLineConfig=gn(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},ms=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},$t=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[mn({sectionId:e.sectionId,lineId:e.lineId})]:[]}},tt=(e,t={})=>{if(e?.rollback)return ms(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let n=e?.pointers?.read;return e.rollback=$t({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},Vr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=tt(n);r.isRestoring||(r.currentIndex<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,r.currentIndex+1)),r.timeline.push(mn(t)),r.currentIndex=r.timeline.length-1)},Yu=({state:e})=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!Array.isArray(n?.timeline)||typeof n.currentIndex!="number"?null:{checkpointIndex:n.currentIndex,checkpoint:n.timeline[n.currentIndex]??null}},Gu=({state:e},t={})=>{let{checkpointIndex:n,checkpointIdentity:r,sectionId:o,lineId:i}=t,l=e.contexts?.[e.contexts.length-1]?.rollback;if(!Number.isInteger(n)||!Array.isArray(l?.timeline)||typeof l.currentIndex!="number")return e;let a=l.timeline[n];return(se(a)?Vn(a):a)!==r||a?.sectionId!==o||a?.lineId!==i||(a.returnable=!1),e},Ku=({state:e},t={})=>{let{slotId:n,saveSlotIdentity:r,checkpointIndex:o,sectionId:i,lineId:s}=t,l=Tt(n),a=e.global.saveSlots?.[l],c=se(a)?Vn(a):a;if(!a||c!==r)return e;let u=a.state?.contexts,d=Array.isArray(u)?u.at(-1):null,f=d?.rollback,p=f?.timeline?.[o];return!Number.isInteger(o)||f?.currentIndex!==o||d?.pointers?.read?.sectionId!==i||d?.pointers?.read?.lineId!==s||p?.sectionId!==i||p?.lineId!==s||(p.returnable=!1,f.returnabilityVersion=$r,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}})),e},Ju=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;if(!n||n.isRestoring||!Array.isArray(n.timeline)||typeof n.currentIndex!="number")return null;let r=Ze[Ze.length-1],o=typeof r?.checkpointIndex=="number"?r.checkpointIndex:n.currentIndex;return o<0||o>=n.timeline.length?null:(typeof r?.checkpointIndex!="number"&&o<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,o+1)),n.timeline[o]??null)},Xu=({state:e},t={})=>{let n=t?.source===Yi?Yi:Nr,o=e.contexts?.[e.contexts.length-1]?.rollback;return!o||o.isRestoring||!Array.isArray(o.timeline)||typeof o.currentIndex!="number"||o.currentIndex<0||o.currentIndex>=o.timeline.length?(Ze.push({checkpointIndex:null,source:n}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Ze.push({checkpointIndex:o.currentIndex,source:n}),e)},Qu=({state:e})=>(Ze.pop(),e),Ce=(e,t,n)=>{let o=Ze[Ze.length-1]?.source??Nr;if(!Af(t,o))return;let i=Ju(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:N(n)}))},Gi=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:l}of r){let a=e.projectData.resources?.variables?.[o],c=a?.scope,u=a?.type;if(De(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Zt(c,o),en(u,i,o),Qn(u,i,s,o,{roundTo:l}),c==="context"&&(n.variables[o]=tn(n.variables[o],i,s,{roundTo:l}))}},Zu=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:n,payload:r})=>{wf(e,n,r)})},ed=(e,t)=>{let{sectionId:n,lineId:r}=t,s=le({state:e},{sectionId:n})?.lines?.find(l=>l.id===r)?.actions;s&&Object.entries(s).forEach(([l,a])=>{$s(e,l,a)})},gs=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=tt(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Nt({state:e}),e.global.skipMode&&Fe({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=Pr(e.projectData),delete n.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=N(pn),e.global.overlayStack=[],ht(e),mt(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let l=i;l<=t;l++)l>i&&Tr(e),ed(e,r.timeline[l]),Zu(e,r.timeline[l]);let s=gt(n);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},td=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=n;Xi(t);let l=t.story.initialSceneId,a=t.story.scenes[l],c=a.initialSectionId,u=a.sections[c],d={sceneId:l,sectionId:c,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:f}=Qt(t),p={...f,...st(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:Iu(s,"accountViewedRegistry"),nextLineConfig:gn(),saveSlots:yu(r),overlayStack:[],variables:p,...ju({loadedGlobalRuntime:i})},contexts:[hs({pointer:d,projectData:t})]}},nd=({state:e})=>e.global.overlayStack||[],rd=({state:e})=>e.global.pendingEffects,ys=({state:e})=>e.global.skipMode,od=({state:e})=>e.global.autoMode,bs=({state:e})=>e.global.dialogueUIHidden,Is=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(!n)return[];let{sectionId:r,lineId:o}=n.pointers.read,i=le({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(d=>d.id===o),l=i.lines.slice(0,s+1),a=[],c={},u=vt({variables:{...e.global?.variables??{},...yn(e)?.variables??{}},runtime:Ke(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let d of l){let f=d.actions||{};if(c=Ye([c,f]),!f.dialogue)continue;let p=c.dialogue||{},h=Xt({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:u}),g=pu({sectionId:r,lineId:d.id,content:f.dialogue.append===!0?p.content:f.dialogue.content,dialogueState:p,characterName:h});if(f.dialogue.append===!0&&a.length>0){a[a.length-1]={...a[a.length-1],content:g.content,text:g.text,characterId:g.characterId,character:g.character,characterName:g.characterName};continue}a.push(g)}return a},id=({state:e})=>e.global.confirmDialog??null,Dt=({state:e},{pointer:t}={})=>{let n=t??Ie({state:e})?.pointer,r=Pu({state:e,pointer:n});return Vu({state:e,form:r.form,pointer:n})},sd=({state:e},{pointer:t}={})=>!!Dt({state:e},{pointer:t}),Ae=({state:e},{pointer:t}={})=>{let n=Dt({state:e},{pointer:t});if(n)return{source:je,formId:n.id,formKey:n.key};let r=As({state:e,pointer:t});return r?{source:ft,resourceId:r}:null},ad=({state:e,registry:t},n)=>{let{sectionId:r,lineId:o}=n,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===r);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let l=le({state:e},{sectionId:r});if(!l||!l.lines||!Array.isArray(l.lines))return s.lastLineId===o;let a=l.lines.findIndex(u=>u.id===s.lastLineId),c=l.lines.findIndex(u=>u.id===o);return a===-1||c===-1?s.lastLineId===o:c<=a},cd=({registry:e},t)=>{let{resourceId:n}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===n)},jr=({state:e},t)=>ad({state:e,registry:e.global.accountViewedRegistry},t),ld=({state:e},t)=>cd({registry:e.global.accountViewedRegistry},t),ud=({state:e})=>e.global.nextLineConfig,As=({state:e,pointer:t}={})=>{let n=t??Ie({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=le({state:e},{sectionId:r})?.lines||[],l=s.findIndex(c=>c.id===o);if(l<0)return;let a;for(let c of s.slice(0,l+1)){let u=c?.actions;if(u?.cleanAll&&(a=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){a=void 0;continue}let d=u.choice;if(d?.resourceId){a=d.resourceId;continue}d?.animations||(a=void 0)}return a},ws=({state:e})=>!!As({state:e}),dd=({state:e})=>structuredClone(e),Es=({state:e})=>e.global.saveSlots,fd=({state:e},t)=>{let n=t?.slotId,r=Tt(n);return e.global.saveSlots[r]},Fr=({state:e})=>Ke(e),pd=({state:e},t)=>Ne(e,t?.runtimeId),bn=({state:e})=>{let t={...e.global?.variables??{},...yn(e)?.variables??{}};return vt({variables:t,runtime:Ke(e),variableConfigs:e.projectData.resources?.variables??{}})},Ie=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(n)return{currentPointerMode:"read",pointer:n.pointers?.read}},le=({state:e},t)=>{let{sectionId:n}=t;return pt(e.projectData,n).section},In=({state:e})=>{let t=Ie({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=le({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},xs=({state:e})=>{let{sectionId:t,lineId:n}=Ie({state:e}).pointer,o=le({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n),l=o.slice(0,i+1).map(c=>{let u=c.actions||{},d={};return Object.keys(u).forEach(f=>{d[f]=u[f]}),d});return Ye(l)},hd=e=>{let t=In({state:e})?.actions?.dialogue;if(t?.clear===!0||!Array.isArray(t?.content))return"";let n=bn({state:e});return t.content.map(r=>`${at(r?.text,{variables:n})??""}`).join("")},An=({state:e})=>qi({text:hd(e),baseDelay:Ne(e,"autoForwardDelay"),speed:Ne(e,"autoForwardSpeed")}),md=({state:e})=>{let t=vs({state:e}),r=In({state:e})?.actions??{},o=Ye([t??{},r]);return Zn(t??{},o??{})},gd=({state:e},{sectionId:t})=>{let n=le({state:e},{sectionId:t});if(!n?.lines)return[];let r=[],o={};for(let i of n.lines){let s=i.actions||{},l=Ye([o,s]),a=Zn(o,l);r.push({id:i.id,changes:a,presentationState:l}),o=er(l)}return r},yd=({state:e},{sectionId:t,includePresentationState:n=!1})=>{let r=gd({state:e},{sectionId:t});return n?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},vs=({state:e})=>{let{sectionId:t,lineId:n}=Ie({state:e}).pointer,o=le({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===n);if(i<=0)return null;let l=o.slice(0,i).map(a=>{let c=a.actions||{},u={};return Object.keys(c).forEach(d=>{u[d]=c[d]}),u});return er(Ye(l))},Mr=({state:e},{slotsPerPage:t=6}={})=>{let o=((Fr({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let l=o+s,a=e.global.saveSlots&&e.global.saveSlots[Tt(l)]||{};i.push({...a,slotId:l})}return{saveSlots:i}},bd=Es,Id=Mr,Ad=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!n||!Array.isArray(n.timeline)||typeof n.currentIndex!="number"?!1:n.currentIndex>=0&&n.currentIndex<n.timeline.length-1},wd=({state:e},t={})=>{let n=xs({state:e}),r=vs({state:e}),o=In({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:N(i)}:o,l=i?.animations&&r===null?{}:r,{sectionId:a}=Ie({state:e}).pointer,{sceneId:c}=pt(e.projectData,a),u=Fr({state:e}),d=t?.activePersistentAnimations??[],f=t?.restoredPersistentAnimations??[],p=Dt({state:e}),h=ws({state:e}),g=bn({state:e}),{saveSlots:b}=Mr({state:e}),A=Ad(e);return Ci({presentationState:n,previousPresentationState:l,currentLineActions:s,resources:e.projectData.resources,currentSceneId:c,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:Ns({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||A,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:Is({state:e}),saveSlots:b,variables:g,runtime:u,activePersistentAnimations:d,restoredPersistentAnimations:f})},Ed=({state:e},t)=>(e.global.confirmDialog=Ou(t),e.global.pendingEffects.push({name:"render"}),e),xd=({state:e})=>(e.global.confirmDialog&&(ht(e),e.global.pendingEffects.push({name:"render"})),e),vd=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Ce(e,"pushOverlay",t),e),Cd=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Ce(e,"popOverlay",void 0),e),Sd=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),Ce(e,"replaceLastOverlay",t),e),_d=({state:e})=>(e.global.overlayStack=[],ht(e),mt(e),e.global.pendingEffects.push({name:"render"}),Ce(e,"clearOverlays",void 0),e),Rd=(e,{activeInteraction:t})=>{e.global.autoMode&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),t&&e.global.skipMode&&e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},wn=(e,t,{screenTransition:n}={})=>{e.global.isLineCompleted=!1,Lu(e,n),mt(e);let r=Ae({state:e},{pointer:t}),o=r?.source===ft,i=r?.source===je;return Rd(e,{activeInteraction:r}),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:r}},En=(e,t,n)=>{!(t?.source===ft||t?.source===je)||n||!e.global.skipMode||e.global.pendingEffects.push({name:"startSkipNextTimer"})},Cs=({state:e})=>(Ae({state:e})||(e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.autoMode=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.isLineCompleted&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:An({state:e})}}),e.global.pendingEffects.push({name:"render"})),e),Nt=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Od=({state:e})=>{let t=e.global.autoMode;return Ae({state:e})&&!t||(t?Nt({state:e}):Cs({state:e})),e},Ss=({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),Fe=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),kd=({state:e})=>{let t=ys({state:e});return Ae({state:e})&&!t||(t?Fe({state:e}):Ss({state:e})),e},xn=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Ce(e,"showDialogueUI",void 0),e),_s=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Ce(e,"hideDialogueUI",void 0),e),Ld=({state:e})=>(bs({state:e})?xn({state:e}):_s({state:e}),e),Me=(e,t,n)=>(ps(e,t,n),Uu(e),e.global.pendingEffects.push({name:"render"}),e),Pt=(e,t,n,r)=>{let o=ps(e,t,n);return e.global.pendingEffects.push({name:"render"}),Ce(e,r,{value:o}),e},$d=({state:e},t)=>Me(e,"dialogueTextSpeed",t?.value),Td=({state:e},t)=>Me(e,"autoForwardDelay",t?.value),Dd=({state:e},t)=>Me(e,"autoForwardSpeed",t?.value),Nd=({state:e},t)=>Me(e,"skipUnseenText",t?.value),Pd=({state:e},t)=>Me(e,"skipTransitionsAndAnimations",t?.value),Vd=({state:e},t)=>Me(e,"soundVolume",t?.value),jd=({state:e},t)=>Me(e,"musicVolume",t?.value),Fd=({state:e},t)=>Me(e,"muteAll",t?.value),Md=({state:e},t)=>Pt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),Bd=({state:e})=>{let t=Ne(e,"saveLoadPagination")+1;return Pt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},Ud=({state:e})=>{let t=Ne(e,"saveLoadPagination")-1;return Pt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},zd=({state:e},t)=>Pt(e,"menuPage",t?.value,"setMenuPage"),qd=({state:e},t)=>Pt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Wd=({state:e})=>(e.global.pendingEffects=[],e),Hd=({state:e},t)=>(e.global.pendingEffects.push(t),e),Rs=(e,{sectionId:t,resetStoryState:n=!1,screen:r})=>{let o=!!as(r),i=le({state:e},{sectionId:t});if(!i)return console.warn(`Section not found: ${t}`),e;let s=i.lines?.[0];if(!s)return console.warn(`Section ${t} has no lines`),e;if(n&&!Wu(e,{queueRender:!o}))return e;let l=Ae({state:e});n&&e.global.skipMode&&Fe({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let u=gt(a),d=u.read;n||et(e,{sectionId:d?.sectionId,lineId:d?.lineId}),a.rollback||tt(a,{compatibilityAnchor:!0}),u.read={sectionId:t,lineId:s.id},n?a.rollback=$t({pointer:u.read}):Vr(e,{sectionId:t,lineId:s.id})}let{activeInteraction:c}=wn(e,a?.pointers?.read,{screenTransition:r});return En(e,l,c),e},Yd=({state:e},t)=>Rs(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),Os=e=>(e.global.accountViewedRegistry=du(e.global.accountViewedRegistry),e.global.accountViewedRegistry),Br=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(n=>({scope:n.scope,path:n.path,op:n.op,value:N(n.value)}))}})},ks=(e,t)=>{Br(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(n=>({sectionId:n.sectionId,...n.lastLineId===void 0?{}:{lineId:n.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},Gd=(e,t,{sectionId:n,lineId:r})=>{if(!n||!r)return!1;let o=$(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===n);if(i){if(i.lastLineId===void 0)return!1;let s=le({state:e},{sectionId:n});if(s?.lines){let l=s.lines.findIndex(c=>c.id===i.lastLineId),a=s.lines.findIndex(c=>c.id===r);if(l===-1||a>l)return i.lastLineId===r?!1:(i.lastLineId=r,!0)}else return i.lastLineId===r?!1:(i.lastLineId=r,!0);return!1}else return o.sections.push({sectionId:n,lastLineId:r}),!0},et=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;Gd(e,Os(e),t)&&ks(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},Kd=({state:e},t)=>(et(e,t),e.global.pendingEffects.push({name:"render"}),e),Jd=({state:e},t)=>{let{resourceId:n}=t;if(e.global.accountViewedRegistry!==void 0){let r=Os(e);r.resources.find(i=>i.resourceId===n)||(r.resources.push({resourceId:n}),ks(e,{sections:[],resources:[{resourceId:n}]}))}return e.global.pendingEffects.push({name:"render"}),e},Ls=({state:e},t)=>{let n=mu(t.manual),{auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;n&&r?(e.global.nextLineConfig={manual:n,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let a=e.global.nextLineConfig.auto?.enabled,c=Ae({state:e});return!l&&!c&&a===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!l&&a===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),Ce(e,"setNextLineConfig",t),e},Xd=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:r}=t,o=t?.savedAt,i=Tt(n),s=N(e.contexts);s?.forEach(c=>{gt(c),ms(c.rollback),bu(c.rollback)});let l={contexts:s},a={formatVersion:Ki,slotId:Qi(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:l};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Qd=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=Tt(n),o=e.global.saveSlots[r];if(o){let i=Ru(o,e.projectData);e.contexts=i.state.contexts,e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=gn(),e.global.overlayStack=[],e.global.isLineCompleted=!0,ht(e),mt(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},Zd=({state:e},t)=>{let{projectData:n}=t;Xi(n),e.projectData=n;let r=n?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=Qt(n??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...st(e.global.variables,r)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...st(s.variables,r)})}),ht(e),mt(e),e.global.pendingEffects.push({name:"render"}),e},ef=({state:e},t)=>{let{sectionId:n,lineId:r}=t;if(!r)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=n||o.pointers.read?.sectionId;if(n&&!le({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=le({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(d=>d.id===r))return console.warn(`Line not found: ${r} in section ${i}`),e;let a=Ae({state:e}),c=gt(o);c.read={sectionId:i,lineId:r};let{activeInteraction:u}=wn(e,c.read);return En(e,a,u),e},tf=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return xn({state:e}),e;let n=Ae({state:e});if(n?.source===ft&&t?.bypassChoice!==!0||n?.source===je&&t?._interactionSource!==je)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=Ie({state:e})?.pointer,d=u?.sectionId,f=u?.lineId;d&&f&&et(e,{sectionId:d,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&!n&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:An({state:e})}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&!n&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let r=Ie({state:e})?.pointer,o=r?.sectionId,i=le({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],l=i?.lines||[],c=l.findIndex(u=>u.id===r?.lineId)+1;if(c<l.length){let u=l[c],d=!Ne(e,"skipUnseenText");if(e.global.skipMode&&d&&!jr({state:e},{sectionId:o,lineId:u.id}))return Fe({state:e}),e;if(s&&!s.rollback&&tt(s,{compatibilityAnchor:!0}),s){let p=gt(s),h=p.read?.lineId;h&&o&&et(e,{sectionId:o,lineId:h}),p.read={sectionId:o,lineId:u.id}}Vr(e,{sectionId:o,lineId:u.id}),Tr(e);let{activeInteraction:f}=wn(e,{sectionId:o,lineId:u.id});En(e,n,f)}else e.global.autoMode&&Nt({state:e}),e.global.skipMode&&Fe({state:e});return e},nf=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ae({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:An({state:e})}});let n=Ie({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&et(e,{sectionId:r,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},rf=({state:e},t)=>Rs(e,{sectionId:t?.sectionId,screen:t?.screen}),of=({state:e},t)=>{let n=t?._conditionalContinuation===!0;if(e.global.dialogueUIHidden&&!n)return xn({state:e}),e;let r=Ae({state:e});if(r?.source===ft&&t?.bypassChoice!==!0||r?.source===je&&t?._interactionSource!==je||r&&r.source!==ft&&r.source!==je)return e;let o=Ie({state:e})?.pointer,i=o?.sectionId,s=le({state:e},{sectionId:i}),l=e.contexts[e.contexts.length-1],a=s?.lines||[],u=a.findIndex(d=>d.id===o?.lineId)+1;if(u<a.length){let d=a[u],f=!Ne(e,"skipUnseenText");if(e.global.skipMode&&f&&!jr({state:e},{sectionId:i,lineId:d.id})&&(Fe({state:e}),!n))return e;if(l&&!l.rollback&&tt(l,{compatibilityAnchor:!0}),l){let h=gt(l),g=h.read?.lineId;g&&i&&et(e,{sectionId:i,lineId:g}),h.read={sectionId:i,lineId:d.id}}Vr(e,{sectionId:i,lineId:d.id}),Tr(e);let{activeInteraction:p}=wn(e,{sectionId:i,lineId:d.id});En(e,r,p)}else e.global.autoMode&&Nt({state:e}),e.global.skipMode&&Fe({state:e}),e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},Ur=(e,t={})=>{let n=Dt({state:e});return!n||t.formKey&&t.formKey!==n.key||t.formId&&t.formId!==n.id?null:n},sf=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let n=e.projectData.resources?.variables?.[t.variableId],r=n?.scope,o=n?.type;if(De(n))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(n?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return Zt(r,t.variableId),en(o,"set",t.variableId),{variableConfig:n,scope:r}},af=(e,t)=>({id:e.id,key:e.key,valid:!0,values:N(t),fields:N(e.fields),fieldList:N(e.fieldList)}),cf=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ie({state:e})?.pointer,n=t?.sectionId,r=t?.lineId;n&&r&&et(e,{sectionId:n,lineId:r})},lf=({state:e},t={})=>{let n=Ur(e,t),r=t.field;if(!n?.fields?.[r])return e;let o=ls(e,n.key),i=hn(t.value),s=n.fields[r],l=Dr(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},uf=({state:e},t={})=>{let n=Ur(e,t);if(!n)return{submitted:!1,valid:!1,reason:"inactive"};let r=ls(e,n.key);r.submitted=!0;let o={},i={};if(Object.entries(n.fields).forEach(([d,f])=>{let p=Object.prototype.hasOwnProperty.call(r.values,d)?r.values[d]:f.value,h=Dr(f,p);r.touched[d]=!0,h&&(i[d]=h),o[d]=cs(f,p)}),r.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:N(i),form:{id:n.id,key:n.key,values:N(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let l=!1,a=[],c=[];Object.entries(n.fields).forEach(([d,f])=>{let{scope:p}=sf(e,f),h=p==="context"?s.variables:e.global.variables,g=o[d];h[f.variableId]=tn(h[f.variableId],"set",g),p==="context"&&(l=!0,c.push({variableId:f.variableId,op:"set",value:g})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${f.variableId}`,op:"set",value:N(h[f.variableId])})}),l&&Ce(e,"updateVariable",{id:"submitForm",operations:c}),Br(e,a);let u=af(n,o);return cf(e),delete e.global.formDrafts[n.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},df=({state:e},t={})=>{let n=Ur(e,t);return n?(delete e.global.formDrafts?.[n.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:n.id,key:n.key,values:N(n.values),fields:N(n.fields),fieldList:N(n.fieldList)}}):{cancelled:!1,reason:"inactive"}},ff=({state:e},t)=>{let{id:n,operations:r=[]}=t;if(!n)throw new Error("updateVariable requires an id field");if(typeof n!="string"||!/^[a-zA-Z0-9]+$/.test(n))throw new Error(`updateVariable id must be alphanumeric, got: "${n}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],l=[];return r.forEach(({variableId:a,op:c,value:u,roundTo:d})=>{let f=e.projectData.resources?.variables?.[a],p=f?.scope,h=f?.type;if(De(f))throw new Error(`Cannot update computed variable: ${a}`);if(f?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);Zt(p,a),en(h,c,a),Qn(h,c,u,a,{roundTo:d});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let b={variableId:a,op:c,value:u};d!==void 0&&(b.roundTo=d),l.push(b)}g[a]=tn(g[a],c,u,{roundTo:d}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:N(g[a])})}),i&&Ce(e,"updateVariable",{id:n,operations:l}),Br(e,s),e.global.pendingEffects.push({name:"render"}),e},pf=e=>(t,n)=>e({state:t},n),hf=e=>({variables:vt({variables:{...e.global?.variables??{},...yn(e)?.variables??{}},runtime:Ke(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:Ke(e)}),mf=e=>{if(!$(e))throw new Error("conditional action payload must be an object");if(!Array.isArray(e.branches))throw new Error("conditional action requires branches array");if(e.branches.length===0)throw new Error("conditional action requires at least one branch")},gf=(e,t,n)=>{if(!$(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!$(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==n-1)throw new Error("conditional else branch must be the last branch")},yf=(e,t)=>{mf(t);for(let n=0;n<t.branches.length;n+=1){let r=t.branches[n];if(gf(r,n,t.branches.length),!(Object.prototype.hasOwnProperty.call(r,"when")&&!xt(r.when,hf(e)))){Object.entries(r.actions).forEach(([i,s])=>{$s(e,i,s)});return}}},bf={conditional:{replayLine:yf},updateVariable:{recordSources:[Nr],replayLine:Gi,replayRecorded:Gi,persistInSaveSlot:!0},setNextLineConfig:{replayLine:pf(Ls)}},vn=e=>bf[e]??null,If=e=>vn(e)?.persistInSaveSlot===!0,Af=(e,t)=>{let n=vn(e)?.recordSources;return Array.isArray(n)&&n.includes(t)},wf=(e,t,n)=>{vn(t)?.replayRecorded?.(e,n)},$s=(e,t,n)=>{vn(t)?.replayLine?.(e,n)},Ef=e=>e?.returnable!==!1,Ts=(e,t)=>{if(t>=0)return e.currentIndex+t;let n=Math.abs(t);for(let r=e.currentIndex-1;r>=0;r-=1)if(Ef(e.timeline[r])&&(n-=1,n===0))return r;return-1},Ds=({state:e},t)=>{let{offset:n}=t;if(n===void 0||typeof n!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let r=e.contexts[e.contexts.length-1];if(!r)return null;let o=r.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=Ts(o,n);if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},Ns=({state:e})=>Ds({state:e},{offset:-1})!==null,xf=({state:e},t)=>{let{offset:n=-1}=t;if(n>=0)throw new Error("rollbackByOffset requires a negative offset");let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let o=tt(r,{compatibilityAnchor:!r.rollback}),i=Ts(o,n);return i<0||i>=o.timeline.length?e:gs(e,i)},vf=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=tt(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===n&&a.lineId===r);if(l===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return l===i.currentIndex?e:gs(e,l)},Ps=e=>{let t=td(e);return $o(t,{selectPendingEffects:rd,selectSkipMode:ys,selectAutoMode:od,selectIsChoiceVisible:ws,selectIsFormVisible:sd,selectActiveInteraction:Ae,selectActiveForm:Dt,selectDialogueUIHidden:bs,selectDialogueHistory:Is,selectConfirmDialog:id,selectIsLineAccountViewed:jr,selectIsResourceAccountViewed:ld,selectNextLineConfig:ud,selectSystemState:dd,selectSaveSlotMap:Es,selectSaveSlots:bd,selectSaveSlot:fd,selectRuntime:Fr,selectRuntimeValue:pd,selectAllVariables:bn,selectCurrentPointer:Ie,selectSection:le,selectCurrentLine:In,selectPresentationState:xs,selectAutoForwardTimerDelay:An,selectPresentationChanges:md,selectSectionLineChanges:yd,selectSaveSlotPage:Mr,selectCurrentPageSlots:Id,selectRenderState:wd,selectOverlayStack:nd,selectLineIdByOffset:Ds,selectCanRollback:Ns,selectRollbackCursor:Yu,startAutoMode:Cs,stopAutoMode:Nt,toggleAutoMode:Od,startSkipMode:Ss,stopSkipMode:Fe,toggleSkipMode:kd,showDialogueUI:xn,hideDialogueUI:_s,toggleDialogueUI:Ld,setDialogueTextSpeed:$d,setAutoForwardDelay:Td,setAutoForwardSpeed:Dd,setSkipUnseenText:Nd,setSkipTransitionsAndAnimations:Pd,setSoundVolume:Vd,setMusicVolume:jd,setMuteAll:Fd,setSaveLoadPagination:Md,incrementSaveLoadPagination:Bd,decrementSaveLoadPagination:Ud,setMenuPage:zd,setMenuEntryPoint:qd,showConfirmDialog:Ed,hideConfirmDialog:xd,resetStoryAtSection:Yd,clearPendingEffects:Wd,appendPendingEffect:Hd,beginRollbackActionBatch:Xu,endRollbackActionBatch:Qu,markRollbackCheckpointTransient:Gu,markSavedRollbackCheckpointTransient:Ku,addViewedLine:Kd,addViewedResource:Jd,setNextLineConfig:Ls,saveSlot:Xd,loadSlot:Qd,updateProjectData:Zd,sectionTransition:rf,jumpToLine:ef,nextLine:tf,markLineCompleted:nf,rollbackToLine:vf,rollbackByOffset:xf,pushOverlay:vd,popOverlay:Cd,replaceLastOverlay:Sd,clearOverlays:_d,updateFormField:lf,submitForm:uf,cancelForm:df,updateVariable:ff,nextLineFromSystem:of},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var Cf="route-engine",Sf="projectPersistence";var js=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),ne=e=>Object.prototype.toString.call(e)==="[object Object]",Vs="variables.",_f=(e={})=>{let t=ne(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!ne(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lineId=="string"?{lineId:n.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!ne(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},Rf=(e={})=>{let t=ne(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!ne(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lastLineId=="string"?{lastLineId:n.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!ne(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},Of=(e,t)=>{let n=Rf(e),r=_f(t),o=n.sections.map(s=>({...s})),i=n.resources.map(s=>({...s}));return r.sections.forEach(s=>{let l=o.find(a=>a.sectionId===s.sectionId);if(!l){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(l.lastLineId!==void 0){if(s.lineId===void 0){delete l.lastLineId;return}l.lastLineId=s.lineId}}),r.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},Fs=(e={})=>{let t=ne(e)?e:{};return{saveSlots:ne(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:ne(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:ne(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:ne(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:ne(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},kf=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,n)=>{if(!ne(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${n}] entry.`);let r=t.path?.startsWith(Vs)?t.path.slice(Vs.length):null;if(r!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(r.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${n}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:r}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${n}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${n}].`)})},Lf=(e,t)=>{let n={};return kf(t).forEach(r=>{if(r.path==="viewedRegistry"){n.accountViewedRegistry=Of(n.accountViewedRegistry??e.accountViewedRegistry,r.value);return}let o=r.scope==="device"?"globalDeviceVariables":"globalAccountVariables";n[o]={...e[o],...n[o],[r.variableId]:r.value}}),n},zr=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},$f=e=>{let t=zr(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Tf=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},Df=({indexedDB:e,databaseName:t,objectStoreName:n})=>new Promise((r,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(n)||s.createObjectStore(n,{keyPath:"namespace"})},i.onsuccess=()=>{r(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),Nf=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let a=r.transaction(t,"readonly").objectStore(t).get(n);a.onsuccess=()=>{o(a.result??null)},a.onerror=()=>{i(a.error??new Error(`Failed to read persisted namespace "${n}" from IndexedDB.`))}})},Vt=async({databasePromise:e,objectStoreName:t,namespace:n,patch:r})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),a=l.objectStore(t),c=a.get(n),u=!1,d=p=>{u||(u=!0,s(p))},f=()=>{u||(u=!0,i())};c.onerror=()=>{d(c.error??new Error(`Failed to read persisted namespace "${n}" before updating IndexedDB.`))},c.onsuccess=()=>{let p=Fs(c.result),h=typeof r=="function"?r(p):r,g={namespace:n,version:1,...js(),...p,...h},b=a.put(g);b.onerror=()=>{d(b.error??new Error(`Failed to persist namespace "${n}" to IndexedDB.`))}},l.oncomplete=()=>{f()},l.onerror=()=>{d(l.error??new Error(`IndexedDB transaction failed while updating namespace "${n}".`))},l.onabort=()=>{d(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${n}".`))}})},Pf=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let s=r.transaction(t,"readwrite"),a=s.objectStore(t).delete(n),c=!1,u=f=>{c||(c=!0,i(f))},d=()=>{c||(c=!0,o())};a.onerror=()=>{u(a.error??new Error(`Failed to clear persisted namespace "${n}" from IndexedDB.`))},s.oncomplete=()=>{d()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${n}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${n}".`))}})},qr=(e={})=>{let{indexedDB:t,databaseName:n=Cf,objectStoreName:r=Sf,namespace:o}=e,i=Tf(t),s=$f(o),l=Df({indexedDB:i,databaseName:n,objectStoreName:r});return{namespace:s,load:async()=>{let a=await Nf({databasePromise:l,objectStoreName:r,namespace:s});return{...js(),...Fs(a)}},clear:async()=>Pf({databasePromise:l,objectStoreName:r,namespace:s}),saveSlots:async a=>Vt({databasePromise:l,objectStoreName:r,namespace:s,patch:{saveSlots:ne(a)?a:{}}}),saveGlobalDeviceVariables:async a=>Vt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:ne(a)?a:{}}}),saveGlobalAccountVariables:async a=>Vt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalAccountVariables:ne(a)?a:{}}}),saveGlobalRuntime:async a=>Vt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalRuntime:ne(a)?a:{}}}),applyScopedDataUpdates:async a=>Vt({databasePromise:l,objectStoreName:r,namespace:s,patch:c=>Lf(c,a)})}},Vf=qr;var jf=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Ff=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),Ms="conditional",Yr=Symbol("conditionalAutoContinue"),Mf=new Set(["sectionTransition","resetStoryAtSection"]),Bf=new Set(["nextLine","nextLineFromSystem","resetStoryAtSection","sectionTransition"]),Uf=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),Wr="form",zf=new Set(["submitForm","cancelForm"]),jt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Cn=e=>e?.type===Yr,Hr=(e,t)=>e?.sectionId===t?.sectionId&&e?.lineId===t?.lineId;function Gr(e){let t,n=0,r=null,o=0,i=!1,s=0,l=[],a=null,c=new Map,u=new Map,d=new Map,{handlePendingEffects:f}=e,p=(y=new Map,I=Date.now())=>new Map(Array.from(y.entries()).filter(([,x])=>I<x.expiresAt).map(([x,_])=>[x,{animation:structuredClone(_.animation),startedAt:_.startedAt,expiresAt:_.expiresAt}])),h=(y=new Map)=>Array.from(y.values()).map(I=>structuredClone(I.animation)),g=(y=Date.now())=>{c=new Map(Array.from(c.entries()).filter(([,I])=>y<I.expiresAt))},b=()=>{if(!(o>0||i)){i=!0;try{for(;t.selectPendingEffects().length>0;){let y=[...t.selectPendingEffects()];t.clearPendingEffects();try{f(y)}catch(I){throw t.clearPendingEffects(),y.forEach(x=>{t.appendPendingEffect(x)}),I}}}finally{i=!1}}},A=y=>{o+=1;try{return y()}finally{o-=1,b()}},w=({initialState:y,namespace:I})=>{t=Ps(y),n=0,r=zr(I),o=0,i=!1,s=0,l=[],a=null,c=new Map,u=new Map,d=new Map,t.appendPendingEffect({name:"handleLineActions"}),b()},C=()=>r,R=()=>t.selectPresentationState(),P=()=>t.selectPresentationChanges(),V=y=>t.selectSectionLineChanges(y),E=(y={})=>{n+=1;let I=Date.now();g(I);let x=u.size>0,_=p(c,I),T=x?p(u,I):new Map,z={...t.selectRenderState({activePersistentAnimations:h(_),restoredPersistentAnimations:h(T)}),id:`render-${n}`};return d.set(z.id,{builtAt:I,persistentAnimationSessions:new Map([...T.entries(),..._.entries()]),usedRestoredPersistentAnimationSessions:x}),z},M=(y={})=>E(y),B=(y={})=>E(y),J=y=>{let I=typeof y?.id=="string"&&y.id.length>0?y.id:null,x=I?d.get(I):null;I&&d.delete(I);let _=new Map;li(y?.animations).forEach(T=>{let W=cn(T);if(!W)return;let z=x?.persistentAnimationSessions?.get(W)??c.get(W),rt=Math.max(0,di(T)),yt=z?.startedAt??x?.builtAt??Date.now();_.set(W,{animation:structuredClone(T),startedAt:yt,expiresAt:yt+rt})}),c=_,x?.usedRestoredPersistentAnimationSessions&&(u=new Map)},F=()=>t.selectSystemState(),H=()=>t.selectSaveSlotMap(),G=y=>t.selectSaveSlot(y),Z=y=>t.selectSaveSlotPage(y),Se=()=>t.selectSkipMode(),ue=()=>t.selectAutoMode(),ee=()=>t.selectRuntime(),re=()=>t.selectIsChoiceVisible(),de=()=>t.selectIsFormVisible(),X=()=>t.selectActiveInteraction(),oe=()=>t.selectPendingEffects().some(y=>y?.name==="handleLineActions"||y?.name==="render"),ie=(y,I,x={})=>!jt(I)||y!=="nextLine"?I:x.bypassChoice===!0?{...I,bypassChoice:!0}:x.interactionSource===Wr?{...I,_interactionSource:Wr}:I,S=(y={})=>({type:Yr,payload:ie("nextLine",{_conditionalContinuation:!0},y)}),O=(y,I)=>Cn(y)?{type:Yr,payload:{...y.payload,...I.payload}}:I,j=y=>{y.savedCheckpointOccurrences.forEach(I=>{t.markSavedRollbackCheckpointTransient(I)}),y.savedCheckpointOccurrences=[]},fe=(y,I)=>{let x=a;return a=null,!x||!Hr(x.pointer,y)||x.checkpointIndex!==I?.checkpointIndex||x.checkpointIdentity!==I?.checkpoint?[]:x.savedCheckpointOccurrences},te=y=>{y.markCurrentCheckpointTransient&&(t.markRollbackCheckpointTransient({checkpointIndex:y.rollbackCursor?.checkpointIndex,checkpointIdentity:y.rollbackCursor?.checkpoint,sectionId:y.pointer?.sectionId,lineId:y.pointer?.lineId}),j(y))},U=(y,I,x)=>Bf.has(y)?y==="resetStoryAtSection"?x?.checkpoint!==I?.checkpoint:x?.checkpoint!==I?.checkpoint&&x?.checkpointIndex>I?.checkpointIndex:!1,Be=y=>{let I=l.at(-1);if(!I?.markCurrentCheckpointTransient)return;let x=t.selectSaveSlot({slotId:y?.slotId});x&&I.savedCheckpointOccurrences.push({slotId:y.slotId,saveSlotIdentity:x,checkpointIndex:I.rollbackCursor?.checkpointIndex,sectionId:I.pointer?.sectionId,lineId:I.pointer?.lineId})},nt=(y,I,x)=>{let _=l.at(-1);if(!_)return;let T=t.selectCurrentPointer()?.pointer,W=U(y,I,x);if(Hr(_.pointer,T)){let z=x?.checkpoint!==I?.checkpoint||x?.checkpointIndex!==I?.checkpointIndex;(W||z&&Uf.has(y))&&(te(_),_.pointer=T,_.rollbackCursor=x,_.markCurrentCheckpointTransient=W,_.savedCheckpointOccurrences=[]);return}te(_),_.pointer=T,_.rollbackCursor=t.selectRollbackCursor?.()??null,_.markCurrentCheckpointTransient=W,_.savedCheckpointOccurrences=[]},Ft=(y,I)=>{if(!t[y])return;Mf.has(y)&&(s+=1),jf.has(y)&&(Ff.has(y)?u=p(c):u=new Map,c=new Map);let x=t.selectRollbackCursor?.()??null,_=t[y](I),T=t.selectRollbackCursor?.()??null;return y==="saveSlot"&&Be(I),nt(y,x,T),b(),_},zs=(y,I,x)=>{let _=t.selectCurrentPointer()?.pointer;I!==_||x!==s||(t.appendPendingEffect({name:"clearAutoNextTimer"}),t.appendPendingEffect({name:"clearNextLineConfigTimer"}),Ft("nextLineFromSystem",y.payload))},Jr=(y,I={})=>A(()=>{let x,_=t.selectCurrentPointer()?.pointer??null,T=t.selectRollbackCursor?.()??null,W=s,z={pointer:_,rollbackCursor:T,markCurrentCheckpointTransient:I.rollbackSource==="line",savedCheckpointOccurrences:I.savedCheckpointOccurrences?.slice()??[]};l.push(z);try{t.beginRollbackActionBatch({source:I.rollbackSource});try{x=y()}finally{t.endRollbackActionBatch({})}Cn(x)&&zs(x,_,W)}finally{l.pop(),(!Hr(_,z.pointer)||T?.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})}}),Xr=(y,I,x,_={})=>{if(y===Ms)return Jr(()=>{let T=_n(x),W=tr({[y]:I},T);return Qr(W[y],x,_)},_);Ft(y,I)},qs=(y,I)=>{Xr(y,I)},_n=y=>{if(!y)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(y,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:I,...x}=y,_=t.selectAllVariables?t.selectAllVariables():void 0;return{...x,_event:I,variables:_,runtime:t.selectRuntime?t.selectRuntime():{}}},Ws=y=>{if(!jt(y))throw new Error("conditional action payload must be an object");if(!Array.isArray(y.branches))throw new Error("conditional action requires branches array");if(y.branches.length===0)throw new Error("conditional action requires at least one branch")},Hs=(y,I,x)=>{if(!jt(y))throw new Error(`conditional branch at index ${I} must be an object`);if(!jt(y.actions))throw new Error(`conditional branch at index ${I} requires actions object`);if(!Object.prototype.hasOwnProperty.call(y,"when")&&I!==x-1)throw new Error("conditional else branch must be the last branch")},Qr=(y,I,x)=>{Ws(y);let _=S(x);for(let T=0;T<y.branches.length;T+=1){let W=y.branches[T];Hs(W,T,y.branches.length);let z=_n(I);if(Object.prototype.hasOwnProperty.call(W,"when")&&!xt(W.when,z))continue;let yt=Rn(W.actions,I,x);return Cn(yt)?O(_,yt):_}return _},Ys=(y,I)=>({...y??{},_form:I}),Gs=(y,I,x,_)=>{let T=Ft(y,I),W=T?.submitted===!0&&T.valid===!0,z=T?.cancelled===!0;if(!(!W&&!z)&&jt(I.actions))return Rn(I.actions,Ys(x,T.form),{..._,interactionSource:Wr})},Ks=(y,I,x,_)=>{let T=_n(x),z=tr({[y]:I},T)[y];if(y===Ms)return Qr(z,x,_);let rt=ie(y,z,_);if(zf.has(y))return Gs(y,rt,x,_);Ft(y,rt)},Rn=(y,I,x)=>{let _;return Object.entries(y).forEach(([T,W])=>{let z=Ks(T,W,I,x);Cn(z)&&(_=O(_,z))}),_},Zr=(y,I,x={})=>Jr(()=>Rn(y,I,x),x),Js=y=>{let I=t.selectCurrentPointer()?.pointer;if(y!==I||t.selectActiveInteraction())return;let x=t.selectNextLineConfig();x?.auto?.enabled&&x.auto.trigger==="fromStart"&&t.appendPendingEffect({name:"nextLineConfigTimer",payload:{delay:x.auto.delay}})};return{init:w,handleAction:Xr,handleInternalAction:qs,handleActions:Zr,selectRenderState:M,prepareRenderState:B,commitRenderState:J,selectPresentationState:R,selectPresentationChanges:P,selectSectionLineChanges:V,selectSystemState:F,selectSaveSlotMap:H,selectSaveSlot:G,selectSaveSlotPage:Z,selectSaveSlots:H,selectRuntime:ee,selectIsChoiceVisible:re,selectIsFormVisible:de,selectActiveInteraction:X,selectHasPendingRenderWork:oe,handleLineActions:()=>A(()=>{let y=t.selectCurrentPointer()?.pointer,I=t.selectRollbackCursor?.()??null,x=fe(y,I),_=t.selectCurrentLine(),T=!1;return _?.actions&&(Zr(_.actions,void 0,{rollbackSource:"line",savedCheckpointOccurrences:x}),T=!0),Js(y),T}),getNamespace:C}}var Kr=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},qf=80,Us=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{if(e.selectHasPendingRenderWork?.())return;let o=e.prepareRenderState?.(r)??e.selectRenderState(r);n?.(o),t.render(o),e.commitRenderState?.(o)},Wf=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&Us({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},Hf=({engine:e,ticker:t,autoTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(t.remove(i),n.setCallback(null),n.setElapsed(0),Sn(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Yf=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Gf=({engine:e,ticker:t,skipTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r?.delay??qf;n.getElapsed()>=l&&(n.setElapsed(0),Sn(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Kf=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Jf=({engine:e,ticker:t,nextLineConfigTimerState:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(n.setElapsed(0),Sn(e,"nextLineFromSystem",{}),t.remove(i),n.getCallback()===i&&n.setCallback(null))};n.setCallback(i),t.add(i)},Xf=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Qf=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveSlots(t?.saveSlots))},Zf=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalDeviceVariables(t?.globalDeviceVariables))},ep=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalAccountVariables(t?.globalAccountVariables))},tp=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalRuntime(t?.globalRuntime))},np=({enqueuePersistenceWrite:e},t)=>{e(n=>{if(typeof n.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return n.applyScopedDataUpdates(t?.updates)})},Bs={render:Us,saveSlots:Qf,saveGlobalDeviceVariables:Zf,saveGlobalAccountVariables:ep,saveGlobalRuntime:tp,applyScopedDataUpdates:np,handleLineActions:Wf,startAutoNextTimer:Hf,clearAutoNextTimer:Yf,startSkipNextTimer:Gf,clearSkipNextTimer:Kf,nextLineConfigTimer:Jf,clearNextLineConfigTimer:Xf},rp=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Sn=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},op=(e=[])=>{let t=new Set,n=[];for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!rp.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},ip=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let a=Kr(),c=Kr(),u=Kr(),d=s??null,f=Promise.resolve(),p=null,h=null,g=!1,b=0,A=S=>{if(o){o(S);return}console.error("RouteEngine persistence write failed.",S)},w=()=>{if(d)return d;let S=e();return d=qr({indexedDB:i,namespace:l??S?.getNamespace?.()}),d},C=S=>{f=f.catch(()=>{}).then(()=>{let O=w();return S(O)}).catch(O=>{A(O)})},R=S=>{let O=typeof S?.id=="string"&&S.id.length>0?S.id:null;b+=1,p=O,g=!1},P=()=>b,V=(S={})=>{if(S?.aborted===!0)return!1;let O=typeof S?.id=="string"&&S.id.length>0?S.id:null;return O?O!==p||O===h?!1:(h=O,!0):p!==null||g?!1:(g=!0,!0)},E=(S,O={})=>{if(S!=="renderComplete"||!V(O))return!1;let j=e();return Sn(j,"markLineCompleted",{}),!0},M=new Set(["updateFormField","submitForm","cancelForm"]),B=new Set(["updateVariable"]),J=S=>typeof S?.selectActiveInteraction=="function"?S.selectActiveInteraction():typeof S?.selectIsChoiceVisible=="function"&&S.selectIsChoiceVisible()?{source:"choice"}:null,F=S=>S?._formKey??S?.formKey,H=(S,O)=>F(S)===O?.formKey,G=(S,O)=>!S||typeof S!="object"||Array.isArray(S)?!1:S._interactionSource===O?.source,Z=(S,O)=>G(S,O)?O.source==="form"?H(S,O):!0:!1,Se=(S,O)=>!S||typeof S!="object"||Array.isArray(S)||O?.source!=="form"?!1:H(S,O),ue=(S={})=>Object.keys(S).some(O=>M.has(O)),ee=(S={},O)=>Object.entries(S).some(([j,fe])=>M.has(j)&&Se(fe,O)),re=(S={})=>Object.keys(S).length>0&&Object.keys(S).every(O=>B.has(O)),de=(S={},O)=>{let j=S?.actions;return O?.source==="form"?!j||typeof j!="object"||Array.isArray(j)?!1:ee(j,O)?!0:ue(j)?!1:re(j):Z(S,O)?!0:!j||typeof j!="object"||Array.isArray(j)?!1:Object.values(j).some(fe=>Z(fe,O))},X=(S,O={})=>{if(!O?.actions)return!1;let j=J(S);return!j||j.source==="choice"?!1:!de(O,j)},oe=({preprocessPayload:S,onEvent:O}={})=>async(j,fe={})=>{let te=e();if(X(te,fe))return O?.(j,fe);let U=await S?.(j,fe)??fe;if(X(te,U))return O?.(j,U);if(E(j,U),U?.actions){let Be=U?._event?{_event:U._event}:U?.event?{_event:U.event}:void 0,nt;U?.bypassChoice===!0?nt={bypassChoice:!0}:U?._interactionSource&&(nt={interactionSource:U._interactionSource}),nt?te.handleActions(U.actions,Be,nt):te.handleActions(U.actions,Be)}return O?.(j,U)},ie=S=>{let O=e(),j=op(S),fe=j.some(U=>U.name==="handleLineActions");j.forEach(U=>{if(!Bs[U.name]&&!r)throw new Error(`Unhandled pending effect "${U.name}".`)});let te={engine:O,routeGraphics:t,ticker:n,autoTimer:a,skipTimer:c,nextLineConfigTimerState:u,trackRenderDispatch:R,getRenderDispatchCount:P,enqueuePersistenceWrite:C};for(let U of j){if(fe&&U.name==="render")continue;let Be=Bs[U.name];if(Be){Be(te,U.payload);continue}r(U,te)}};return ie.handleRouteGraphicsEvent=E,ie.createRouteGraphicsEventHandler=oe,ie},sp=ip;var ap=(e,t={})=>{let{resources:n={}}=t;return Sr(e,n)};var Fh=Gr;export{ir as DEFAULT_VISUAL_LAYER,ct as RENDER_LAYER,_e as VISUAL_LAYER,sp as createEffectsHandler,Vf as createIndexedDbPersistence,Fh as default,oc as resolveComputedVariables,ap as resolveLayoutReferences};
|
package/package.json
CHANGED