route-engine-js 1.29.2 → 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 Ts=Object.defineProperty;var Ds=(e,t)=>{for(var r in t)Ts(e,r,{get:t[r],enumerable:!0})};var Xn=Symbol.for("immer-nothing"),Hn=Symbol.for("immer-draftable"),pe=Symbol.for("immer-state");function Ae(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var nt=Object.getPrototypeOf;function he(e){return!!e&&!!e[pe]}function ze(e){return e?Qn(e)||Array.isArray(e)||!!e[Hn]||!!e.constructor?.[Hn]||Mt(e)||Ut(e):!1}var Ps=Object.prototype.constructor.toString();function Qn(e){if(!e||typeof e!="object")return!1;let t=nt(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)===Ps}function Nt(e,t){Ft(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function Ft(e){let t=e[pe];return t?t.type_:Array.isArray(e)?1:Mt(e)?2:Ut(e)?3:0}function Sr(e,t){return Ft(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Zn(e,t,r){let n=Ft(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function Ns(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Mt(e){return e instanceof Map}function Ut(e){return e instanceof Set}function Be(e){return e.copy_||e.base_}function _r(e,t){if(Mt(e))return new Map(e);if(Ut(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=Qn(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[pe];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],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(nt(e),n)}else{let n=nt(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function kr(e,t=!1){return Bt(e)||he(e)||!ze(e)||(Ft(e)>1&&(e.set=e.add=e.clear=e.delete=Vs),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>kr(n,!0))),e}function Vs(){Ae(2)}function Bt(e){return Object.isFrozen(e)}var js={};function qe(e){let t=js[e];return t||Ae(0,e),t}var gt;function eo(){return gt}function Fs(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Yn(e,t){t&&(qe("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Rr(e){Or(e),e.drafts_.forEach(Ms),e.drafts_=null}function Or(e){e===gt&&(gt=e.parent_)}function Gn(e){return gt=Fs(gt,e)}function Ms(e){let t=e[pe];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Kn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[pe].modified_&&(Rr(t),Ae(4)),ze(e)&&(e=Vt(t,e),t.parent_||jt(t,e)),t.patches_&&qe("Patches").generateReplacementPatches_(r[pe].base_,e,t.patches_,t.inversePatches_)):e=Vt(t,r,[]),Rr(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Xn?e:void 0}function Vt(e,t,r){if(Bt(t))return t;let n=t[pe];if(!n)return Nt(t,(o,i)=>Jn(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return jt(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),Nt(i,(c,a)=>Jn(e,n,o,c,a,r,s)),jt(e,o,!1),r&&e.patches_&&qe("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function Jn(e,t,r,n,o,i,s){if(he(o)){let c=i&&t&&t.type_!==3&&!Sr(t.assigned_,n)?i.concat(n):void 0,a=Vt(e,o,c);if(Zn(r,n,a),he(a))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(ze(o)&&!Bt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Vt(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&jt(e,o)}}function jt(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&kr(t,r)}function Us(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:eo(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=Tr;r&&(o=[n],i=yt);let{revoke:s,proxy:c}=Proxy.revocable(o,i);return n.draft_=c,n.revoke_=s,c}var Tr={get(e,t){if(t===pe)return e;let r=Be(e);if(!Sr(r,t))return Bs(e,r,t);let n=r[t];return e.finalized_||!ze(n)?n:n===vr(e.base_,t)?(Cr(e),e.copy_[t]=$r(n,e)):n},has(e,t){return t in Be(e)},ownKeys(e){return Reflect.ownKeys(Be(e))},set(e,t,r){let n=to(Be(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=vr(Be(e),t),i=o?.[pe];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(Ns(r,o)&&(r!==void 0||Sr(e.base_,t)))return!0;Cr(e),Lr(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 vr(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Cr(e),Lr(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Be(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){Ae(11)},getPrototypeOf(e){return nt(e.base_)},setPrototypeOf(){Ae(12)}},yt={};Nt(Tr,(e,t)=>{yt[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});yt.deleteProperty=function(e,t){return yt.set.call(this,e,t,void 0)};yt.set=function(e,t,r){return Tr.set.call(this,e[0],t,r,e[0])};function vr(e,t){let r=e[pe];return(r?Be(r):e)[t]}function Bs(e,t,r){let n=to(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function to(e,t){if(!(t in e))return;let r=nt(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=nt(r)}}function Lr(e){e.modified_||(e.modified_=!0,e.parent_&&Lr(e.parent_))}function Cr(e){e.copy_||(e.copy_=_r(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var zs=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"&&Ae(6),n!==void 0&&typeof n!="function"&&Ae(7);let o;if(ze(t)){let i=Gn(this),s=$r(t,void 0),c=!0;try{o=r(s),c=!1}finally{c?Rr(i):Or(i)}return Yn(i,n),Kn(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===Xn&&(o=void 0),this.autoFreeze_&&kr(o,!0),n){let i=[],s=[];qe("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else Ae(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){ze(e)||Ae(8),he(e)&&(e=We(e));let t=Gn(this),r=$r(e,void 0);return r[pe].isManual_=!0,Or(t),r}finishDraft(e,t){let r=e&&e[pe];(!r||!r.isManual_)&&Ae(9);let{scope_:n}=r;return Yn(n,t),Kn(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=qe("Patches").applyPatches_;return he(e)?n(e,t):this.produce(e,o=>n(o,t))}};function $r(e,t){let r=Mt(e)?qe("MapSet").proxyMap_(e,t):Ut(e)?qe("MapSet").proxySet_(e,t):Us(e,t);return(t?t.scope_:eo()).drafts_.push(r),r}function We(e){return he(e)||Ae(10,e),ro(e)}function ro(e){if(!ze(e)||Bt(e))return e;let t=e[pe],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=_r(e,t.scope_.immer_.useStrictShallowCopy_)}else r=_r(e,!0);return Nt(r,(n,o)=>{Zn(r,n,ro(o))}),t&&(t.finalized_=!1),r}var me=new zs,Dr=me.produce,Pd=me.produceWithPatches.bind(me),Nd=me.setAutoFreeze.bind(me),Vd=me.setUseStrictShallowCopy.bind(me),jd=me.applyPatches.bind(me),Fd=me.createDraft.bind(me),Md=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},O={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},ot={NOT:0};var x=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},fe=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Pr=e=>{if(!e||e.trim()==="")throw new x("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new x(`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 x(`Incomplete comparison expression - missing right operand (got: '${e}')`)},no=e=>{if(e.trim().endsWith(" in"))throw new x(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new x(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new x(`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 x(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new x(`Invalid loop syntax (got: '$for ${e}')`)}};var oo=(e,t,r=!1)=>{if(t===null)return new fe(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new fe(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new fe(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new fe(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},io=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new fe(`Unknown function '${e}' (${r})`)};var qs=(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=L(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},L=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return G(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return G(e.path,r,n);if(e.type===m.INTERPOLATION)return Hs(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return ao(e,t,r,n);case m.BINARY:return co(e,t,r,n);case m.UNARY:return lo(e,t,r,n);case m.CONDITIONAL:return Gs(e,t,r,n);case m.LOOP:return Zs(e,t,r,n);case m.OBJECT:return ta(e,t,r,n);case m.ARRAY:return ra(e,t,r,n);case m.PARTIAL:return na(e,t,r,n);case m.PATH_REFERENCE:return oa(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},so=new Map,Ws=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},G=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=so.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=Ws(a.trim());n.push(...l)}so.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},Hs=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},ao=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw io(e.name,o);let s=e.args.map(c=>L(c,t,r,n));return i(...s)},$e=(e,t,r,n)=>{if(e.var&&!e.type)return G(e.var,r,n);switch(e.type){case m.VARIABLE:return G(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return co(e,t,r,n);case m.UNARY:return lo(e,t,r,n);case m.FUNCTION:return ao(e,t,r,n);default:return L(e,t,r,n)}},co=(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=L(e.left,t,r,n),i=L(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 fe(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case O.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new fe(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},lo=(e,t,r,n)=>{let o=e.op===ot.NOT?$e(e.operand,t,r,n):L(e.operand,t,r,n);if(e.op===ot.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Ys=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(G(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?L(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]=G(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=G(d.path,r,n);u.push(p!=null?String(p):"")}else{let p=L(d,t,r,n);u.push(p!=null?String(p):"")}c[l]=u.join("")}else c[l]=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?L(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]=G(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=G(d.path,r,n);u.push(p!=null?String(p):"")}else{let p=L(d,t,r,n);u.push(p!=null?String(p):"")}c[l]=u.join("")}else c[l]=L(f,t,r,n)}return c}}}return null},Gs=(e,t,r,n)=>{let o=Ys(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 L(e.bodies[i],t,r,n)}return uo},Ks=(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 I=y.path;if(I===n)h.push(l!=null?String(l):"");else if(I.startsWith(n+".")){let A=I.substring(n.length+1),v=l[A];h.push(v!=null?String(v):"")}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},Js=(e,t)=>{let r=e.body,n=e.itemVar,o=Ks(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},Xs=(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?L(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 I=y.path;if(I===c)u[g]=f;else if(I===a)u[g]=l;else if(I.startsWith(c+".")){let A=I.substring(c.length+1);!A.includes(".")&&!A.includes("[")?u[g]=f[A]:u[g]=G(I,r,{...n,[c]:f,...a&&{[a]:l}})}else u[g]=G(I,r,{...n,[c]:f,...a&&{[a]:l}})}else if(y.type===m.INTERPOLATION){let I=[];for(let A of y.parts)if(typeof A=="string")I.push(A);else if(A.type===m.VARIABLE){let v=A.path,_;if(v===c)_=f;else if(v===a)_=l;else if(v.startsWith(c+".")){let k=v.substring(c.length+1);!k.includes(".")&&!k.includes("[")?_=f[k]:_=G(v,r,{...n,[c]:f,...a&&{[a]:l}})}else _=G(v,r,{...n,[c]:f,...a&&{[a]:l}});I.push(_!=null?String(_):"")}else{let v={...n,[c]:f,...a&&{[a]:l}},_=L(A,t,r,v);I.push(_!=null?String(_):"")}u[g]=I.join("")}else{let I={...n,[c]:f,...a&&{[a]:l}};u[g]=L(y,t,r,I)}}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},Zs=(e,t,r,n)=>{let o=L(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 oo(u,o,f)}if(!e.indexVar){let l=Qs(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=Js(e,o);if(l!==null)return l}let i=Xs(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=L(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},ea=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(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?L(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]=G(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=G(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]=G(y.path,r,n);else if(y.type===m.INTERPOLATION){let I=[];for(let A of y.parts)if(typeof A=="string")I.push(A);else if(A.type===m.VARIABLE){let v=G(A.path,r,n);I.push(v!=null?String(v):"")}else{l=!1;break}if(!l)break;p[g]=I.join("")}else{l=!1;break}}if(!l)break;a[u]=p}else{l=!1;break}}if(l)return c[i]=a,c}}return null},ta=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!$e(e.whenCondition,o,r,n))return;let i=ea(e,t,r,n);if(i!==null)return i;if(e.fast){let l={};for(let f of e.properties){let u=f.parsedKey?L(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]=G(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=G(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=L(h,t,r,n);p.push(g!=null?String(g):"")}l[u]=p.join("")}else l[u]=L(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(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(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=L(u.value,t,r,n);d!==void 0&&(s[l.key]=d)}else{let d=L(l.value,t,r,n);d!==void 0&&(s[l.key]=d)}}else{let u=l.parsedKey?L(l.parsedKey,t,r,n):l.key,d=L(l.value,t,r,n);d!==void 0&&(s[u]=d)}}return s},uo={},ra=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=L(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,r,n);s!==uo&&s!==void 0&&o.push(s)}return o},na=(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 fe(`Partial '${o}' is not defined`);let l=n._partialStack||[];if(l.includes(o))throw new fe(`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=L(i,t,r,n);u={...u,...p}}return L(f,t,u,d)},oa=(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 fe(`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 fe(`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 fe(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return c.length>0&&(a+="."+c.join(".")),a};var Nr=qs;var ia=/\$\{([^}]*)\}/g,sa=/#\{([^}]*)\}/g,po=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=aa(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},aa=(e,t={})=>e.trim()?ca(e).map(n=>la(n.trim(),t)):[],ca=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},la=(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=po(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=He(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}},ho=/^\w+\(.*\)$/,ua=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,fa=e=>{if(!(!e||e.trim()===""||ho.test(e))&&ua.test(e))throw e.includes("?")&&e.includes(":")?new x(`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 x(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new x(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},fo=e=>{let t=e.trim();if(ho.test(t))throw new x(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new x(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new x(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new x(`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 x(`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}},bt=(e,t={})=>{let r=e.trim();fa(r);let n=po(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}},Vr=(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(ia)],i=[...r.matchAll(sa)],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"?bt(l[1],t):fo(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=bt(d.trim(),t):h=fo(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 Mr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),yo=e=>Object.keys(e),ae=e=>e.join("."),ke=(e,t,r)=>{let n=yo(e).filter(o=>!t.has(o));if(n.length>0)throw new x(`Unexpected key '${n[0]}' in condition JSON at '${ae(r)}'`)},Te=(e,t)=>typeof e=="string"?Vr(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?pa(e,t):ha(e,t):{type:m.LITERAL,value:e},da=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new x("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new x("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new x("Empty $each body not allowed");if(r.$partial!==void 0)throw new x("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${n}`]:r}},pa=(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=da(i),l=Object.keys(a);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let f=go(l[0],a[l[0]],t,!0);r.push(f),n=!0;continue}}catch(a){throw a instanceof x?a:new x(a.message)}let c=Object.keys(i);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let a=go(c[0],i[c[0]],t);r.push(a),n=!0;continue}}let s=Te(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}},ha=(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 x("$partial value must be a string");if(e.$partial.trim()==="")throw new x("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],l=[];for(let[I]of i)for(let A of a)if(I===A||I.startsWith(A+" ")||I.startsWith(A+"#")){l.push(A);break}if(l.length>0)throw new x(`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[I,A]of Object.entries(d)){let v=I;(I.startsWith("\\$")||I.startsWith("$$"))&&(v=I.slice(1)),p[v]=A,h=!0}let g=null;if(h&&(g=Te(p,t),g.type===m.OBJECT)){let I=!1;for(let A of g.properties)if(A.value.type===m.VARIABLE||A.value.type===m.INTERPOLATION||A.value.type===m.FUNCTION||A.value.type===m.CONDITIONAL||A.value.type===m.OBJECT&&!A.value.fast||A.value.type===m.ARRAY&&!A.value.fast){I=!0;break}I&&(g.fast=!1)}let y={type:m.PARTIAL,name:f,data:g};return u!==void 0&&(y.whenCondition=mo(u,t)),y}for(let[a,l]of i)if(a==="$when"){if(o!==null)throw new x("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new x("Missing condition expression after '$when'");o=mo(l,t),n=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new x("'$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 x("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let f=ma(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 x(`$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 x(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new x("Missing condition expression after '$if'");{let f=Te(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=Vr(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},ma=(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 x(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());Pr(l);let f=J(l,r);for(n.push(f),o.push(Te(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{Pr(h);let g=J(h,r);n.push(g)}if(o.push(Te(d,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:a},nextIndex:i}},jr={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},Fr={all:O.AND,any:O.OR},ga=new Set(["var","literal","call","not",...Object.keys(jr),...Object.keys(Fr)]),ya=(e,t,r)=>{if(!Array.isArray(e))throw new x(`Condition JSON operator '${t}' at '${ae(r)}' requires an array`);if(e.length!==2)throw new x(`Condition JSON operator '${t}' at '${ae(r)}' requires exactly 2 operands`);return e},ba=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new x(`Condition JSON operator '${t}' at '${ae(o)}' requires an array`);if(e.length===0)throw new x(`Condition JSON operator '${t}' at '${ae(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}))},Ia=(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(Mr(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 x(`Condition JSON call at '${ae(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new x(`Condition JSON call at '${ae(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new x(`Invalid condition JSON function name '${n}' at '${ae(r)}'`);if(!Array.isArray(o))throw new x(`Condition JSON call '${n}' at '${ae(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 x(`Condition JSON array at '${ae(r)}' must be wrapped in an operator or { literal: [...] }`);if(!Mr(e))throw new x(`Invalid condition JSON value at '${ae(r)}'`);let n=yo(e);if(n.length===0)throw new x(`Condition JSON object at '${ae(r)}' must contain an operator`);let o=n.filter(s=>ga.has(s));if(o.length===0)throw new x(`Unknown condition JSON operator '${n[0]}' at '${ae(r)}'`);if(o.length>1)throw new x(`Condition JSON at '${ae(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 x(`Condition JSON var at '${ae(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 Ia(e,t,r);if(i==="not")return ke(e,new Set(["not"]),r),{type:m.UNARY,op:ot.NOT,operand:Ce(e.not,t,[...r,"not"])};if(i in Fr)return ke(e,new Set([i]),r),ba(e[i],i,Fr[i],t,[...r,i]);if(i in jr){ke(e,new Set([i]),r);let s=ya(e[i],i,[...r,i]);return{type:m.BINARY,op:jr[i],left:Ce(s[0],t,[...r,i,0]),right:Ce(s[1],t,[...r,i,1])}}throw new x(`Unknown condition JSON operator '${i}' at '${ae(r)}'`)},mo=(e,t={})=>{if(e==null)throw new x("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new x("Empty condition expression after '$when'");return J(e,t)}return Mr(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=He(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=He(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=He(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=He(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(He(e,l)!==-1)throw new x(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:m.UNARY,op:ot.NOT,operand:J(e.substring(1).trim(),t)}:bo(e,t)},He=(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},Aa=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}},bo=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return bt(r,t);let o=Aa(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return bt(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},wa=(e,t=!1)=>{let r=t?"$each":"$for";try{no(e)}catch(n){if(n instanceof x&&t){let o=n.message.replace(/\$for/g,"$each");throw new x(o.replace("Parse Error: ",""))}throw n}},go=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new x(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],c=i[2].trim();wa(c,n);let a=c.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let y=n?"$each":"$for";throw new x(`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(I=>I.trim());if(y.length!==2)throw new x(`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 x(`Reserved variable name: ${u}`);if(d&&p.includes(d))throw new x(`Reserved variable name: ${d}`);let h=bo(f,r),g=Te(t,r);return{type:m.LOOP,itemVar:u,indexVar:d,iterable:h,body:g,flatten:s!=="nested"}};var Ea=(e,t={})=>{let{functions:r={}}=t;return Te(e,r)},zt=Ea;var It={};Ds(It,{now:()=>xa});var xa=()=>Date.now();var va=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...It,...n},s=zt(e,{functions:i}),c={};for(let[a,l]of Object.entries(o))c[a]=zt(l,{functions:i});return Nr(s,t,{functions:i,partials:c})},ce=va;var Ca=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Sa=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,_a=(e,t)=>{if(Ca(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new x("Empty condition expression");return J(e,t)}return Ce(e,t)},Ra=(e,t={},r={})=>{let n=Sa(r),o={...It,...n},i=_a(e,o);return!!$e(i,{functions:o,partials:{}},t,{})},Ur=Ra;var wt=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return Ur(e,t)},vo=(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=Dr(n,p=>{let h=l(c(p),...f);u=h!==void 0&&!he(h)?h:void 0}),u});return{...o,...i}},Ht=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return Dr(n,i=>{o.forEach(s=>{t.forEach(c=>{c(i,s)})})})};var Oa=(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{}}},ye=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),At=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Co=e=>{let t=he(e)?We(e):e;return structuredClone(t)},La=({characterId:e,resourceCharacter:t,variables:r={}}={})=>{if(!ye(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},Yt=({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=La({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},De=e=>ye(e,"computed"),it=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!De(t[r]))),$a=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),Br=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},ka=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=$a(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 Br(s,i)}return n==="runtime"?Br(t.runtime,r.slice(1)):Br(t,r)},Ta=(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)`)},Io=(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`)},Da=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},we=(e,t,r,n)=>(Ta(e,t,n),t.map(o=>Wt(o,r))),ge=(e,t,r,n)=>{let o=we(e,t,r,n);return o.forEach(i=>Da(e,i)),o},Pa=(e,t,r)=>{switch(e){case"var":return ka(t,r);case"add":{let[n,o]=ge(e,t,r,2);return n+o}case"sub":{let[n,o]=ge(e,t,r,2);return n-o}case"mul":{let[n,o]=ge(e,t,r,2);return n*o}case"div":{let[n,o]=ge(e,t,r,2);return n/o}case"mod":{let[n,o]=ge(e,t,r,2);return n%o}case"neg":{let[n]=ge(e,t,r,1);return-n}case"round":{let[n]=ge(e,t,r,1);return Math.round(n)}case"floor":{let[n]=ge(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=ge(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=ge(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=ge(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=ge(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=we(e,t,r,2);return n==o}case"neq":{let[n,o]=we(e,t,r,2);return n!=o}case"gt":{let[n,o]=we(e,t,r,2);return n>o}case"gte":{let[n,o]=we(e,t,r,2);return n>=o}case"lt":{let[n,o]=we(e,t,r,2);return n<o}case"lte":{let[n,o]=we(e,t,r,2);return n<=o}case"in":{let[n,o]=we(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return Io(e,t),t.every(n=>!!Wt(n,r));case"or":case"any":return Io(e,t),t.some(n=>!!Wt(n,r));case"not":{let[n]=we(e,t,r,1);return!n}case"length":{let[n]=we(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:At(n)?Object.keys(n).length:0}case"includes":{let[n,o]=we(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return Co(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},Wt=(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 Pa(n,o,t)},Na=(e,t={})=>wt(e,{variables:t.variables,runtime:t.runtime}),Va=(e,t)=>{if(!At(e))throw new Error(`${t} must be an object`);let r=ye(e,"expr"),n=ye(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},zr=(e,t,r)=>(Va(e,t),ye(e,"value")?Co(e.value):Wt(e.expr,r)),ja=(e,t={},r="unknown")=>{if(!At(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=ye(e,"expr"),o=ye(e,"value");if(ye(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(!At(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(!At(c))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!ye(c,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(Na(c.when,t))return zr(c,`Computed variable "${r}" branch ${s}`,t)}return zr(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 zr(e,`Computed variable "${r}"`,t)},Fa=(e,t,r)=>{switch(t){case"number":if(typeof r!="number"||!Number.isFinite(r))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(r)?"array":typeof r}`);return;case"boolean":if(typeof r!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(r)?"array":typeof r}`);return;case"string":if(typeof r!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(r)?"array":typeof r}`);return;case"object":if(r===null||typeof r!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof r}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},Et=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=it(e,r),i=Object.entries(r).filter(([,u])=>De(u)).map(([u])=>u),s={},c=[],a=u=>{if(ye(s,u))return s[u];let d=r[u];if(!De(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=ja(d.computed,f,u);return Fa(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"&&(ye(o,d)||i.includes(d)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(u,d)=>{if(!(typeof d!="string"||!ye(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},Ma=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>Et({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),Gt=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(De(o))return;let i=Oa(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},Kt=(e,t)=>{let r=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!r.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${r.join(", ")}`)},Jt=(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(", ")}`)},Ua=2,Ao=12,So=(e=Ua)=>{if(!Number.isInteger(e)||e<0||e>Ao)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${Ao}.`);return e},Ba=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},qt=e=>typeof e=="number"&&Number.isFinite(e),Hr=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!qt(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!qt(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!qt(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}".`);So(o.roundTo)}}},Xt=(e,t,r,n={})=>{let o=(s,c,a)=>{let l=s??c;if(!qt(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 Ba(o(e,0,"current value")/i(r),So(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 _o=(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()))},za=(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},wo=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},Eo=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},xo=(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,qa=(e,t)=>{let r={},n=xo(wo(e),wo(t)),o=xo(Eo(e),Eo(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},Yr=(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=qa(e.background,t.background);i&&(r.background=i),o("screen"),o("bgm"),o("voice");let s=za(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},Gr=(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},Wa=(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},Ha=(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=Wa(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},Ya={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"])},Ro=(e,t)=>{let r=e[e.length-1];return r?Ya[r]?.has(t)===!0:!1},qr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>qr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Ro(r,n)?o:qr(o,t,[...r,n])])):Ha(e,t),Wr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Wr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Ro(r,n)?o:Wr(o,t,[...r,n])])):typeof e=="string"?ce(e,t):e,Kr=(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=qr(e,t._event);return Wr(r,t)};var q=e=>structuredClone(he(e)?We(e):e),z=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Oo=e=>e?.animations?.playback?.continuity==="persistent",$=(e,t)=>z(e??{},t)&&e[t]!==void 0,xt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:q(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Ga=e=>$(e,"opacity")||$(e,"blur"),To=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Do=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Jr=["animationName","animationSpeed","loop"],Ka=e=>To.some(t=>$(e,t)),Po=e=>e?.text&&$(e.text,"content")&&$(e.text,"textStyleId"),No=e=>$(e,"text"),Ja=(e,t)=>e.resourceId?!0:Po(e)?!t?.text:!1,Xa=(e,t)=>{let r={...q(e),...t};return t.text&&e.text&&(r.text={...q(e.text),...q(t.text)}),r},Qa=(e,t)=>{if(No(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!Po(e)&&!t?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},Lo=e=>Do.some(t=>$(e,t)),$o=e=>Jr.some(t=>$(e,t)),Za=(e,t,{hasAuthoredTransformId:r=!1}={})=>{if(!t)return e;for(let n of Do)!r&&!$(e,n)&&$(t,n)&&(e[n]=t[n]),z(e,n)&&e[n]===void 0&&delete e[n];return e},Vo=(e,t,r)=>{let n=e[r];return n?.id===t?.id?n:e.find(o=>o.id===t?.id)},ec=(e,t)=>{if(!t)return e;for(let r of To)!$(e,r)&&$(t,r)&&(e[r]=t[r]),z(e,r)&&e[r]===void 0&&delete e[r];return e},tc=(e,t)=>(t&&(!$(e,"opacity")&&$(t,"opacity")&&(e.opacity=t.opacity),!$(e,"blur")&&$(t,"blur")&&(e.blur=q(t.blur)),z(e,"opacity")&&e.opacity===void 0&&delete e.opacity,z(e,"blur")&&e.blur===void 0&&delete e.blur),e),jo=(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=Vo(r,s,c),l=t(s,a),f=Ga(s),u=Ka(s),d=n(s),p=z(s,"animations"),h=q(s);return!l&&(f||u||d)&&a&&(h=o?o(a,h):{...q(a),...h},p||delete h.animations),tc(ec(h,a),a)}).filter(s=>t(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},rc=e=>{if(e){if(e.character&&z(e.character,"name"))return e.character.name;if(z(e,"characterName"))return e.characterName}},Fo=e=>!!e?.character&&z(e.character,"sprite"),nc=e=>{let t={},r=!1,n=rc(e);return n!==void 0&&(t.name=n,r=!0),Fo(e)&&(t.sprite=q(e.character.sprite),r=!0),r?t:void 0},ko=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},oc=({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=>q(o)):delete e.initialRevealedContent,e.content=[...n,...t]},ic=()=>({}),sc=(e,t)=>{if(!t.screen)return;let r=$(t.screen,"opacity"),n=$(t.screen,"blur"),o=z(t.screen,"animations");if(!r&&!n){o||delete e.screen;return}let i=e.screen,s={};if(r?s.opacity=t.screen.opacity:$(i,"opacity")&&(s.opacity=i.opacity),n?s.blur=q(t.screen.blur):$(i,"blur")&&(s.blur=q(i.blur)),z(s,"opacity")&&s.opacity===void 0&&delete s.opacity,z(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},ac=(e,t)=>{if(t.background){let r=$(t.background,"resourceId"),n=$(t.background,"colorId"),o=$(t.background,"opacity"),i=$(t.background,"blur"),s=$(t.background,"transformId"),c=Lo(t.background),a=$o(t.background),{animationsOnly:l,state:f}=xt(t.background,p=>$(p,"resourceId")||$(p,"colorId")||$(p,"opacity")||$(p,"blur")||$(p,"transformId")||Lo(p)||$o(p));if(l){e.background=e.background?{...q(e.background),...f}:f;return}if(!r&&!n&&!o&&!i&&!s&&!c&&!a){delete e.background;return}let u=e.background,d=q(t.background);if(!r&&u?.resourceId){d.resourceId=u.resourceId,!z(d,"transformId")&&u.transformId&&(d.transformId=u.transformId);for(let p of Jr)!$(d,p)&&$(u,p)&&(d[p]=u[p])}Za(d,u,{hasAuthoredTransformId:s}),!n&&u?.colorId&&(d.colorId=u.colorId),!o&&$(u,"opacity")&&(d.opacity=u.opacity),!i&&$(u,"blur")&&(d.blur=q(u.blur)),z(d,"resourceId")&&d.resourceId===void 0&&delete d.resourceId,z(d,"colorId")&&d.colorId===void 0&&delete d.colorId,z(d,"animations")&&d.animations===void 0&&delete d.animations,z(d,"transformId")&&d.transformId===void 0&&delete d.transformId,z(d,"opacity")&&d.opacity===void 0&&delete d.opacity,z(d,"blur")&&d.blur===void 0&&delete d.blur;for(let p of Jr)z(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&&!z(d,"animations")&&Oo(u)&&(d.animations=q(u.animations)),e.background=d}else e.background?.animations&&!Oo(e.background)&&(e.background.animations={})},cc=(e,t)=>{if(!t.dialogue){e.dialogue&&(ko(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}=xt(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&&oc({dialogueState:e.dialogue,content:t.dialogue.content,append:n}),z(t.dialogue,"textSpeed")?e.dialogue.textSpeed=t.dialogue.textSpeed:delete e.dialogue.textSpeed;let o=z(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=z(t.dialogue,"characterId"),s=nc(t.dialogue),c=s!==void 0,a=Fo(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?{...q(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,a||ko(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=q(e.dialogue.character)),e.dialogue.lines.push(l)}},lc=(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=q(t.sfx)}else e.sfx&&delete e.sfx},uc=(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=q(t.bgm),t.bgm.resourceId&&(e.bgm.loop=t.bgm.loop??!0)}},fc=(e,t)=>{if(t.visual){let r=e.visual?.items||[];t.visual.items?.forEach((i,s)=>{Qa(i,Vo(r,i,s))});let{hasValidItems:n,processedItems:o}=jo(t.visual.items,Ja,r,{hasPatchFn:No,mergeItemFn:Xa});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))},dc=(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}=jo(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},pc=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},hc=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=xt(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},mc=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=xt(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},gc=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=xt(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=q(t.form)}else e.form&&delete e.form},yc=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},bc=(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=q(t.voice)}else e.voice&&delete e.voice},Ic=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},Ye=e=>Ht(ic,[Ic,sc,ac,lc,uc,fc,cc,dc,pc,hc,mc,gc,yc,bc])(e);var st=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=ce(e,t);return r&&typeof r=="object"?e:r};var Ac=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}),vt=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Mo=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"}),Xr=Object.freeze(["dialogueTextSpeed","autoForwardDelay","autoForwardSpeed","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Qr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),wc=(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]}},Ke=e=>Object.fromEntries(Object.entries(Ac).map(([t,r])=>{let n=wc(e,r.source),o=n!==void 0?n:Ge[t]??vt[t];return[t,o]})),Pe=(e,t)=>Ke(e)[t],Uo=(e={})=>Object.fromEntries(Xr.map(t=>[t,e[t]??Ge[t]]));var at=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:at.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:at.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:at.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:at.VISUAL_BEHIND_CHOICE,FOREGROUND:at.VISUAL_FOREGROUND}),Zr=_e.BEHIND_DIALOGUE,en=Object.freeze(Object.values(_e).sort((e,t)=>e-t));var Re={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:_o},Ec=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,xc=(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},tr=(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=Ec.exec(s);if(c){let[,a,l,f]=c,u=xc(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 I=tr(y,g,r),A=ce(I,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(tr(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=tr(i,t,r)}),n},bn=({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".`)},vc=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);if(bn({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n!==void 0){let s=Rc(n,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},Cc=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return bn({animationType:e.type,animationId:t,animationPath:r}),e.type},Sc=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},_c=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Rc=(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},Oc=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),ei=e=>e?.playback?.continuity==="persistent",ln=e=>Array.isArray(e)?e.map(ln):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=ln(e[r]),t),{}),nr=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(ln(t))},ti=(e=[])=>e.filter(t=>ei(t)).map(t=>structuredClone(t)),ri=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,tn=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,ri(r)),0),ni=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(tn(e.tween),tn(e.prev?.tween),tn(e.next?.tween),ri(e.mask?.progress))/Oc(e),Bo=({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(nr).filter(Boolean));return e.some(n=>{if(!ei(n))return!1;let o=nr(n);return o?r.has(o):!1})},Ee=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||Bo({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:Bo({animationInstances:e,activePersistentAnimations:o}),Lc=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),$c=(e,t)=>{if(Lc(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},kc=({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?vc({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},Tc=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return bn({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},In=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(Tc(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},un=(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},Dc=({content:e,path:t,variables:r})=>un(e,t).reduce((n,o)=>{let i=st(o.text,{variables:r});return n+`${i??""}`.length},0),zo=(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))},Qt=(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("-")}`},Zt=(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},Pc=(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},Nc=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Vc=(e={})=>Nc.some(t=>Je(e,t)),oi=(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"}},rr=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},jc=(e={})=>e.textStyles||{},Fc=(e={})=>e.images||{},Mc=.5,Uc=(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]},ii=({id:e,resourceId:t,spritesheet:r,animationName:n,animationSpeed:o,loop:i,transform:s={}}={})=>{let c=Uc(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??Mc,loop:i??a.loop??!0}}},si=({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 ii({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}`)},Bc=(e={})=>e.colors||{},zc=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,_t=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,lt=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},rn=(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},nn=(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},sr=(e,t)=>{if(typeof e!="string"||!zc.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},qo=(e,t,r)=>{let n=sr(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})`},qc=(e={},t)=>{let r=jc(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=rn(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:qo(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=rn(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=qo(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:sr(c.hex,`Shadow color "${r.shadow.colorId}" for text style "${t}"`),alpha:rn(r.shadow.alpha,"shadow.alpha",t),blur:nn(r.shadow.blur,"blur",t,0,{minimum:0}),offsetX:nn(r.shadow.offsetX,"offsetX",t,2),offsetY:nn(r.shadow.offsetY,"offsetY",t,2)}}return s},fn=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>fn(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]=fn(i,t,_t(r,o)));return e.textStyleId!==void 0&&(lt(e.textStyleId,r,"textStyleId"),n.textStyle=qc(t,e.textStyleId)),n},An=(e={},t)=>{let r=Bc(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return sr(r.hex,`Color "${t}"`)},ai=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",on=(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 ${ai(`${t}.fill`)} instead`)},Wc=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Rt(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;let n={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(n[o]=Rt(i,t,_t(r,o)));return e.colorId!==void 0&&(lt(e.colorId,r,"colorId"),n.fill=An(t,e.colorId)),n},Rt=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Rt(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${r}". Use ${ai("fill")} instead`);on(e,"hover",r),on(e,"click",r),on(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]=Wc(i,t,_t(r,o));continue}n[o]=Rt(i,t,_t(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(lt(e.colorId,r,"colorId"),n.fill=An(t,e.colorId)),n},sn=(e={},t)=>{let r=Fc(e)?.[t];return r||null},ci=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",Wo=(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 ${ci(`${t}.${n}`)} instead`)},Ho=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},dn=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>dn(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(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 ${ci(o)} instead`);Wo(e,"hover",r,"src"),Wo(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]=dn(i,t,_t(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){lt(e.imageId,r,"imageId");let o=sn(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&&(lt(e.hoverImageId,r,"hoverImageId"),Ho(n,"hover",sn(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(lt(e.clickImageId,r,"clickImageId"),Ho(n,"click",sn(t,e.clickImageId)?.fileId??e.clickImageId)),n},wn=(e,t={},r="root")=>dn(Rt(fn(e,t,r),t,r),t,r),Oe=wn,Qe=(e=[])=>e.find(t=>t.id==="story"),Hc="#000000",pn="bg-cg-background-color",Yc=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?sr(r?.backgroundColor??Hc,"screen.backgroundColor"):An(e,t.colorId),li=(e={})=>{if(Je(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Gc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Yo=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=li(e),n=Gc(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},Kc=(e={})=>{if(Je(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Jc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},ui=(e={})=>{let t=Kc(e),r=Jc(e),n={};return t!==void 0&&(n.alpha=t),r&&(n.blur=r),n},Ct=(e={})=>ui(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},Xc=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],En=(e={})=>e.text&&Je(e.text,"content")&&Je(e.text,"textStyleId"),Go=(e={})=>{if(e.resourceId)return e.resourceId;if(En(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(!En(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let t of Xc)if(Je(e.text,t))throw new Error(`Visual item "${e.id}" text.${t} is reserved for the visual item`)}},Zc=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:pn,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:Yc({resources:e,background:t,screen:r})};if(n){let i=li(t);i!==void 0&&(o.alpha=i)}return o},el=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.spritesheets?.[t]||e.layouts?.[t]):!1,Ko=({resources:e={},resourceId:t,colorId:r})=>{let n=oi(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:rr({resourceId:t,kind:n})}:r!==void 0?{resourceId:pn,targetId:pn}:{resourceId:void 0,targetId:void 0}},fi=100,Xe=fi,tl="channel:bgm",rl="channel:voice",nl="default",ol=e=>String(e).replaceAll("%","%25").replaceAll(":","%3A"),St=(...e)=>e.map(ol).join(":"),or=(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)})},il=(e,t)=>e*t/fi,di=(e={},t)=>e?.[t]??Ge[t],xn=(e={},t,r=Xe)=>il(r,di(e,t)),vn=({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}),er=(e,t,r,n)=>e[r]!==void 0?e[r]:t[r]!==void 0?t[r]:n,sl=["muted","pan","playbackRate","startAt","endAt"],Cn=({id:e,sound:t,resource:r,defaultLoop:n=!1})=>{let o={id:e,type:"sound",src:r.fileId,loop:er(t,r,"loop",n),volume:er(t,r,"volume",Xe),startDelayMs:er(t,r,"startDelayMs",0)};sl.forEach(s=>{let c=er(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},xe=({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:I}={})=>{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},v=fl({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e,runtime:A}),_={variables:e,runtime:A,saveSlots:r,isChoiceVisible:a,isFormVisible:l,canRollback:f,confirmDialog:u,form:d,historyDialogue:p,characters:h};return v&&(_.dialogue=v,_.dialogueLines=v.lines),_},Jo=100,ir=(e,t)=>{if(Array.isArray(e))return e.map(n=>ir(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=ir(r[n],t)}),r.type==="text-revealing"?t(r):r},al=e=>ir(e,t=>({...t,revealEffect:"none"})),cl=e=>ir(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,Jo):Jo;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?al(e):r?cl(e):e,pi=({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:{}}}}),hn=e=>{if(Array.isArray(e))return e.map(hn);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=hn(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}}:{}}}}},ll=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),Xo="submit",an=(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}}},mn=(e,t,r={})=>{if(Array.isArray(e))return e.map(l=>mn(l,t,r));if(!e||typeof e!="object")return e;let n=typeof e.type=="string",o=n&&e.formRole===Xo,i=n&&r.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},c={};for(let[l,f]of Object.entries(e))c[l]=mn(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:an(a.change,f),submit:an(a.submit,t.submitActions)}}}return a.formRole===Xo||i?{...a,click:an(a.click,t.submitActions,{replaceActions:!0})}:a},gn=(e,t)=>{if(Array.isArray(e))return e.map(n=>gn(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=gn(o,t);for(let n of ll){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form"}})}return r},yn=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0,s=Yt({characterId:e,character:t,characterName:r,characters:n,variables:o});return{...i||{},...t||{},name:s}},hi=(e=[],t={},r={})=>e.map(n=>{let o=yn({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}}),ul=e=>!(!e||e.mode==="adv"&&e.content===void 0),fl=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n,runtime:o}={})=>{if(!t&&!ul(e))return;let i=e.content===void 0?[{text:""}]:un(e.content,"dialogue.content"),s=e.content===void 0?0:Dc({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),c=o?.dialogueTextSpeed??Ge.dialogueTextSpeed,a=e.textSpeed??c,l=(e.lines||[]).map((u,d)=>{let p=un(u.content,`dialogue.lines[${d}].content`),h=yn({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:st(g.text,{variables:n})})),character:h,characterName:h.name}}),f=yn({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:st(u.text,{variables:n})})),initialRevealedCharacters:s,lines:l}},mi=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=ce(e,r,{functions:Re});return Oe(Ve(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},cn=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),Qo=({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:cn(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:cn(o.keyup)});return}e[n]={...i,[r]:{payload:cn(o)}}})},dl=(e={},t={})=>{let r={};return Qo({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),Qo({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:I,targetId:A})=>{let v=kc({resources:t,animationId:p,playback:h,instanceId:I,targetId:A,animationPath:s});v&&a.push(v)},f=r!=null&&r!==!1,u=n!=null&&n!==!1,d=o&&i&&o===i;$c(e,s);let p=Sc(e),h=_c(e),g=t?.animations?.[p],y=Cc(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 I=`${c}-animation-transition`,A=h?.continuity==="persistent"?I:`${c}-animation-in`;if(f&&u&&d)return l({instanceId:I,targetId:i}),a;f&&l({instanceId:`${c}-animation-out`,targetId:o}),u&&l({instanceId:A,targetId:i})}return a},pl=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),hl=(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:I,saveSlots:A=[]})=>{let{elements:v,animations:_}=e;if(t.background){let k=n===void 0?!0:Je(n?.background??{},"animations"),N=v.find(re=>re.id==="story");if(!N)return e;let w=Pc(o,t.background),M=w||Vc(t.background),U=r?.background?.resourceId,H=r?.background?.colorId,j=t.background.resourceId??(t.background.animations?U:void 0),W=t.background.colorId??(t.background.animations?H:void 0),K=el(o,j),ee={...t.background,colorId:W};if((W!==void 0||K)&&N.children.push(Zc({resources:o,background:ee,screen:i,includeOpacity:!K})),j){let{images:re={},videos:ue={},spritesheets:Y={}}=o,ne=oi(o,j),oe;if(ne==="sprite"?oe=re[j]:ne==="video"?oe=ue[j]:ne==="spritesheet-animation"&&(oe=Y[j]),oe){let C=ne==="video",R=ne==="spritesheet-animation",T={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...w},ie={...Yo(t.background,{includeDefaultAlpha:!0}),...Ne(T,t.background)},se;R?se=ii({id:rr({resourceId:j,kind:ne}),resourceId:j,spritesheet:oe,animationName:t.background.animationName,animationSpeed:t.background.animationSpeed,loop:t.background.loop,transform:ie}):se={id:rr({resourceId:j,kind:ne}),type:C?"video":"sprite",src:oe.fileId,width:oe.width,height:oe.height,...ie},C&&(se.loop=t.background.loop??!1,se.volume=oe.volume??50),se&&N.children.push(se)}}if(j){let{layouts:re={}}=o,ue=re[j];if(ue){let Y={id:rr({resourceId:j,kind:"container"}),type:"container",children:ue.elements,...Yo(t.background)};M&&Object.assign(Y,Ne({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...w},t.background));let ne=ce(Y,xe({variables:a,runtime:l,saveSlots:A,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:I,characters:o.characters||{},skipTransitionsAndAnimations:c}),{functions:Re});N.children.push(Oe(Ve(ne,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:c}),o))}}let ve=Ko({resources:o,resourceId:U,colorId:H}),te=Ko({resources:o,resourceId:j,colorId:W}),X=Le({animationsDef:t.background.animations,resources:o,previousResourceId:ve.resourceId,currentResourceId:te.resourceId,previousTargetId:ve.targetId,currentTargetId:te.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});Ee({animationInstances:X,isLineCompleted:s,skipTransitionsAndAnimations:c,activePersistentAnimations:f,restoredPersistentAnimations:u,isAuthoredOnCurrentLine:k})&&_.push(...X)}return e},ml=(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=zo(f),p=zo(u);for(let h=0;h<f.length;h++){let g=f[h],{transformId:y,sprites:I}=g,A=u.find(j=>j.id===g.id),v=u.findIndex(j=>j.id===g.id),_=A?.sprites&&A.sprites.length>0,k=I&&I.length>0,N=v>=0?Qt(A,v,p):void 0,w=Le({animationsDef:g.animations,resources:n,previousResourceId:N,currentResourceId:k?Qt(g,h,d):void 0,previousTargetId:N,currentTargetId:k?Qt(g,h,d):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!I&&!y&&_&&Ee({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...w);continue}if(g.animations&&!I&&!y)continue;if(!I||I.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let M=Qt(g,h,d),U=n.transforms[y];if(!U){console.warn("Transform not found:",y);continue}let H={type:"container",id:M,...Ne(U,g),...Ct(g),children:[]};for(let j of I){let W=si({id:`${M}-${j.id}`,item:j,resources:n});W&&H.children.push(W)}l.children.push(H),Ee({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...w)}}return e},gi=(e,t)=>{if(!en.includes(e))throw new Error(`${t} must be one of: ${en.join(", ")}.`)},gl=(e,t)=>{let r=!!e.resourceId||En(e),n=e.layer??(r?void 0:t?.layer)??Zr;return gi(n,`Visual item "${e.id}" layer`),n},yl=(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:I,animations:A}=e;if(t.visual&&n){let v=I.find(w=>w.id==="story");if(!v)return e;let _=t.visual.items,k=r?.visual?.items||[],N=xe({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&&gi(y,"visualLayer");for(let w of _){let M=k.find(K=>K.id===w.id),U=gl(w,M);if(y!==void 0&&U!==y)continue;if(Qc(w),w.text){let K=Zt(n,w),ee={...structuredClone(w.text),id:`visual-${w.id}`,type:"text",...Ne(K,w)};Object.assign(ee,Ct(w)),v.children.push(Oe(ce(ee,N,{functions:Re}),n))}if(w.resourceId){let{images:K={},videos:ee={},spritesheets:ve={}}=n,te=ve[w.resourceId];if(te){let X=Zt(n,w),re=w.animationName;if(re){let ue=te.animations?.[re];if(!ue)throw new Error(`Animation '${re}' not found in spritesheet resource '${w.resourceId}'`);let Y=Ct(w),ne={id:`visual-${w.id}`,type:"spritesheet-animation",...Ne(X,w),width:w.width??te.width,height:w.height??te.height,alpha:Y.alpha??w.alpha??1,src:te.fileId,atlas:te.jsonData,playback:{frames:ue.frames,animationSpeed:w.animationSpeed??ue.animationSpeed??.5,loop:w.loop??ue.loop??!0}};Y.blur&&(ne.blur=Y.blur),v.children.push(structuredClone(ne))}}else{let X=K[w.resourceId]||ee[w.resourceId];if(X){let re=ee[w.resourceId]!==void 0,ue=Zt(n,w),Y={id:`visual-${w.id}`,type:re?"video":"sprite",src:X.fileId,width:X.width,height:X.height,...Ne(ue,w)};Object.assign(Y,Ct(w)),re&&(Y.loop=X.loop??!1,Y.volume=X.volume??50),v.children.push(Y)}}}if(w.resourceId){let{layouts:K={}}=n,ee=K[w.resourceId];if(ee){let ve=Zt(n,w),te={id:`visual-${w.id}`,type:"container",children:structuredClone(ee.elements),...Ne(ve,w)};Object.assign(te,Ct(w));let X=ce(te,N,{functions:Re});v.children.push(Oe(Ve(X,{isLineCompleted:o,skipMode:f,skipTransitionsAndAnimations:i}),n))}}let H=Go(M),j=Go(w),W=Le({animationsDef:w.animations,resources:n,previousResourceId:H,currentResourceId:j,previousTargetId:H?`visual-${w.id}`:void 0,currentTargetId:j?`visual-${w.id}`:void 0,animationPath:`visual.items[${w.id}].animations`,idPrefix:w.id});Ee({animationInstances:W,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:a})&&A.push(...W)}}return e},ct="dialogue-character-sprite",Zo=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,bl=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=Qe(e.elements);if(!a)return e;let l=t.dialogue?.character?.sprite,f=r?.dialogue?.character?.sprite,u=Zo(l),d=Zo(f),p=Le({animationsDef:l?.animations,resources:n,previousResourceId:d?ct:void 0,currentResourceId:u?ct:void 0,previousTargetId:d?ct:void 0,currentTargetId:u?ct:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!u)return l?.animations&&d&&Ee({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:ct,...Ne(h),children:[]};for(let y of l.items){let I=si({id:`${ct}-${y.id}`,item:y,resources:n});I&&g.children.push(I)}return a.children.push(g),Ee({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e},Il=(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:I=[]})=>{let{elements:A,animations:v}=e;if(!t.dialogue||o)return e;let _=A.find(N=>N.id==="story");if(!_)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},U=xe({variables:h,runtime:g,saveSlots:I,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}),H={functions:Re},j=tr(M,U,H),W=ce(j,U,H),K=Oe(Ve(W?.elements,{isLineCompleted:d,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(K))for(let ee of K)_.children.push(ee);else K&&_.children.push(K)}}bl(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let k=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 Ee({animationInstances:k,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&v.push(...k),e},Al=(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:I,animations:A}=e;if(t.choice&&n){let v=Qe(I);if(!v)return e;let _=n?.layouts[t.choice.resourceId];if(_&&_.elements){let N={elements:_.elements},w=ce(N,{...xe({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=hn(Oe(Ve(w?.elements,{isLineCompleted:i,skipMode:f,skipTransitionsAndAnimations:s}),n));if(Array.isArray(M))for(let U of M)v.children.push(U);else M&&v.children.push(M)}let k=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"});Ee({animationInstances:k,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&A.push(...k)}return e},wl=(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:I,animations:A}=e;if(!y?.resourceId||!n)return e;let v=Qe(I);if(!v)return e;let _=n?.layouts?.[y.resourceId];if(!_)return console.warn(`Form layout not found: ${y.resourceId}`),e;let k={id:"form-container",type:"container",x:0,y:0,children:_.elements||[]},N={...xe({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=ce(k,N,{functions:Re}),M=gn(Oe(Ve(mn(w,y),{isLineCompleted:i,skipMode:f,skipTransitionsAndAnimations:s}),n),y);M&&v.children.push(M);let U=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 Ee({animationInstances:U,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(...U),e},El=(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=dl(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=Qe(e.elements);if(!y)return e;let I={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(mi({container:I,resources:r,templateData:xe({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},xl=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Qe(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||or(f,"BGM sound"),f.forEach(p=>{let h=r.sounds?.[p.resourceId];h&&u.push(Cn({id:St("bgm",l?"default":p.id),sound:p,resource:h,defaultLoop:!0}))}),u.length===0)return e;let d=xe({variables:o,runtime:n}).runtime;s.push(vn({id:tl,volume:xn(d,"musicVolume",l?Xe:a.volume??Xe),muted:a.muted,pan:a.pan,children:u,runtime:d}))}return e},vl=(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:nl,sounds:i.items??[]}]:i.channels;s||or(c,"SFX channel"),c.forEach(a=>{let l=[];s||or(a.sounds,"SFX sound",`SFX channel "${a.id}"`),a.sounds.forEach((f,u)=>{let d=r.sounds?.[f.resourceId];d&&l.push(Cn({id:s?St("sfx","default",u,f.id):St("sfx",a.id,f.id),sound:f,resource:d}))}),l.length!==0&&o.push(vn({id:St("channel","sfx",a.id),volume:xn(n,"soundVolume",a.volume??Xe),muted:a.muted,pan:a.pan,children:l,runtime:n}))})}return e},Cl=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},Sl=(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:Xe,startDelayMs:c.startDelayMs??0}]:[]:c.sounds,f=[];if(a||or(l,"Voice sound"),l.forEach(d=>{let p=Cl(r,n,d.resourceId);p&&f.push(Cn({id:St("voice",n,a?"default":d.id),sound:d,resource:p}))}),f.length===0)return e;let u=xe({variables:i,runtime:o}).runtime;return s.push(vn({id:rl,volume:a?c.volume??di(u,"soundVolume"):xn(u,"soundVolume",c.volume??Xe),muted:c.muted,pan:c.pan,children:f,runtime:u})),e},_l=(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:I}=e;if(t.layout){let k=Qe(y);if(!k)return e;let N=n.layouts[t.layout.resourceId];if(!N)return e;Array.isArray(N.transitions)&&!p&&!h&&In({animations:I,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||[]};k.children.push(mi({container:w,resources:n,templateData:xe({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,v=t.layout?.resourceId,_=Le({animationsDef:t.layout?.animations,resources:n,previousResourceId:A,currentResourceId:v,previousTargetId:A?`layout-${A}`:void 0,currentTargetId:v?`layout-${v}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return Ee({animationInstances:_,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&I.push(..._),e},Rl=(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 Ee({animationInstances:f,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...f),e},Ol=(e,{presentationState:t})=>{let r=Qe(e.elements);return!r||!t?.screen||Object.assign(r,ui(t.screen)),e},Ll=(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:I,animations:A}=e;return u&&u.length>0&&u.forEach((v,_)=>{let k=r.layouts[v.resourceId];if(!k){console.warn(`Overlay layout not found: ${v.resourceId}`);return}Array.isArray(k.transitions)&&(y||In({animations:A,transitions:k.transitions,defaultTargetId:`overlayStack-${_}`,idPrefix:`overlayStack-${_}`,animationPathPrefix:`overlayStack[${_}]`}));let N={id:`overlayStack-${_}`,type:"container",x:0,y:0,children:[pi({id:`overlayStack-${_}-blocker`,screen:h}),...k.elements||[]]},w=hi(d,r.characters,n),M=xe({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}),U=ce(N,M,{functions:Re}),[H,...j]=U.children||[],W=Oe(Ve({...U,children:j},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);I.push({...W,children:H?[H,...W.children||[]]:W.children})}),e},$l=(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:I,animations:A}=e;if(!d?.resourceId)return e;let v=r.layouts?.[d.resourceId];if(!v)return console.warn(`ConfirmDialog layout not found: ${d.resourceId}`),e;Array.isArray(v.transitions)&&!y&&In({animations:A,transitions:v.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let _={id:"confirmDialog",type:"container",x:0,y:0,children:[pi({id:"confirmDialog-blocker",screen:h}),...v.elements||[]]},k=hi(p,r.characters,n),N=ce(_,xe({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:k,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:Re}),[w,...M]=N.children||[],U=Oe(Ve({...N,children:M},{isLineCompleted:g,skipMode:c,skipTransitionsAndAnimations:y}),r);return I.push({...U,children:w?[w,...U.children||[]]:U.children}),e},Ot=e=>(t,r)=>yl(t,{...r,visualLayer:e}),kl=Ot(_e.BEHIND_BACKGROUND),Tl=Ot(_e.BEHIND_CHARACTER),Dl=Ot(_e.BEHIND_DIALOGUE),Pl=Ot(_e.BEHIND_CHOICE),Nl=Ot(_e.FOREGROUND),yi=e=>Ht(pl,[El,kl,hl,Tl,ml,Dl,Il,Pl,Al,wl,_l,Nl,Ol,Rl,xl,vl,Sl,Ll,$l])(e);function bi(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 Ii(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 Ai="090001000h1v5g2903000hl2v6jh16ng1s210111110o35aa10u2k1g10l6600152113h2010u1q1r5aq3890o13181214r22k3158q2n1000v100h1k20000001207030001160721k171001h1j11610332010010321210090411021c1c02100o301201412230u1130b100h1j116111420120411001100k11l10051001h1j11611142011000321210072411021d0g10r3000000132120090o200200g1j11f2012031213711271t1001o301001000001121371b1f0c101h1l2011001031212000080a1t1001m40400102101600i11t301006c7i601008b6p41r10101041h3d0004115a1j290p3q223000511010100g1501010302003172030c0010016000e0i6v50n40n5tl12ir33s12t11u11cj30100060700010a90t220000l71i20m7203010241000502rd101004k300000006101027050920g3t22bk1300616g209030207u18c1000t10003010501b2o20000102000004g37070101o921c000640602001mcv3rg20000001o16d0c0m1fg6g2h30m10q55f1vm11c0ma0p1a42nc0ne1a090q3314902021204020112030318250105bb1201110i1021i15101131502141b15120511011k1155132040202510201010603060a1f02040104210b1g3290e0e0kn11vs12j11j3040pp12t80g6v1vmo7319g21g51gh103040n11010040j51i3f01q1h1d0m27p1a0000cs13200523j200010301010100v140018a4q2501010101c08000i1f12601011g3012215110u1a0001015000pcq181000100011000iji5fvc0u91g5bhg20ie0l94lo6002115303121s12240la1tj23h44tj11t45m4ah33q700000l3ep2021a200t220301012040a0i320j2040007f00100r20c100g3208000011531000s520201036020t900207l1101n311000000321210090a12634b910201l22001051020120011020000e1i520701020000n10h5001050000010000010001re0010323010001r11i520701000001q6000000107l600000230004gg12080001lc62027111n1000411230000000000t820321030030r10090n205001380800501020n2050c0001mc00002000000nc006150000i5l1100600010001q753011160000i441111000000rl11019100000c1h201043102n10ltk1f006eoss2b0202gs94r36si2033ku101m373h50b1rqs4113sli1t22m1uh2435070726u13k92rr7m34h380e0m141egl561g1261114k60ga6nn10t33sv13uf1jf0207150qt16t66pr60n23k6bf1f0e1l29g71c1e029j1n30p11ea0k1028139m16rb2v621122i52213040tf1u3b51n17127c0232041d120819052c28220104060306l5g3l4572g130152cqdl2c3o37a5o27u11c32d9m2cu2191obo57eh9gg1tv3",wi="262122424333333393233393339333333333393393bf3b3b3b3b3f3f3bffff33b3bb33ff3f33b3b3333333bffff3b33bb33f33bffff33b3bb33ff3f33b3bbb333b3ff33b333f33b3b3b3b3333b3bf33b3bb39333b33b33b3b3b333b333333b3b33333f3b33b3ffb3f3fff3f3b33f35dc33333f3b3b3b33323333b3bb3b33b3fb3b3333b33333bff3b3f33bfb3b3ff3b3b3b3b3b333b333b3323e22442344444444444444444444444444444444444444444444444444444444444444444444444444444443333333333b3b3bb33333b353bff3b3b3b3f3ff3b3b333bfff3f33333fb3bb3fb3b3bb33232333f333fff333333333b3b3333bb3b39393f3b3fbf33bb3b393b3b3b3333b33b33b3bbb33b33ffff3b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b3fffff3bb39b9b3b33b3bf3f3b33f3b3f93b33b3b3bb33b33b3b3b3333393b3b3b33b39bffb3b332333b333dd3b3333233332333333333333333333333333333444444444444a4444444444444344444444444444444444444444444444444444444444",Ei="0001000000010010000000100000000000000000000000000001000000010014000100000001001000010101100101100000000000000000000100000001111000010000000110101001110111111111000100000021001000010000000100100001000000011010000100000001111000013000000100140001000000010010";var xi=65535,Sn=40960,ar=126976,Si=new Uint8Array(12288),_i=new Uint8Array(3072),Ri=new Uint8Array(2816),Oi,Li;{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 bi(Ai,wi))e(Si,0,o,i,s),e(_i,Sn,o,i,s),e(Ri,ar,o,i,s),i>=65040&&!(o>=ar&&i<=129791)&&(t[n]=o,r[n++]=i<<5|s);Oi=t.slice(0,n),Li=r.slice(0,n)}function vi(e){return e<12288?Si[e]:e<Sn?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?_i[e-Sn]: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>=ar&&e<129792?Ri[e-ar]:e>=917504?e>921599?0:e>=917536&&e<917632||e>=917760&&e<918e3?3:2:Ii(e,Oi,Li)}var $i=Uint8Array.from(Ei,Number);function Vl(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 Ci(e,t,r){switch(t){case 3:return e&24?r===8204?e&6:(e&24)===16||Vl(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*ki(e){let t=e.length;if(t===0)return;let r=e.codePointAt(0),n=r>xi?2:1,o=vi(r),i=50200>>o&1?Ci(0,o,r):0,s=0,c=r,a=o;for(;n<t;){r=e.codePointAt(n);let l=r>xi?2:1,f=vi(r),u=$i[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)?Ci(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*Ti(e){for(let t of ki(e))yield t.segment}{let e=ki("_");$i._keep=[e,e.next()]}var Di=1e3,jl=1,Fl=60,Ml=3,Ul=.5,Bl=2e4,zl=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,ql=/^\s+$/u,Pi,Wl=e=>{let t=`${e??""}`.normalize("NFC"),r=globalThis.Intl?.Segmenter;return typeof r!="function"?Array.from(Ti(t)):(Pi??=new r(void 0,{granularity:"grapheme"}),Array.from(Pi.segment(t),({segment:n})=>n))},Hl=e=>Wl(e).reduce((t,r)=>ql.test(r)?t+Ul:zl.test(r)?t+Ml:t+1,0),Ni=({text:e="",baseDelay:t=Di,speed:r=jl}={})=>{let n=Number.isFinite(t)?Math.max(0,t):Di,o=Number.isFinite(r)&&r>0?r:1,i=Hl(e)*Fl/o,s=Math.max(n,Bl);return Math.min(n+i,s)};var cr={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Ui=1,ut="choice",je="form",fr=()=>({manual:{...cr.manual},auto:{...cr.auto},applyMode:cr.applyMode}),_n=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...fr()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},P=e=>{let t=he(e)?We(e):e;return structuredClone(t)},D=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),dr=e=>String(e),Bi=()=>({sections:[],resources:[]}),Yl=e=>D(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Bi(),Gl=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Kl=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:Gl(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),Jl=()=>({resourceId:void 0}),Xl=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},Rn=(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}},zi=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)}}},qi=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Wi=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Ui)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Ql=(e,t={})=>{let r;try{r=Wi(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:qi(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},Zl=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Ql(t,r)])),Hi=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Yf(r));return t.length>0?t:void 0},eu=e=>{!D(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!D(t))return;let r=Hi(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},Vi=(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}},tu=(e,t="viewedRegistry")=>{if(e===void 0)return Bi();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=Vi(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Vi(o,"resources",i,t);return[s.resourceId,s]})))}},Yi=(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}=Rn(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}},ru=(e,t,r)=>{if(!D(e)||!Array.isArray(e.timeline))return Lt({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((c,a)=>{if(!D(c))return[];try{let l=Yi(c,r,`rollback.timeline[${a}]`),f=ur({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:c.rollbackPolicy}),u=Hi(P(c.executedActions));return u&&(f.executedActions=u),[f]}catch{return[]}});if(n.length===0)return Lt({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(ur({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}},nu=(e,t,r)=>{if(!D(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=$n(t),o=Yi(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?it(P(e.variables),t.resources?.variables??{}):{},s=gu({loadedContextRuntime:D(e.runtime)?P(e.runtime):{}}),c={currentPointerMode:"read",pointers:{read:o},configuration:D(e.configuration)?P(e.configuration):{},views:Array.isArray(e.views)?P(e.views):[],bgm:D(e.bgm)?P(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:ru(e.rollback,o,t)};return s&&(c.runtime=s),c},ou=(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)=>nu(r,t,n))}},iu=(e,t)=>{if(!D(e))throw new Error("Malformed save slot.");let r=Wi(e.formatVersion);return{...e,formatVersion:r,state:ou(e.state,t)}},ji=(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=P(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},su=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:ji(e.confirmActions,"confirmActions",{required:!0}),cancelActions:ji(e.cancelActions,"cancelActions")}},ft=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},au=e=>(D(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),dt=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},Gi=e=>{if(!(!D(e)||!e.animations))return{animations:P(e.animations)}},cu=(e,t)=>{let r=Gi(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},lu=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},uu=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},lr=e=>String(e??""),Ki=(e,t)=>{let r=lr(t);return e?.trim===!0?r.trim():r},fu=e=>D(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>D(t)).map(([t,r])=>[t,{id:t,...P(r)}])):{},du=(e,t)=>{if(!t||!D(e.global.formDrafts))return;let r=e.global.formDrafts[t];return D(r)?r:void 0},Ji=(e,t)=>{let r=au(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},On=(e,t)=>{let r=Ki(e,t);return e?.required===!0&&r.length===0?"required":null},pu=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=le({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:Ye(n.slice(0,o+1).map(i=>i.actions||{}))},hu=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=lu(t),o=uu(r,n);if(!n||!o)return null;let i=du(e,o),s=fu(t),c=hr({state:e}),a={},l=[],f={},u=!0;return Object.entries(s).forEach(([d,p])=>{let h=lr(c?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},d)?lr(i.values[d]):h,y=i?.touched?.[d]===!0,I=On(p,g),A=i?.submitted||y?I:null,v=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,_={id:d,variableId:p.variableId,value:g,initialValue:h,valid:!I,error:A,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...v!==void 0?{maxLength:v}:{}};I&&(u=!1),a[d]=_,l.push(_),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:P(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:P(t.cancelActions??{})}}}},Ze=[],Fi="line",Ln="interaction",ur=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),$n=e=>{let{contextVariableDefaultValues:t}=Gt(e??{});return P(t)},Xi=()=>({...P(vt)}),Qi=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:P(r),hasLoadedValues:!1};if(!D(e))throw new Error(`Malformed ${n}.`);let o=P(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Zi(s,P(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},mu=({loadedGlobalRuntime:e={}})=>Qi({loadedRuntime:e,runtimeIds:Xr,defaults:Ge,path:"global.runtime"}).runtimeState,gu=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=Qi({loadedRuntime:e,runtimeIds:Qr,defaults:Xi(),path:"context.runtime"});return r?t:void 0},pr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},yu=e=>e.runtime?(Qr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=P(vt[t]))}),e.runtime):(e.runtime=Xi(),e.runtime),bu=e=>Uo(e.global),Iu=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:bu(e)}})},Au=e=>Mo[e],wu=(e,t)=>{let r=Au(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}"`)},Zi=(e,t)=>{if(wu(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},es=(e,t,r)=>{let n=Zi(t,r);if(t in vt){let o=pr(e);if(!o)return n;let i=yu(o);return i[t]=n,n}return e.global[t]=n,n},ts=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:P(e)},configuration:{},views:[],bgm:Jl(),variables:$n(t),rollback:Lt({pointer:e})}),pt=e=>e?(e.currentPointerMode="read",D(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Eu=(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=ts({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,xu(e,{queueRender:t}),o},xu=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,ft(e),dt(e),e.global.nextLineConfig=fr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},rs=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},Lt=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[ur({sectionId:e.sectionId,lineId:e.lineId})]:[]}},tt=(e,t={})=>{if(e?.rollback)return rs(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=Lt({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},kn=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=tt(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(ur(t)),n.currentIndex=n.timeline.length-1},vu=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=Ze[Ze.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)},Cu=({state:e},t={})=>{let r=t?.source===Fi?Fi:Ln,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:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Ze.push({checkpointIndex:o.currentIndex,source:r}),e)},Su=({state:e})=>(Ze.pop(),e),Se=(e,t,r)=>{let o=Ze[Ze.length-1]?.source??Ln;if(!Gf(t,o))return;let i=vu(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:P(r)}))},Mi=(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(De(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Kt(l,o),Jt(f,i,o),Hr(f,i,s,o,{roundTo:c}),l==="context"&&(r.variables[o]=Xt(r.variables[o],i,s,{roundTo:c}))}},_u=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{Kf(e,r,n)})},Ru=(e,t)=>{let{sectionId:r,lineId:n}=t,s=le({state:e},{sectionId:r})?.lines?.find(c=>c.id===n)?.actions;s&&Object.entries(s).forEach(([c,a])=>{Is(e,c,a)})},ns=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=tt(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&kt({state:e}),e.global.skipMode&&Fe({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=$n(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=P(cr),e.global.overlayStack=[],ft(e),dt(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let c=i;c<=t;c++)c>i&&_n(e),Ru(e,n.timeline[c]),_u(e,n.timeline[c]);let s=pt(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},Ou=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;zi(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}=Gt(t),p={...d,...it(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:tu(s,"accountViewedRegistry"),nextLineConfig:fr(),saveSlots:Zl(n),overlayStack:[],variables:p,...mu({loadedGlobalRuntime:i})},contexts:[ts({pointer:u,projectData:t})]}},Lu=({state:e})=>e.global.overlayStack||[],$u=({state:e})=>e.global.pendingEffects,os=({state:e})=>e.global.skipMode,ku=({state:e})=>e.global.autoMode,is=({state:e})=>e.global.dialogueUIHidden,ss=({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=le({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=Et({variables:{...e.global?.variables??{},...pr(e)?.variables??{}},runtime:Ke(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let u of c){let d=u.actions||{};if(l=Ye([l,d]),!d.dialogue)continue;let p=l.dialogue||{},h=Yt({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:f}),g=Kl({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},Tu=({state:e})=>e.global.confirmDialog??null,$t=({state:e},{pointer:t}={})=>{let r=t??be({state:e})?.pointer,n=pu({state:e,pointer:r});return hu({state:e,form:n.form,pointer:r})},Du=({state:e},{pointer:t}={})=>!!$t({state:e},{pointer:t}),Ie=({state:e},{pointer:t}={})=>{let r=$t({state:e},{pointer:t});if(r)return{source:je,formId:r.id,formKey:r.key};let n=as({state:e,pointer:t});return n?{source:ut,resourceId:n}:null},Pu=({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=le({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},Nu=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},Tn=({state:e},t)=>Pu({state:e,registry:e.global.accountViewedRegistry},t),Vu=({state:e},t)=>Nu({registry:e.global.accountViewedRegistry},t),ju=({state:e})=>e.global.nextLineConfig,as=({state:e,pointer:t}={})=>{let r=t??be({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=le({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},cs=({state:e})=>!!as({state:e}),Fu=({state:e})=>structuredClone(e),ls=({state:e})=>e.global.saveSlots,Mu=({state:e},t)=>{let r=t?.slotId,n=dr(r);return e.global.saveSlots[n]},Dn=({state:e})=>Ke(e),Uu=({state:e},t)=>Pe(e,t?.runtimeId),hr=({state:e})=>{let t={...e.global?.variables??{},...pr(e)?.variables??{}};return Et({variables:t,runtime:Ke(e),variableConfigs:e.projectData.resources?.variables??{}})},be=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},le=({state:e},t)=>{let{sectionId:r}=t;return Rn(e.projectData,r).section},mr=({state:e})=>{let t=be({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=le({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},us=({state:e})=>{let{sectionId:t,lineId:r}=be({state:e}).pointer,o=le({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 Ye(c)},Bu=e=>{let t=mr({state:e})?.actions?.dialogue;if(t?.clear===!0||!Array.isArray(t?.content))return"";let r=hr({state:e});return t.content.map(n=>`${st(n?.text,{variables:r})??""}`).join("")},gr=({state:e})=>Ni({text:Bu(e),baseDelay:Pe(e,"autoForwardDelay"),speed:Pe(e,"autoForwardSpeed")}),zu=({state:e})=>{let t=fs({state:e}),n=mr({state:e})?.actions??{},o=Ye([t??{},n]);return Yr(t??{},o??{})},qu=({state:e},{sectionId:t})=>{let r=le({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},c=Ye([o,s]),a=Yr(o,c);n.push({id:i.id,changes:a,presentationState:c}),o=Gr(c)}return n},Wu=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=qu({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},fs=({state:e})=>{let{sectionId:t,lineId:r}=be({state:e}).pointer,o=le({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 Gr(Ye(c))},Pn=({state:e},{slotsPerPage:t=6}={})=>{let o=((Dn({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[dr(c)]||{};i.push({...a,slotId:c})}return{saveSlots:i}},Hu=ls,Yu=Pn,Gu=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},Ku=({state:e},t={})=>{let r=us({state:e}),n=fs({state:e}),o=mr({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:P(i)}:o,c=i?.animations&&n===null?{}:n,{sectionId:a}=be({state:e}).pointer,{sceneId:l}=Rn(e.projectData,a),f=Dn({state:e}),u=t?.activePersistentAnimations??[],d=t?.restoredPersistentAnimations??[],p=$t({state:e}),h=cs({state:e}),g=hr({state:e}),{saveSlots:y}=Pn({state:e}),I=Gu(e);return yi({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:ws({state:e}),skipOnlyViewedLines:!f.skipUnseenText,isLineCompleted:f.isLineCompleted,skipTransitionsAndAnimations:!!f.skipTransitionsAndAnimations||I,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:ss({state:e}),saveSlots:y,variables:g,runtime:f,activePersistentAnimations:u,restoredPersistentAnimations:d})},Ju=({state:e},t)=>(e.global.confirmDialog=su(t),e.global.pendingEffects.push({name:"render"}),e),Xu=({state:e})=>(e.global.confirmDialog&&(ft(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),Zu=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Se(e,"popOverlay",void 0),e),ef=({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),tf=({state:e})=>(e.global.overlayStack=[],ft(e),dt(e),e.global.pendingEffects.push({name:"render"}),Se(e,"clearOverlays",void 0),e),rf=(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"})},yr=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,cu(e,r),dt(e);let n=Ie({state:e},{pointer:t}),o=n?.source===ut,i=n?.source===je;return rf(e,{activeInteraction:n}),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},br=(e,t,r)=>{!(t?.source===ut||t?.source===je)||r||!e.global.skipMode||e.global.pendingEffects.push({name:"startSkipNextTimer"})},ds=({state:e})=>(Ie({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:gr({state:e})}}),e.global.pendingEffects.push({name:"render"})),e),kt=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),nf=({state:e})=>{let t=e.global.autoMode;return Ie({state:e})&&!t||(t?kt({state:e}):ds({state:e})),e},ps=({state:e})=>(Ie({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),of=({state:e})=>{let t=os({state:e});return Ie({state:e})&&!t||(t?Fe({state:e}):ps({state:e})),e},Ir=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Se(e,"showDialogueUI",void 0),e),hs=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Se(e,"hideDialogueUI",void 0),e),sf=({state:e})=>(is({state:e})?Ir({state:e}):hs({state:e}),e),Me=(e,t,r)=>(es(e,t,r),Iu(e),e.global.pendingEffects.push({name:"render"}),e),Tt=(e,t,r,n)=>{let o=es(e,t,r);return e.global.pendingEffects.push({name:"render"}),Se(e,n,{value:o}),e},af=({state:e},t)=>Me(e,"dialogueTextSpeed",t?.value),cf=({state:e},t)=>Me(e,"autoForwardDelay",t?.value),lf=({state:e},t)=>Me(e,"autoForwardSpeed",t?.value),uf=({state:e},t)=>Me(e,"skipUnseenText",t?.value),ff=({state:e},t)=>Me(e,"skipTransitionsAndAnimations",t?.value),df=({state:e},t)=>Me(e,"soundVolume",t?.value),pf=({state:e},t)=>Me(e,"musicVolume",t?.value),hf=({state:e},t)=>Me(e,"muteAll",t?.value),mf=({state:e},t)=>Tt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),gf=({state:e})=>{let t=Pe(e,"saveLoadPagination")+1;return Tt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},yf=({state:e})=>{let t=Pe(e,"saveLoadPagination")-1;return Tt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},bf=({state:e},t)=>Tt(e,"menuPage",t?.value,"setMenuPage"),If=({state:e},t)=>Tt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Af=({state:e})=>(e.global.pendingEffects=[],e),wf=({state:e},t)=>(e.global.pendingEffects.push(t),e),ms=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!Gi(n),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(r&&!Eu(e,{queueRender:!o}))return e;let c=Ie({state:e});r&&e.global.skipMode&&Fe({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let f=pt(a),u=f.read;r||et(e,{sectionId:u?.sectionId,lineId:u?.lineId}),a.rollback||tt(a,{compatibilityAnchor:!0}),f.read={sectionId:t,lineId:s.id},r?a.rollback=Lt({pointer:f.read}):kn(e,{sectionId:t,lineId:s.id})}let{activeInteraction:l}=yr(e,a?.pointers?.read,{screenTransition:n});return br(e,c,l),e},Ef=({state:e},t)=>ms(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),gs=e=>(e.global.accountViewedRegistry=Yl(e.global.accountViewedRegistry),e.global.accountViewedRegistry),Nn=(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:P(r.value)}))}})},ys=(e,t)=>{Nn(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:[]}}])},xf=(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=le({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},et=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;xf(e,gs(e),t)&&ys(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},vf=({state:e},t)=>(et(e,t),e.global.pendingEffects.push({name:"render"}),e),Cf=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=gs(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),ys(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},bs=({state:e},t)=>{let r=Xl(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=Ie({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},Sf=({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=dr(r),s=P(e.contexts);s?.forEach(l=>{pt(l),rs(l.rollback),eu(l.rollback)});let c={contexts:s},a={formatVersion:Ui,slotId:qi(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},_f=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=dr(r),o=e.global.saveSlots[n];if(o){let i=iu(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=fr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,ft(e),dt(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},Rf=({state:e},t)=>{let{projectData:r}=t;zi(r),e.projectData=r;let n=r?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=Gt(r??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...it(e.global.variables,n)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...it(s.variables,n)})}),ft(e),dt(e),e.global.pendingEffects.push({name:"render"}),e},Of=({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&&!le({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),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(u=>u.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let a=Ie({state:e}),l=pt(o);l.read={sectionId:i,lineId:n};let{activeInteraction:f}=yr(e,l.read);return br(e,a,f),e},Lf=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return Ir({state:e}),e;let r=Ie({state:e});if(r?.source===ut&&t?.bypassChoice!==!0||r?.source===je&&t?._interactionSource!==je)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let f=be({state:e})?.pointer,u=f?.sectionId,d=f?.lineId;u&&d&&et(e,{sectionId:u,lineId:d}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&!r&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:gr({state:e})}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&!r&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=be({state:e})?.pointer,o=n?.sectionId,i=le({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],c=i?.lines||[],l=c.findIndex(f=>f.id===n?.lineId)+1;if(l<c.length){let f=c[l],u=!Pe(e,"skipUnseenText");if(e.global.skipMode&&u&&!Tn({state:e},{sectionId:o,lineId:f.id}))return Fe({state:e}),e;if(s&&!s.rollback&&tt(s,{compatibilityAnchor:!0}),s){let p=pt(s),h=p.read?.lineId;h&&o&&et(e,{sectionId:o,lineId:h}),p.read={sectionId:o,lineId:f.id}}kn(e,{sectionId:o,lineId:f.id}),_n(e);let{activeInteraction:d}=yr(e,{sectionId:o,lineId:f.id});br(e,r,d)}else e.global.autoMode&&kt({state:e}),e.global.skipMode&&Fe({state:e});return e},$f=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ie({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:gr({state:e})}});let r=be({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&et(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},kf=({state:e},t)=>ms(e,{sectionId:t?.sectionId,screen:t?.screen}),Tf=({state:e},t)=>{let r=t?._conditionalContinuation===!0;if(e.global.dialogueUIHidden&&!r)return Ir({state:e}),e;let n=Ie({state:e});if(n?.source===ut&&t?.bypassChoice!==!0||n?.source===je&&t?._interactionSource!==je||n&&n.source!==ut&&n.source!==je)return e;let o=be({state:e})?.pointer,i=o?.sectionId,s=le({state:e},{sectionId:i}),c=e.contexts[e.contexts.length-1],a=s?.lines||[],f=a.findIndex(u=>u.id===o?.lineId)+1;if(f<a.length){let u=a[f],d=!Pe(e,"skipUnseenText");if(e.global.skipMode&&d&&!Tn({state:e},{sectionId:i,lineId:u.id})&&(Fe({state:e}),!r))return e;if(c&&!c.rollback&&tt(c,{compatibilityAnchor:!0}),c){let h=pt(c),g=h.read?.lineId;g&&i&&et(e,{sectionId:i,lineId:g}),h.read={sectionId:i,lineId:u.id}}kn(e,{sectionId:i,lineId:u.id}),_n(e);let{activeInteraction:p}=yr(e,{sectionId:i,lineId:u.id});br(e,n,p)}else e.global.autoMode&&kt({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},Vn=(e,t={})=>{let r=$t({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},Df=(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(De(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return Kt(n,t.variableId),Jt(o,"set",t.variableId),{variableConfig:r,scope:n}},Pf=(e,t)=>({id:e.id,key:e.key,valid:!0,values:P(t),fields:P(e.fields),fieldList:P(e.fieldList)}),Nf=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=be({state:e})?.pointer,r=t?.sectionId,n=t?.lineId;r&&n&&et(e,{sectionId:r,lineId:n})},Vf=({state:e},t={})=>{let r=Vn(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=Ji(e,r.key),i=lr(t.value),s=r.fields[n],c=On(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},jf=({state:e},t={})=>{let r=Vn(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=Ji(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=On(d,p);n.touched[u]=!0,h&&(i[u]=h),o[u]=Ki(d,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:P(i),form:{id:r.id,key:r.key,values:P(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}=Df(e,d),h=p==="context"?s.variables:e.global.variables,g=o[u];h[d.variableId]=Xt(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:P(h[d.variableId])})}),c&&Se(e,"updateVariable",{id:"submitForm",operations:l}),Nn(e,a);let f=Pf(r,o);return Nf(e),delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:f}},Ff=({state:e},t={})=>{let r=Vn(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:P(r.values),fields:P(r.fields),fieldList:P(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},Mf=({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(De(d))throw new Error(`Cannot update computed variable: ${a}`);if(d?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);Kt(p,a),Jt(h,l,a),Hr(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]=Xt(g[a],l,f,{roundTo:u}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:P(g[a])})}),i&&Se(e,"updateVariable",{id:r,operations:c}),Nn(e,s),e.global.pendingEffects.push({name:"render"}),e},Uf=e=>(t,r)=>e({state:t},r),Bf=e=>({variables:Et({variables:{...e.global?.variables??{},...pr(e)?.variables??{}},runtime:Ke(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:Ke(e)}),zf=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")},qf=(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")},Wf=(e,t)=>{zf(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(qf(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!wt(n.when,Bf(e)))){Object.entries(n.actions).forEach(([i,s])=>{Is(e,i,s)});return}}},Hf={conditional:{replayLine:Wf},updateVariable:{recordSources:[Ln],replayLine:Mi,replayRecorded:Mi,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Uf(bs)}},Ar=e=>Hf[e]??null,Yf=e=>Ar(e)?.persistInSaveSlot===!0,Gf=(e,t)=>{let r=Ar(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},Kf=(e,t,r)=>{Ar(t)?.replayRecorded?.(e,r)},Is=(e,t,r)=>{Ar(t)?.replayLine?.(e,r)},As=({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}},ws=({state:e})=>As({state:e},{offset:-1})!==null,Jf=({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=tt(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:ns(e,i)},Xf=({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=tt(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:ns(e,c)},Es=e=>{let t=Ou(e);return vo(t,{selectPendingEffects:$u,selectSkipMode:os,selectAutoMode:ku,selectIsChoiceVisible:cs,selectIsFormVisible:Du,selectActiveInteraction:Ie,selectActiveForm:$t,selectDialogueUIHidden:is,selectDialogueHistory:ss,selectConfirmDialog:Tu,selectIsLineAccountViewed:Tn,selectIsResourceAccountViewed:Vu,selectNextLineConfig:ju,selectSystemState:Fu,selectSaveSlotMap:ls,selectSaveSlots:Hu,selectSaveSlot:Mu,selectRuntime:Dn,selectRuntimeValue:Uu,selectAllVariables:hr,selectCurrentPointer:be,selectSection:le,selectCurrentLine:mr,selectPresentationState:us,selectAutoForwardTimerDelay:gr,selectPresentationChanges:zu,selectSectionLineChanges:Wu,selectSaveSlotPage:Pn,selectCurrentPageSlots:Yu,selectRenderState:Ku,selectOverlayStack:Lu,selectLineIdByOffset:As,selectCanRollback:ws,startAutoMode:ds,stopAutoMode:kt,toggleAutoMode:nf,startSkipMode:ps,stopSkipMode:Fe,toggleSkipMode:of,showDialogueUI:Ir,hideDialogueUI:hs,toggleDialogueUI:sf,setDialogueTextSpeed:af,setAutoForwardDelay:cf,setAutoForwardSpeed:lf,setSkipUnseenText:uf,setSkipTransitionsAndAnimations:ff,setSoundVolume:df,setMusicVolume:pf,setMuteAll:hf,setSaveLoadPagination:mf,incrementSaveLoadPagination:gf,decrementSaveLoadPagination:yf,setMenuPage:bf,setMenuEntryPoint:If,showConfirmDialog:Ju,hideConfirmDialog:Xu,resetStoryAtSection:Ef,clearPendingEffects:Af,appendPendingEffect:wf,beginRollbackActionBatch:Cu,endRollbackActionBatch:Su,addViewedLine:vf,addViewedResource:Cf,setNextLineConfig:bs,saveSlot:Sf,loadSlot:_f,updateProjectData:Rf,sectionTransition:kf,jumpToLine:Of,nextLine:Lf,markLineCompleted:$f,rollbackToLine:Xf,rollbackByOffset:Jf,pushOverlay:Qu,popOverlay:Zu,replaceLastOverlay:ef,clearOverlays:tf,updateFormField:Vf,submitForm:jf,cancelForm:Ff,updateVariable:Mf,nextLineFromSystem:Tf},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var Qf="route-engine",Zf="projectPersistence";var vs=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),Z=e=>Object.prototype.toString.call(e)==="[object Object]",xs="variables.",ed=(e={})=>{let t=Z(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!Z(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)}:!Z(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},td=(e={})=>{let t=Z(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!Z(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)}:!Z(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},rd=(e,t)=>{let r=td(e),n=ed(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}},Cs=(e={})=>{let t=Z(e)?e:{};return{saveSlots:Z(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:Z(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:Z(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:Z(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:Z(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},nd=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!Z(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(xs)?t.path.slice(xs.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}].`)})},od=(e,t)=>{let r={};return nd(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=rd(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},jn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},id=e=>{let t=jn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},sd=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},ad=({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}".`))}}),cd=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.`))}})},Dt=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=Cs(l.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...vs(),...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}".`))}})},ld=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}".`))}})},Fn=(e={})=>{let{indexedDB:t,databaseName:r=Qf,objectStoreName:n=Zf,namespace:o}=e,i=sd(t),s=id(o),c=ad({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let a=await cd({databasePromise:c,objectStoreName:n,namespace:s});return{...vs(),...Cs(a)}},clear:async()=>ld({databasePromise:c,objectStoreName:n,namespace:s}),saveSlots:async a=>Dt({databasePromise:c,objectStoreName:n,namespace:s,patch:{saveSlots:Z(a)?a:{}}}),saveGlobalDeviceVariables:async a=>Dt({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:Z(a)?a:{}}}),saveGlobalAccountVariables:async a=>Dt({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalAccountVariables:Z(a)?a:{}}}),saveGlobalRuntime:async a=>Dt({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalRuntime:Z(a)?a:{}}}),applyScopedDataUpdates:async a=>Dt({databasePromise:c,objectStoreName:n,namespace:s,patch:l=>od(l,a)})}},ud=Fn;var fd=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),dd=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),Ss="conditional",Un=Symbol("conditionalAutoContinue"),pd=new Set(["sectionTransition","resetStoryAtSection"]),Mn="form",hd=new Set(["submitForm","cancelForm"]),Pt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),wr=e=>e?.type===Un;function Bn(e){let t,r=0,n=null,o=0,i=!1,s=0,c=new Map,a=new Map,l=new Map,{handlePendingEffects:f}=e,u=(b=new Map,E=Date.now())=>new Map(Array.from(b.entries()).filter(([,S])=>E<S.expiresAt).map(([S,V])=>[S,{animation:structuredClone(V.animation),startedAt:V.startedAt,expiresAt:V.expiresAt}])),d=(b=new Map)=>Array.from(b.values()).map(E=>structuredClone(E.animation)),p=(b=Date.now())=>{c=new Map(Array.from(c.entries()).filter(([,E])=>b<E.expiresAt))},h=()=>{if(!(o>0||i)){i=!0;try{for(;t.selectPendingEffects().length>0;){let b=[...t.selectPendingEffects()];t.clearPendingEffects();try{f(b)}catch(E){throw t.clearPendingEffects(),b.forEach(S=>{t.appendPendingEffect(S)}),E}}}finally{i=!1}}},g=b=>{o+=1;try{return b()}finally{o-=1,h()}},y=({initialState:b,namespace:E})=>{t=Es(b),r=0,n=jn(E),o=0,i=!1,s=0,c=new Map,a=new Map,l=new Map,t.appendPendingEffect({name:"handleLineActions"}),h()},I=()=>n,A=()=>t.selectPresentationState(),v=()=>t.selectPresentationChanges(),_=b=>t.selectSectionLineChanges(b),k=(b={})=>{r+=1;let E=Date.now();p(E);let S=a.size>0,V=u(c,E),B=S?u(a,E):new Map,de={...t.selectRenderState({activePersistentAnimations:d(V),restoredPersistentAnimations:d(B)}),id:`render-${r}`};return l.set(de.id,{builtAt:E,persistentAnimationSessions:new Map([...B.entries(),...V.entries()]),usedRestoredPersistentAnimationSessions:S}),de},N=(b={})=>k(b),w=(b={})=>k(b),M=b=>{let E=typeof b?.id=="string"&&b.id.length>0?b.id:null,S=E?l.get(E):null;E&&l.delete(E);let V=new Map;ti(b?.animations).forEach(B=>{let Q=nr(B);if(!Q)return;let de=S?.persistentAnimationSessions?.get(Q)??c.get(Q),ht=Math.max(0,ni(B)),mt=de?.startedAt??S?.builtAt??Date.now();V.set(Q,{animation:structuredClone(B),startedAt:mt,expiresAt:mt+ht})}),c=V,S?.usedRestoredPersistentAnimationSessions&&(a=new Map)},U=()=>t.selectSystemState(),H=()=>t.selectSaveSlotMap(),j=b=>t.selectSaveSlot(b),W=b=>t.selectSaveSlotPage(b),K=()=>t.selectSkipMode(),ee=()=>t.selectAutoMode(),ve=()=>t.selectRuntime(),te=()=>t.selectIsChoiceVisible(),X=()=>t.selectIsFormVisible(),re=()=>t.selectActiveInteraction(),ue=()=>t.selectPendingEffects().some(b=>b?.name==="handleLineActions"||b?.name==="render"),Y=(b,E,S={})=>!Pt(E)||b!=="nextLine"?E:S.bypassChoice===!0?{...E,bypassChoice:!0}:S.interactionSource===Mn?{...E,_interactionSource:Mn}:E,ne=(b={})=>({type:Un,payload:Y("nextLine",{_conditionalContinuation:!0},b)}),oe=(b,E)=>wr(b)?{type:Un,payload:{...b.payload,...E.payload}}:E,C=(b,E)=>{if(!t[b])return;pd.has(b)&&(s+=1),fd.has(b)&&(dd.has(b)?a=u(c):a=new Map,c=new Map);let S=t[b](E);return h(),S},R=(b,E,S)=>{let V=t.selectCurrentPointer()?.pointer;E!==V||S!==s||(t.appendPendingEffect({name:"clearAutoNextTimer"}),t.appendPendingEffect({name:"clearNextLineConfigTimer"}),C("nextLineFromSystem",b.payload))},T=(b,E={})=>g(()=>{let S,V=t.selectCurrentPointer()?.pointer??null,B=s;t.beginRollbackActionBatch({source:E.rollbackSource});try{S=b()}finally{t.endRollbackActionBatch({})}wr(S)&&R(S,V,B)}),ie=(b,E,S,V={})=>{if(b===Ss)return T(()=>{let B=F(S),Q=Kr({[b]:E},B);return qn(Q[b],S,V)},V);C(b,E)},se=(b,E)=>{ie(b,E)},F=b=>{if(!b)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(b,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:E,...S}=b,V=t.selectAllVariables?t.selectAllVariables():void 0;return{...S,_event:E,variables:V,runtime:t.selectRuntime?t.selectRuntime():{}}},Ue=b=>{if(!Pt(b))throw new Error("conditional action payload must be an object");if(!Array.isArray(b.branches))throw new Error("conditional action requires branches array");if(b.branches.length===0)throw new Error("conditional action requires at least one branch")},rt=(b,E,S)=>{if(!Pt(b))throw new Error(`conditional branch at index ${E} must be an object`);if(!Pt(b.actions))throw new Error(`conditional branch at index ${E} requires actions object`);if(!Object.prototype.hasOwnProperty.call(b,"when")&&E!==S-1)throw new Error("conditional else branch must be the last branch")},qn=(b,E,S)=>{Ue(b);let V=ne(S);for(let B=0;B<b.branches.length;B+=1){let Q=b.branches[B];rt(Q,B,b.branches.length);let de=F(E);if(Object.prototype.hasOwnProperty.call(Q,"when")&&!wt(Q.when,de))continue;let mt=xr(Q.actions,E,S);return wr(mt)?oe(V,mt):V}return V},Os=(b,E)=>({...b??{},_form:E}),Ls=(b,E,S,V)=>{let B=C(b,E),Q=B?.submitted===!0&&B.valid===!0,de=B?.cancelled===!0;if(!(!Q&&!de)&&Pt(E.actions))return xr(E.actions,Os(S,B.form),{...V,interactionSource:Mn})},$s=(b,E,S,V)=>{let B=F(S),de=Kr({[b]:E},B)[b];if(b===Ss)return qn(de,S,V);let ht=Y(b,de,V);if(hd.has(b))return Ls(b,ht,S,V);C(b,ht)},xr=(b,E,S)=>{let V;return Object.entries(b).forEach(([B,Q])=>{let de=$s(B,Q,E,S);wr(de)&&(V=oe(V,de))}),V},Wn=(b,E,S={})=>T(()=>xr(b,E,S),S),ks=b=>{let E=t.selectCurrentPointer()?.pointer;if(b!==E||t.selectActiveInteraction())return;let S=t.selectNextLineConfig();S?.auto?.enabled&&S.auto.trigger==="fromStart"&&t.appendPendingEffect({name:"nextLineConfigTimer",payload:{delay:S.auto.delay}})};return{init:y,handleAction:ie,handleInternalAction:se,handleActions:Wn,selectRenderState:N,prepareRenderState:w,commitRenderState:M,selectPresentationState:A,selectPresentationChanges:v,selectSectionLineChanges:_,selectSystemState:U,selectSaveSlotMap:H,selectSaveSlot:j,selectSaveSlotPage:W,selectSaveSlots:H,selectRuntime:ve,selectIsChoiceVisible:te,selectIsFormVisible:X,selectActiveInteraction:re,selectHasPendingRenderWork:ue,handleLineActions:()=>g(()=>{let b=t.selectCurrentPointer()?.pointer,E=t.selectCurrentLine(),S=!1;return E?.actions&&(Wn(E.actions,void 0,{rollbackSource:"line"}),S=!0),ks(b),S}),getNamespace:I}}var zn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},md=80,Rs=({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)},gd=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&Rs({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},yd=({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),Er(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},bd=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Id=({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??md;r.getElapsed()>=c&&(r.setElapsed(0),Er(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},Ad=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},wd=({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),Er(e,"nextLineFromSystem",{}),t.remove(i),r.getCallback()===i&&r.setCallback(null))};r.setCallback(i),t.add(i)},Ed=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},xd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},vd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},Cd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},Sd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},_d=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},_s={render:Rs,saveSlots:xd,saveGlobalDeviceVariables:vd,saveGlobalAccountVariables:Cd,saveGlobalRuntime:Sd,applyScopedDataUpdates:_d,handleLineActions:gd,startAutoNextTimer:yd,clearAutoNextTimer:bd,startSkipNextTimer:Id,clearSkipNextTimer:Ad,nextLineConfigTimer:wd,clearNextLineConfigTimer:Ed},Rd=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Er=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},Od=(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(!Rd.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},Ld=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:c})=>{let a=zn(),l=zn(),f=zn(),u=s??null,d=Promise.resolve(),p=null,h=null,g=!1,y=0,I=C=>{if(o){o(C);return}console.error("RouteEngine persistence write failed.",C)},A=()=>{if(u)return u;let C=e();return u=Fn({indexedDB:i,namespace:c??C?.getNamespace?.()}),u},v=C=>{d=d.catch(()=>{}).then(()=>{let R=A();return C(R)}).catch(R=>{I(R)})},_=C=>{let R=typeof C?.id=="string"&&C.id.length>0?C.id:null;y+=1,p=R,g=!1},k=()=>y,N=(C={})=>{if(C?.aborted===!0)return!1;let R=typeof C?.id=="string"&&C.id.length>0?C.id:null;return R?R!==p||R===h?!1:(h=R,!0):p!==null||g?!1:(g=!0,!0)},w=(C,R={})=>{if(C!=="renderComplete"||!N(R))return!1;let T=e();return Er(T,"markLineCompleted",{}),!0},M=new Set(["updateFormField","submitForm","cancelForm"]),U=new Set(["updateVariable"]),H=C=>typeof C?.selectActiveInteraction=="function"?C.selectActiveInteraction():typeof C?.selectIsChoiceVisible=="function"&&C.selectIsChoiceVisible()?{source:"choice"}:null,j=C=>C?._formKey??C?.formKey,W=(C,R)=>j(C)===R?.formKey,K=(C,R)=>!C||typeof C!="object"||Array.isArray(C)?!1:C._interactionSource===R?.source,ee=(C,R)=>K(C,R)?R.source==="form"?W(C,R):!0:!1,ve=(C,R)=>!C||typeof C!="object"||Array.isArray(C)||R?.source!=="form"?!1:W(C,R),te=(C={})=>Object.keys(C).some(R=>M.has(R)),X=(C={},R)=>Object.entries(C).some(([T,ie])=>M.has(T)&&ve(ie,R)),re=(C={})=>Object.keys(C).length>0&&Object.keys(C).every(R=>U.has(R)),ue=(C={},R)=>{let T=C?.actions;return R?.source==="form"?!T||typeof T!="object"||Array.isArray(T)?!1:X(T,R)?!0:te(T)?!1:re(T):ee(C,R)?!0:!T||typeof T!="object"||Array.isArray(T)?!1:Object.values(T).some(ie=>ee(ie,R))},Y=(C,R={})=>{if(!R?.actions)return!1;let T=H(C);return!T||T.source==="choice"?!1:!ue(R,T)},ne=({preprocessPayload:C,onEvent:R}={})=>async(T,ie={})=>{let se=e();if(Y(se,ie))return R?.(T,ie);let F=await C?.(T,ie)??ie;if(Y(se,F))return R?.(T,F);if(w(T,F),F?.actions){let Ue=F?._event?{_event:F._event}:F?.event?{_event:F.event}:void 0,rt;F?.bypassChoice===!0?rt={bypassChoice:!0}:F?._interactionSource&&(rt={interactionSource:F._interactionSource}),rt?se.handleActions(F.actions,Ue,rt):se.handleActions(F.actions,Ue)}return R?.(T,F)},oe=C=>{let R=e(),T=Od(C),ie=T.some(F=>F.name==="handleLineActions");T.forEach(F=>{if(!_s[F.name]&&!n)throw new Error(`Unhandled pending effect "${F.name}".`)});let se={engine:R,routeGraphics:t,ticker:r,autoTimer:a,skipTimer:l,nextLineConfigTimerState:f,trackRenderDispatch:_,getRenderDispatchCount:k,enqueuePersistenceWrite:v};for(let F of T){if(ie&&F.name==="render")continue;let Ue=_s[F.name];if(Ue){Ue(se,F.payload);continue}n(F,se)}};return oe.handleRouteGraphicsEvent=w,oe.createRouteGraphicsEventHandler=ne,oe},$d=Ld;var kd=(e,t={})=>{let{resources:r={}}=t;return wn(e,r)};var uh=Bn;export{Zr as DEFAULT_VISUAL_LAYER,at as RENDER_LAYER,_e as VISUAL_LAYER,$d as createEffectsHandler,ud as createIndexedDbPersistence,uh as default,Ma as resolveComputedVariables,kd 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