route-engine-js 1.9.0 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/RouteEngine.js +1 -1
- package/package.json +2 -2
package/dist/RouteEngine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var co=Object.defineProperty;var lo=(e,t)=>{for(var n in t)co(e,n,{get:t[n],enumerable:!0})};var In=Symbol.for("immer-nothing"),hn=Symbol.for("immer-draftable"),G=Symbol.for("immer-state");function Z(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var xe=Object.getPrototypeOf;function se(e){return!!e&&!!e[G]}function ue(e){return e?An(e)||Array.isArray(e)||!!e[hn]||!!e.constructor?.[hn]||qe(e)||Ke(e):!1}var uo=Object.prototype.constructor.toString();function An(e){if(!e||typeof e!="object")return!1;let t=xe(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)===uo}function ze(e,t){He(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function He(e){let t=e[G];return t?t.type_:Array.isArray(e)?1:qe(e)?2:Ke(e)?3:0}function gt(e,t){return He(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function wn(e,t,n){let r=He(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function fo(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function qe(e){return e instanceof Map}function Ke(e){return e instanceof Set}function le(e){return e.copy_||e.base_}function mt(e,t){if(qe(e))return new Map(e);if(Ke(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=An(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[G];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let s=o[i],a=r[s];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(r[s]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[s]})}return Object.create(xe(e),r)}else{let r=xe(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function wt(e,t=!1){return Ge(e)||se(e)||!ue(e)||(He(e)>1&&(e.set=e.add=e.clear=e.delete=po),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>wt(r,!0))),e}function po(){Z(2)}function Ge(e){return Object.isFrozen(e)}var ho={};function fe(e){let t=ho[e];return t||Z(0,e),t}var $e;function xn(){return $e}function go(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function gn(e,t){t&&(fe("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function yt(e){bt(e),e.drafts_.forEach(mo),e.drafts_=null}function bt(e){e===$e&&($e=e.parent_)}function mn(e){return $e=go($e,e)}function mo(e){let t=e[G];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function yn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[G].modified_&&(yt(t),Z(4)),ue(e)&&(e=We(t,e),t.parent_||Ye(t,e)),t.patches_&&fe("Patches").generateReplacementPatches_(n[G].base_,e,t.patches_,t.inversePatches_)):e=We(t,n,[]),yt(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==In?e:void 0}function We(e,t,n){if(Ge(t))return t;let r=t[G];if(!r)return ze(t,(o,i)=>bn(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Ye(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),ze(i,(a,l)=>bn(e,r,o,a,l,n,s)),Ye(e,o,!1),n&&e.patches_&&fe("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function bn(e,t,n,r,o,i,s){if(se(o)){let a=i&&t&&t.type_!==3&&!gt(t.assigned_,r)?i.concat(r):void 0,l=We(e,o,a);if(wn(n,r,l),se(l))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(ue(o)&&!Ge(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;We(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&Ye(e,o)}}function Ye(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&wt(t,n)}function yo(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:xn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=xt;n&&(o=[r],i=ke);let{revoke:s,proxy:a}=Proxy.revocable(o,i);return r.draft_=a,r.revoke_=s,a}var xt={get(e,t){if(t===G)return e;let n=le(e);if(!gt(n,t))return bo(e,n,t);let r=n[t];return e.finalized_||!ue(r)?r:r===pt(e.base_,t)?(ht(e),e.copy_[t]=At(r,e)):r},has(e,t){return t in le(e)},ownKeys(e){return Reflect.ownKeys(le(e))},set(e,t,n){let r=En(le(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=pt(le(e),t),i=o?.[G];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(fo(n,o)&&(n!==void 0||gt(e.base_,t)))return!0;ht(e),It(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 pt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,ht(e),It(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=le(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){Z(11)},getPrototypeOf(e){return xe(e.base_)},setPrototypeOf(){Z(12)}},ke={};ze(xt,(e,t)=>{ke[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ke.deleteProperty=function(e,t){return ke.set.call(this,e,t,void 0)};ke.set=function(e,t,n){return xt.set.call(this,e[0],t,n,e[0])};function pt(e,t){let n=e[G];return(n?le(n):e)[t]}function bo(e,t,n){let r=En(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function En(e,t){if(!(t in e))return;let n=xe(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=xe(n)}}function It(e){e.modified_||(e.modified_=!0,e.parent_&&It(e.parent_))}function ht(e){e.copy_||(e.copy_=mt(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Io=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(l=i,...c){return s.produce(l,u=>n.call(this,u,...c))}}typeof n!="function"&&Z(6),r!==void 0&&typeof r!="function"&&Z(7);let o;if(ue(t)){let i=mn(this),s=At(t,void 0),a=!0;try{o=n(s),a=!1}finally{a?yt(i):bt(i)}return gn(i,r),yn(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===In&&(o=void 0),this.autoFreeze_&&wt(o,!0),r){let i=[],s=[];fe("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else Z(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...a)=>this.produceWithPatches(s,l=>t(l,...a));let r,o;return[this.produce(t,n,(s,a)=>{r=s,o=a}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){ue(e)||Z(8),se(e)&&(e=Et(e));let t=mn(this),n=At(e,void 0);return n[G].isManual_=!0,bt(t),n}finishDraft(e,t){let n=e&&e[G];(!n||!n.isManual_)&&Z(9);let{scope_:r}=n;return gn(r,t),yn(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=fe("Patches").applyPatches_;return se(e)?r(e,t):this.produce(e,o=>r(o,t))}};function At(e,t){let n=qe(e)?fe("MapSet").proxyMap_(e,t):Ke(e)?fe("MapSet").proxySet_(e,t):yo(e,t);return(t?t.scope_:xn()).drafts_.push(n),n}function Et(e){return se(e)||Z(10,e),vn(e)}function vn(e){if(!ue(e)||Ge(e))return e;let t=e[G],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=mt(e,t.scope_.immer_.useStrictShallowCopy_)}else n=mt(e,!0);return ze(n,(r,o)=>{wn(n,r,vn(o))}),t&&(t.finalized_=!1),n}var X=new Io,vt=X.produce,vc=X.produceWithPatches.bind(X),Sc=X.setAutoFreeze.bind(X),_c=X.setUseStrictShallowCopy.bind(X),Cc=X.applyPatches.bind(X),Rc=X.createDraft.bind(X),Lc=X.finishDraft.bind(X);var h={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},T={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},Oe={NOT:0};var x=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},Y=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var St=e=>{if(!e||e.trim()==="")throw new x("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new x(`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 x(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Sn=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,n]=e.split(" in ");if(!n||n.trim()==="")throw new x(`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 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 _n=(e,t,n=!1)=>{if(t===null)return new Y(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new Y(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new Y(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new Y(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},Cn=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new Y(`Unknown function '${e}' (${n})`)};var Ao=(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=C(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},C=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return M(e.var,n,r);if(e.type===h.LITERAL)return e.value;if(e.type===h.VARIABLE)return M(e.path,n,r);if(e.type===h.INTERPOLATION)return xo(e.parts,t,n,r);switch(e.type){case h.FUNCTION:return Ln(e,t,n,r);case h.BINARY:return $n(e,t,n,r);case h.UNARY:return kn(e,t,n,r);case h.CONDITIONAL:return vo(e,t,n,r);case h.LOOP:return Lo(e,t,n,r);case h.OBJECT:return ko(e,t,n,r);case h.ARRAY:return Oo(e,t,n,r);case h.PARTIAL:return Po(e,t,n,r);case h.PATH_REFERENCE:return To(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},Rn=new Map,wo=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 a=s.slice(1,-1);t.push({type:"property",value:a})}else t.push({type:"property",value:s});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},M=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=Rn.get(e);if(!r){let i=[],s="",a=0;for(let l=0;l<e.length;l++){let c=e[l];c==="["?(a++,s+=c):c==="]"?(a--,s+=c):c==="."&&a===0?s&&(i.push(s),s=""):s+=c}s&&i.push(s),r=[];for(let l of i){let c=wo(l.trim());r.push(...c)}Rn.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},xo=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=C(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},Ln=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Cn(e.name,o);let s=e.args.map(a=>C(a,t,n,r));return i(...s)},Ee=(e,t,n,r)=>{if(e.var&&!e.type)return M(e.var,n,r);switch(e.type){case h.VARIABLE:return M(e.path,n,r);case h.LITERAL:return e.value;case h.BINARY:return $n(e,t,n,r);case h.UNARY:return kn(e,t,n,r);case h.FUNCTION:return Ln(e,t,n,r);default:return C(e,t,n,r)}},$n=(e,t,n,r)=>{if(e.op===T.AND||e.op===T.OR){let s=Ee(e.left,t,n,r),a=Ee(e.right,t,n,r);switch(e.op){case T.AND:return s&&a;case T.OR:return s||a}}let o=C(e.left,t,n,r),i=C(e.right,t,n,r);switch(e.op){case T.EQ:return o==i;case T.NEQ:return o!=i;case T.GT:return o>i;case T.LT:return o<i;case T.GTE:return o>=i;case T.LTE:return o<=i;case T.IN:return Array.isArray(i)?i.includes(o):!1;case T.ADD:if(typeof o!="number"||typeof i!="number")throw new Y(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case T.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new Y(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},kn=(e,t,n,r)=>{let o=e.op===Oe.NOT?Ee(e.operand,t,n,r):C(e.operand,t,n,r);if(e.op===Oe.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Eo=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===h.VARIABLE)if(M(o.path,n,r)){let s=e.bodies[0];if(s.type===h.OBJECT&&s.properties.length<=5){let a={};for(let l of s.properties){let c=l.parsedKey?C(l.parsedKey,t,n,r):l.key,u=l.value;if(u.type===h.LITERAL)a[c]=u.value;else if(u.type===h.VARIABLE)a[c]=M(u.path,n,r);else if(u.type===h.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===h.VARIABLE){let p=M(d.path,n,r);f.push(p!=null?String(p):"")}else{let p=C(d,t,n,r);f.push(p!=null?String(p):"")}a[c]=f.join("")}else a[c]=C(u,t,n,r)}return a}}else{let s=e.bodies[1];if(s.type===h.OBJECT&&s.properties.length<=5){let a={};for(let l of s.properties){let c=l.parsedKey?C(l.parsedKey,t,n,r):l.key,u=l.value;if(u.type===h.LITERAL)a[c]=u.value;else if(u.type===h.VARIABLE)a[c]=M(u.path,n,r);else if(u.type===h.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===h.VARIABLE){let p=M(d.path,n,r);f.push(p!=null?String(p):"")}else{let p=C(d,t,n,r);f.push(p!=null?String(p):"")}a[c]=f.join("")}else a[c]=C(u,t,n,r)}return a}}}return null},vo=(e,t,n,r)=>{let o=Eo(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||Ee(s,t,n,r))return C(e.bodies[i],t,n,r)}return On},So=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===h.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===h.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===h.OBJECT&&i.properties.length<=5){for(let l of i.properties)if(l.parsedKey)return null;let a=[];for(let l=0;l<t.length;l++){let c=t[l];if(c[s]){let u={};for(let f of i.properties){let d=f.key,p=f.value;if(p.type===h.LITERAL)u[d]=p.value;else if(p.type===h.VARIABLE){let g=p.path;if(g===r)u[d]=c;else if(g.startsWith(r+".")){let y=g.substring(r.length+1);u[d]=c[y]}else return null}else if(p.type===h.INTERPOLATION){let g=[],y=!0;for(let I of p.parts)if(typeof I=="string")g.push(I);else if(I.type===h.VARIABLE){let b=I.path;if(b===r)g.push(c!=null?String(c):"");else if(b.startsWith(r+".")){let m=b.substring(r.length+1),w=c[m];g.push(w!=null?String(w):"")}else{y=!1;break}}else{y=!1;break}if(!y)return null;u[d]=g.join("")}else return null}a.push(u)}}return a}}}return null},_o=(e,t)=>{let n=e.body,r=e.itemVar,o=So(e,t);if(o!==null)return o;if(n.type===h.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let a of n.properties)if(a.parsedKey)return null;let i=[],s=!0;for(let a of n.properties){let l=a.key,c=a.value;if(c.type===h.LITERAL)i.push({key:l,type:"literal",value:c.value});else if(c.type===h.VARIABLE){let u=c.path;if(u===r)i.push({key:l,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:l,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(c.type===h.INTERPOLATION&&c.parts.length===1){let u=c.parts[0];if(u.type===h.VARIABLE){let f=u.path;if(f===r)i.push({key:l,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:l,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let a=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 l=0;l<t.length;l++){let c=t[l];a[l]={id:c.id,title:c.title!=null?String(c.title):"",completed:c.completed}}else for(let l=0;l<t.length;l++){let c=t[l],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=c;else if(f.type==="prop")u[f.key]=c[f.prop];else if(f.type==="item_string")u[f.key]=c!=null?String(c):"";else if(f.type==="prop_string"){let d=c[f.prop];u[f.key]=d!=null?String(d):""}a[l]=u}return a}}return null},Co=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===h.OBJECT&&s.fast!==!1){let a=e.itemVar,l=e.indexVar;for(let c=0;c<o.length;c++){let u=o[c],f={},d={...r,[a]:u,...l&&{[l]:c}};d.__paths__||(d.__paths__=r.__paths__||{});let p=e.iterable.path||"";if(r&&r.__paths__&&p){let g=p.split("."),y=g[0];y in r.__paths__&&(p=r.__paths__[y],g.length>1&&(p+="."+g.slice(1).join(".")))}d.__paths__={...d.__paths__,[a]:`${p}[${c}]`,...l&&{[l]:c}};for(let g of s.properties){let y=g.parsedKey?C(g.parsedKey,t,n,d):g.key,I=g.value;if(I.type===h.LITERAL)f[y]=I.value;else if(I.type===h.VARIABLE){let b=I.path;if(b===a)f[y]=u;else if(b===l)f[y]=c;else if(b.startsWith(a+".")){let m=b.substring(a.length+1);!m.includes(".")&&!m.includes("[")?f[y]=u[m]:f[y]=M(b,n,{...r,[a]:u,...l&&{[l]:c}})}else f[y]=M(b,n,{...r,[a]:u,...l&&{[l]:c}})}else if(I.type===h.INTERPOLATION){let b=[];for(let m of I.parts)if(typeof m=="string")b.push(m);else if(m.type===h.VARIABLE){let w=m.path,v;if(w===a)v=u;else if(w===l)v=c;else if(w.startsWith(a+".")){let R=w.substring(a.length+1);!R.includes(".")&&!R.includes("[")?v=u[R]:v=M(w,n,{...r,[a]:u,...l&&{[l]:c}})}else v=M(w,n,{...r,[a]:u,...l&&{[l]:c}});b.push(v!=null?String(v):"")}else{let w={...r,[a]:u,...l&&{[l]:c}},v=C(m,t,n,w);b.push(v!=null?String(v):"")}f[y]=b.join("")}else{let b={...r,[a]:u,...l&&{[l]:c}};f[y]=C(I,t,n,b)}}i.push(f)}return i}return null},Ro=(e,t,n)=>{let r=e.body;if(r.type===h.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===h.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===h.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===h.OBJECT&&s.properties.length===2){let a=s.properties[0],l=s.properties[1];if(a.key==="id"&&a.value.type===h.VARIABLE&&a.value.path==="item.id"&&l.key==="$if item.highlighted"&&l.value.type===h.CONDITIONAL){let c=[];for(let u=0;u<t.length;u++){let f=t[u];if(f.visible){let d={id:f.id};f.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${f.name}`):(d.highlight=!1,d.message=f.name),c.push(d)}}return c}}}}return null},Lo=(e,t,n,r)=>{let o=C(e.iterable,t,n,r);if(!Array.isArray(o)){let c,u=!1;if(e.iterable.type===h.FUNCTION){u=!0;let d=e.iterable.args.map(p=>p.type===h.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===h.VARIABLE?p.path:p.type===h.FUNCTION?`${p.name}(...)`:"?").join(", ");c=`${e.iterable.name}(${d})`}else c=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${c}`;throw _n(f,o,u)}if(!e.indexVar){let c=Ro(e,o,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=_o(e,o);if(c!==null)return c}let i=Co(e,t,n,r,o);if(i!==null)return i;let s=[],a=e.iterable.path||"";if(r&&r.__paths__&&a){let c=a.split("."),u=c[0];u in r.__paths__&&(a=r.__paths__[u],c.length>1&&(a+="."+c.slice(1).join(".")))}let l=!1;e.body.type===h.ARRAY&&(e.body.items.length<=1?l=!1:l=e.body._shouldPreserveArray??=e.body.items.some(c=>c.type===h.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]:`${a}[${c}]`},e.indexVar&&(u.__paths__[e.indexVar]=c);let f=C(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!l){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},$o=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?C(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===h.OBJECT&&s.properties.length<=10&&!s.whenCondition){let a={},l={},c=!0;for(let u of s.properties){let f=u.parsedKey?C(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===h.LITERAL)l[f]=d.value;else if(d.type===h.VARIABLE)l[f]=M(d.path,n,r);else if(d.type===h.INTERPOLATION){let p=[];for(let g of d.parts)if(typeof g=="string")p.push(g);else if(g.type===h.VARIABLE){let y=M(g.path,n,r);p.push(y!=null?String(y):"")}else{c=!1;break}if(!c)break;l[f]=p.join("")}else if(d.type===h.OBJECT&&d.properties.length<=5){let p={};for(let g of d.properties){let y=g.key,I=g.value;if(I.type===h.LITERAL)p[y]=I.value;else if(I.type===h.VARIABLE)p[y]=M(I.path,n,r);else if(I.type===h.INTERPOLATION){let b=[];for(let m of I.parts)if(typeof m=="string")b.push(m);else if(m.type===h.VARIABLE){let w=M(m.path,n,r);b.push(w!=null?String(w):"")}else{c=!1;break}if(!c)break;p[y]=b.join("")}else{c=!1;break}}if(!c)break;l[f]=p}else{c=!1;break}}if(c)return a[i]=l,a}}return null},ko=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!Ee(e.whenCondition,o,n,r))return;let i=$o(e,t,n,r);if(i!==null)return i;if(e.fast){let c={};for(let u of e.properties){let f=u.parsedKey?C(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===h.LITERAL)c[f]=d.value;else if(d.type===h.VARIABLE)c[f]=M(d.path,n,r);else if(d.type===h.INTERPOLATION){let p=[];for(let g of d.parts)if(typeof g=="string")p.push(g);else if(g.type===h.VARIABLE){let y=M(g.path,n,r);p.push(y!=null?String(y):"")}else{let y=C(g,t,n,r);p.push(y!=null?String(y):"")}c[f]=p.join("")}else c[f]=C(d,t,n,r)}return c}let s={},a=null,l=!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 ")){l=!0;break}for(let c of e.properties)if(c.key.startsWith("$if ")||c.key.match(/^\$if\s+\w+.*:?$/)){let u=C(c.value,t,n,r);if(!l&&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 C(c.value,t,n,r)}else{let u=c.value;if(u&&u.type===h.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=C(f.value,t,n,r);d!==void 0&&(s[c.key]=d)}else{let d=C(c.value,t,n,r);d!==void 0&&(s[c.key]=d)}}else{let f=c.parsedKey?C(c.parsedKey,t,n,r):c.key,d=C(c.value,t,n,r);d!==void 0&&(s[f]=d)}}return s},On={},Oo=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===h.LOOP){let s=C(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=C(i,t,n,r);s!==On&&s!==void 0&&o.push(s)}return o},Po=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,a=t.partials||{},l=t.functions||t;if(s&&!Ee(s,l,n,r))return;if(!a[o])throw new Y(`Partial '${o}' is not defined`);let c=r._partialStack||[];if(c.includes(o))throw new Y(`Circular partial reference detected: ${o}`);let u=a[o],f=n,d={...r,_partialStack:[...c,o]};if(r){f={...n};for(let p of Object.keys(r))p.startsWith("_")||(f[p]=r[p])}if(i){let p=C(i,t,n,r);f={...f,...p}}return C(u,t,f,d)},To=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),s=i[0],a=i.slice(1);if(!r||!(s in r))throw new Y(`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 Y(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let l=r.__paths__[s];if(typeof l=="number"){if(a.length>0)throw new Y(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(l)}return a.length>0&&(l+="."+a.join(".")),l},_t=Ao;var Do=/\$\{([^}]*)\}/g,No=/#\{([^}]*)\}/g,Tn=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=Vo(o,t);return{isFunction:!0,type:h.FUNCTION,name:r,args:i}},Vo=(e,t={})=>e.trim()?Mo(e).map(r=>jo(r.trim(),t)):[],Mo=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let a=e[s],l=s>0?e[s-1]:"";!o&&(a==='"'||a==="'")?(o=!0,i=a,n+=a):o&&a===i&&l!=="\\"?(o=!1,i="",n+=a):!o&&a==="("?(r++,n+=a):!o&&a===")"?(r--,n+=a):!o&&a===","&&r===0?(t.push(n),n=""):n+=a}return n&&t.push(n),t},jo=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:h.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:h.LITERAL,value:parseFloat(e)};if(e==="true")return{type:h.LITERAL,value:!0};if(e==="false")return{type:h.LITERAL,value:!1};if(e==="null")return{type:h.LITERAL,value:null};let n=Tn(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:a,type:l}of o){let c=0;for(;c<r.length;){let u=de(r.substring(c),a);if(u===-1)break;let f=c+u;f>i&&(i=f,s={op:a,type:l}),c=f+a.length}}if(i!==-1)try{return W(r,t)}catch{return{type:h.VARIABLE,path:r}}return{type:h.VARIABLE,path:r}},Dn=/^\w+\(.*\)$/,Uo=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Bo=e=>{if(!(!e||e.trim()===""||Dn.test(e))&&Uo.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}"`)},Pn=e=>{let t=e.trim();if(Dn.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:h.PATH_REFERENCE,path:t}},Pe=(e,t={})=>{let n=e.trim();Bo(n);let r=Tn(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:h.VARIABLE,path:n}},Ct=(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 f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\(#\{[^}]*\})/g,(c,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...n.matchAll(Do)],i=[...n.matchAll(No)],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:h.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"?Pe(c[1],t):Pn(c[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:h.LITERAL,value:n};throw f}}let a=[],l=0;for(let{match:c,type:u}of s){let[f,d]=c,p=c.index;if(p>l){let g=n.substring(l,p);for(let y=0;y<r.length;y++)g=g.replace(`__ESCAPED_${y}__`,r[y]);g&&a.push(g)}try{let g;u==="variable"?g=Pe(d.trim(),t):g=Pn(d.trim()),a.push(g)}catch(g){if(g.message==="Invalid array index syntax")a.push(f);else throw g}l=p+f.length}if(l<n.length){let c=n.substring(l);for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);c&&a.push(c)}return{type:h.INTERPOLATION,parts:a}};var ae=(e,t)=>typeof e=="string"?Ct(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?zo(e,t):Wo(e,t):{type:h.LITERAL,value:e},Fo=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new x("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new x("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new x("Empty $each body not allowed");if(n.$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 ${r}`]:n}},zo=(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 l=Fo(i),c=Object.keys(l);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let u=Nn(c[0],l[c[0]],t,!0);n.push(u),r=!0;continue}}catch(l){throw l instanceof x?l:new x(l.message)}let a=Object.keys(i);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let l=Nn(a[0],i[a[0]],t);n.push(l),r=!0;continue}}let s=ae(i,t);n.push(s),(s.type===h.FUNCTION||s.type===h.CONDITIONAL||s.type===h.LOOP||s.type===h.PARTIAL||s.type===h.OBJECT&&!s.fast||s.type===h.ARRAY&&!s.fast)&&(r=!0)}return{type:h.ARRAY,items:n,fast:!r}},Wo=(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 x("$partial value must be a string");if(e.$partial.trim()==="")throw new x("$partial value cannot be an empty string");let l=["$if","$elif","$else","$for"],c=[];for(let[b]of i)for(let m of l)if(b===m||b.startsWith(m+" ")||b.startsWith(m+"#")){c.push(m);break}if(c.length>0)throw new x(`Cannot use $partial with ${c.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...d}=e,p={},g=!1;for(let[b,m]of Object.entries(d)){let w=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(w=b.slice(1)),p[w]=m,g=!0}let y=null;if(g&&(y=ae(p,t),y.type===h.OBJECT)){let b=!1;for(let m of y.properties)if(m.value.type===h.VARIABLE||m.value.type===h.INTERPOLATION||m.value.type===h.FUNCTION||m.value.type===h.CONDITIONAL||m.value.type===h.OBJECT&&!m.value.fast||m.value.type===h.ARRAY&&!m.value.fast){b=!0;break}b&&(y.fast=!1)}let I={type:h.PARTIAL,name:u,data:y};if(f!==void 0){let b;if(typeof f=="string"){if(f.trim()==="")throw new x("Empty condition expression after '$when'");b=W(f,t)}else b={type:h.LITERAL,value:f};I.whenCondition=b}return I}for(let[l,c]of i)if(l==="$when"){if(o!==null)throw new x("Multiple '$when' directives on the same object are not allowed");if(c==null)throw new x("Missing condition expression after '$when'");let u=typeof c=="string"?c:JSON.stringify(c);if(u.trim()==="")throw new x("Empty condition expression after '$when'");o=W(u,t),r=!0}else if(l.startsWith("$when#")||l.startsWith("$when "))throw new x("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[l,c]=i[s];if(l==="$when"){s++;continue}if(l==="$each")throw new x("$each can only be used inside arrays");if(l.startsWith("$if ")||l.match(/^\$if#\w+\s/)||l.match(/^\$if\s+\w+.*:$/)){let u=Yo(i,s,t);n.push({key:l,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(l)){let u=l.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new x(`$for loops must be inside arrays - use '- $for${f} item in items:' instead of '$for${f} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(l.startsWith("$elif ")||l.startsWith("$else"))throw new x(`'${l.split(" ")[0]}' without matching '$if'`);if(l==="$if"||l==="$if:")throw new x("Missing condition expression after '$if'");{let u=ae(c,t);(u.type===h.FUNCTION||u.type===h.CONDITIONAL||u.type===h.PARTIAL||u.type===h.OBJECT&&!u.fast||u.type===h.ARRAY&&!u.fast)&&(r=!0);let f=Ct(l,t),d={key:l,value:u};(f.type!==h.LITERAL||f.value!==l)&&(d.parsedKey=f),n.push(d),s++}}}let a={type:h.OBJECT,properties:n,fast:!r};return o&&(a.whenCondition=o),a},Yo=(e,t,n={})=>{let r=[],o=[],i=t,[s,a]=e[i],l=null,c;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)l=f[1],c=f[2];else throw new x(`Invalid conditional syntax: ${s}`)}else c=s.substring(4),c.endsWith(":")&&(c=c.slice(0,-1).trim());St(c);let u=W(c,n);for(r.push(u),o.push(ae(a,n)),i++;i<e.length;){let[f,d]=e[i],p=!1,g;if(l?f.startsWith(`$elif#${l} `)?(g=f.substring(`$elif#${l} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),p=!0):(f===`$else#${l}`||f===`$else#${l}:`)&&(p=!0,g=null):f.startsWith("$elif ")?(g=f.substring(6),g.endsWith(":")&&(g=g.slice(0,-1).trim()),p=!0):(f==="$else"||f==="$else:")&&(p=!0,g=null),p){if(g===null)r.push(null);else{St(g);let y=W(g,n);r.push(y)}if(o.push(ae(d,n)),i++,g===null)break}else break}return{node:{type:h.CONDITIONAL,conditions:r,bodies:o,id:l},nextIndex:i}},W=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let c=e.slice(1,-1),u=0,f=!0;for(let d=0;d<c.length;d++)if(c[d]==="("?u++:c[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return W(c,t)}let n=de(e,"||");if(n!==-1)return{type:h.BINARY,op:T.OR,left:W(e.substring(0,n).trim(),t),right:W(e.substring(n+2).trim(),t)};let r=de(e,"&&");if(r!==-1)return{type:h.BINARY,op:T.AND,left:W(e.substring(0,r).trim(),t),right:W(e.substring(r+2).trim(),t)};let o=[{op:">=",type:T.GTE},{op:"<=",type:T.LTE},{op:"==",type:T.EQ},{op:"!=",type:T.NEQ},{op:">",type:T.GT},{op:"<",type:T.LT},{op:" in ",type:T.IN}];for(let{op:c,type:u}of o){let f=de(e,c);if(f!==-1)return{type:h.BINARY,op:u,left:W(e.substring(0,f).trim(),t),right:W(e.substring(f+c.length).trim(),t)}}let i=-1,s=null,a=[{op:" + ",type:T.ADD},{op:" - ",type:T.SUBTRACT}];for(let{op:c,type:u}of a){let f=0;for(;f<e.length;){let d=de(e.substring(f),c);if(d===-1)break;let p=f+d;p>i&&(i=p,s={op:c,type:u}),f=p+c.length}}if(i!==-1&&s)return{type:h.BINARY,op:s.type,left:W(e.substring(0,i).trim(),t),right:W(e.substring(i+s.op.length).trim(),t)};let l=[" * "," / "," % "];for(let c of l)if(de(e,c)!==-1)throw new x(`Arithmetic operations are not allowed in conditionals: "${c}"`);return e.startsWith("!")?{type:h.UNARY,op:Oe.NOT,operand:W(e.substring(1).trim(),t)}:Vn(e,t)},de=(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},Ho=e=>{if(e=e.trim(),e==="true")return{type:h.LITERAL,value:!0};if(e==="false")return{type:h.LITERAL,value:!1};if(e==="null")return{type:h.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:h.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:h.LITERAL,value:""};if(e==="{}")return{type:h.LITERAL,value:{}};if(e==="[]")return{type:h.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:h.LITERAL,value:t}:{type:h.VARIABLE,path:e}},Vn=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return Pe(n,t);let o=Ho(n);if(o.type===h.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:h.VARIABLE,path:n};try{return Pe(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},qo=(e,t=!1)=>{let n=t?"$each":"$for";try{Sn(e)}catch(r){if(r instanceof x&&t){let o=r.message.replace(/\$for/g,"$each");throw new x(o.replace("Parse Error: ",""))}throw r}},Nn=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let I=r?"$each":"$for";throw new x(`Invalid loop syntax (got: '${e.replace("$for",I)}')`)}let s=i[1],a=i[2].trim();qo(a,r);let l=a.match(/^(.+?)\s+in\s+(.+)$/);if(!l){let I=r?"$each":"$for";throw new x(`Invalid loop syntax - missing 'in' keyword (got: '${I} ${a}')`)}let c=l[1].trim(),u=l[2].trim(),f,d=null;if(c.includes(",")){let I=c.split(",").map(b=>b.trim());if(I.length!==2)throw new x(`Invalid loop variables: ${c}. Expected format: "item" or "item, index"`);f=I[0],d=I[1]}else f=c;let p=["this","undefined","null","true","false"];if(p.includes(f))throw new x(`Reserved variable name: ${f}`);if(d&&p.includes(d))throw new x(`Reserved variable name: ${d}`);let g=Vn(u,n),y=ae(t,n);return{type:h.LOOP,itemVar:f,indexVar:d,iterable:g,body:y,flatten:s!=="nested"}};var Ko=(e,t={})=>{let{functions:n={}}=t;return ae(e,n)},Xe=Ko;var Rt={};lo(Rt,{now:()=>Go});var Go=()=>Date.now();var Xo=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...Rt,...r},s=Xe(e,{functions:i}),a={};for(let[l,c]of Object.entries(o))a[l]=Xe(c,{functions:i});return _t(s,t,{functions:i,partials:a})},J=Xo;var Mn=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=l=>l,transformActionFirstArgument:a=l=>l}=n;for(let[l,c]of Object.entries(t))l!=="createInitialState"&&(l.startsWith("select")?o[l]=(...u)=>c(s(r),...u):i[l]=(...u)=>{r=vt(r,d=>c(a(d),...u))});return{...o,...i}},Je=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return vt(r,i=>{o.forEach(s=>{t.forEach(a=>{a(i,s)})})})};var Jo=(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{}}},kt=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{let i=Jo(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},Ot=(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(", ")}`)},Pt=(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(", ")}`)},Tt=(e,t,n)=>{switch(t){case"set":return n;case"multiply":return(e??1)*n;case"divide":return(e??0)/n;case"increment":return(e??0)+(n??1);case"decrement":return(e??0)-(n??1);case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var jn=(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()))},Zo=(e,t)=>{let n=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let a=i.character?.sprite;return a&&Object.keys(a).length>0&&(s.sprite=a),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},Dt=(e={},t={})=>{let n={},r=["sfx","voice"],o=s=>{let a=e[s],l=t[s];l&&!a?n[s]={changeType:"add",data:l}:a&&!l?r.includes(s)||(n[s]={changeType:"delete",data:a}):a&&l&&JSON.stringify(a)!==JSON.stringify(l)&&(n[s]={changeType:"update",data:l})};o("background"),o("bgm"),o("voice");let i=Zo(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},Nt=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,t.background.resourceId||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"),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(a=>{let l={...a};return delete l.animations,i(l)?l: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},Qo=(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},ei=(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=Qo(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},ti={updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"])},Un=(e,t)=>{let n=e[e.length-1];return n?ti[n]?.has(t)===!0:!1},Lt=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Lt(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Un(n,r)?o:Lt(o,t,[...n,r])])):ei(e,t),$t=(e,t,n=[])=>Array.isArray(e)?e.map(r=>$t(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Un(n,r)?o:$t(o,t,[...n,r])])):typeof e=="string"?J(e,t):e,Bn=(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=Lt(e,t._event);return $t(n,t)};var Ze=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:structuredClone(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Wn=(e,t)=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let n=e.map(r=>structuredClone(r)).filter(r=>t(r)||r.animations);return{hasValidItems:n.length>0,processedItems:n}},ve=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Fn=e=>e?.animations?.playback?.continuity==="persistent",ni=e=>{if(e){if(e.character&&ve(e.character,"name"))return e.character.name;if(ve(e,"characterName"))return e.characterName}},Yn=e=>!!e?.character&&ve(e.character,"sprite"),ri=e=>{let t={},n=!1,r=ni(e);return r!==void 0&&(t.name=r,n=!0),Yn(e)&&(t.sprite=structuredClone(e.character.sprite),n=!0),n?t:void 0},zn=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},oi=()=>({}),ii=(e,t)=>{if(t.background){let{animationsOnly:n,state:r}=Ze(t.background,s=>!!s.resourceId);if(n){e.background=e.background?.resourceId?{...structuredClone(e.background),...r}:r;return}if(!t.background.resourceId){delete e.background;return}let o=structuredClone(t.background),i=e.background;i?.resourceId===o.resourceId&&i?.transformId===o.transformId&&!ve(o,"animations")&&Fn(i)&&(o.animations=structuredClone(i.animations)),e.background=o}else e.background?.animations&&!Fn(e.background)&&(e.background.animations={})},si=(e,t)=>{if(!t.dialogue){e.dialogue&&(zn(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}if(e.dialogue||(e.dialogue={}),t.dialogue.ui){let{animationsOnly:a,state:l}=Ze(t.dialogue.ui,c=>!!c.resourceId);a?e.dialogue.ui={...e.dialogue.ui,...l}: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"),t.dialogue.content!==void 0&&(e.dialogue.content=t.dialogue.content);let n=ve(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;n?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let r=ve(t.dialogue,"characterId"),o=ri(t.dialogue),i=o!==void 0,s=Yn(t.dialogue);if(r?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:n||delete e.dialogue.characterId,i?e.dialogue.character=!r&&n&&e.dialogue.character?{...structuredClone(e.dialogue.character),...o}:o:(r||!n)&&delete e.dialogue.character,s||zn(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 a={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(a.character=structuredClone(e.dialogue.character)),e.dialogue.lines.push(a)}},ai=(e,t)=>{if(t.sfx){if(!t.sfx.items||t.sfx.items.length===0){delete e.sfx;return}e.sfx=t.sfx}else e.sfx&&delete e.sfx},ci=(e,t)=>{if(t.bgm){if(!t.bgm.resourceId){e.bgm=void 0;return}e.bgm={...t.bgm,loop:t.bgm.loop||t.bgm.loop===void 0}}},li=(e,t)=>{if(t.visual){let{hasValidItems:n,processedItems:r}=Wn(t.visual.items,o=>!!o.resourceId);n?e.visual={items:r}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},ui=(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}=Wn(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);n?e.character={items:r}:delete e.character},fi=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},di=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=Ze(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},pi=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=Ze(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},hi=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},gi=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},mi=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},Se=e=>Je(oi,[mi,ii,ai,ci,li,si,ui,fi,di,pi,hi,gi])(e);var pe={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:jn},yi=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,bi=(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},tt=(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),a=yi.exec(s);if(a){let[,l,c,u]=a,f=bi(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((p,g)=>{let y={...t,[l]:p};c&&(y[c]=g),d.forEach(I=>{let b=tt(I,y,n),m=J(b,y,n);Array.isArray(m)?o.push(...m):o.push(m)})});continue}}o.push(tt(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=tt(i,t,n)}),r},qt=({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".`)},Ii=({id:e,targetId:t,animation:n,playback:r,animationPath:o="animation"})=>{let i=structuredClone(n);return qt({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,r&&(i.playback=structuredClone(r)),i},Ai=(e,{animationId:t="animation",animationPath:n="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return qt({animationType:e.type,animationId:t,animationPath:n}),e.type},wi=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},xi=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Ei=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),or=e=>e?.playback?.continuity==="persistent",Ft=e=>Array.isArray(e)?e.map(Ft):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,n)=>(t[n]=Ft(e[n]),t),{}),nt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify(Ft(t))},ir=(e=[])=>e.filter(t=>or(t)).map(t=>structuredClone(t)),sr=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,Vt=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,n)=>Math.max(t,sr(n)),0),ar=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(Vt(e.tween),Vt(e.prev?.tween),Vt(e.next?.tween),sr(e.mask?.progress)),Hn=({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(nt).filter(Boolean));return e.some(r=>{if(!or(r))return!1;let o=nt(r);return o?n.has(o):!1})},ne=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:n,activePersistentAnimations:r,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||n?!1:i&&!t||Hn({animationInstances:e,activePersistentAnimations:r})?!0:i?!1:Hn({animationInstances:e,activePersistentAnimations:o}),vi=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Si=(e,t)=>{if(vi(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},_i=({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?Ii({id:r,targetId:o,animation:s,playback:n,animationPath:i}):null},Ci=({hasPrevious:e,hasCurrent:t,previousResourceId:n,currentResourceId:r,sharedTarget:o})=>!e&&t?"enter":e&&!t?"exit":e&&t?n===r&&o?"update":"replace":"none",Ri=({animationType:e,animationId:t,animationPath:n,lifecycle:r})=>{if(!(e!=="update"||r==="update"))throw new Error(`[${n}] Animation "${t}" has type "update", but update animations can only be used when the same target persists across the state change. Use type "transition" for enter, exit, and replace.`)},Li=(e,{defaultTargetId:t,defaultId:n,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return qt({animationType:o.type,animationId:o.id??n,animationPath:r}),o.id??=n,o.targetId??=t,o},Kt=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r,animationPathPrefix:o=r})=>{t.forEach((i,s)=>{e.push(Li(i,{defaultTargetId:n,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},qn=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=J(e,t);return n&&typeof n=="object"?e:n},Kn=(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},Gn=(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))},Qe=(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("-")}`},Mt=(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},$i=(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},Xn=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},et=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},ki=(e={})=>e.textStyles||{},Oi=(e={})=>e.images||{},Pi=(e={})=>e.colors||{},Ti=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Te=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,Ce=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},Jn=(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},cr=(e,t)=>{if(typeof e!="string"||!Ti.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},Zn=(e,t,n)=>{let r=cr(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})`},Di=(e={},t)=>{let n=ki(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=Jn(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:Zn(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 a=e.colors?.[n.strokeColorId];if(!a)throw new Error(`Stroke color "${n.strokeColorId}" not found for text style "${t}"`);let l=Jn(n.strokeAlpha,"strokeAlpha",t);s.strokeColor=Zn(a.hex,l,`Stroke color "${n.strokeColorId}" for text style "${t}"`)}else if(n.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return n.strokeWidth!==void 0&&(s.strokeWidth=n.strokeWidth),s},zt=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>zt(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]=zt(i,t,Te(n,o)));return e.textStyleId!==void 0&&(Ce(e.textStyleId,n,"textStyleId"),r.textStyle=Di(t,e.textStyleId)),r},lr=(e={},t)=>{let n=Pi(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return cr(n.hex,`Color "${t}"`)},ur=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",jt=(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 ${ur(`${t}.fill`)} instead`)},Ni=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>De(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]=De(i,t,Te(n,o)));return e.colorId!==void 0&&(Ce(e.colorId,n,"colorId"),r.fill=lr(t,e.colorId)),r},De=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>De(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 ${ur("fill")} instead`);jt(e,"hover",n),jt(e,"click",n),jt(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]=Ni(i,t,Te(n,o));continue}r[o]=De(i,t,Te(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(Ce(e.colorId,n,"colorId"),r.fill=lr(t,e.colorId)),r},Ut=(e={},t)=>{let n=Oi(e)?.[t];return n||null},fr=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",Qn=(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 ${fr(`${t}.${r}`)} instead`)},er=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},Wt=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Wt(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 ${fr(o)} instead`);Qn(e,"hover",n,"src"),Qn(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]=Wt(i,t,Te(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){Ce(e.imageId,n,"imageId");let o=Ut(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&&(Ce(e.hoverImageId,n,"hoverImageId"),er(r,"hover",Ut(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(Ce(e.clickImageId,n,"clickImageId"),er(r,"click",Ut(t,e.clickImageId)?.fileId??e.clickImageId)),r},Gt=(e,t={},n="root")=>Wt(De(zt(e,t,n),t,n),t,n),he=Gt,Ne=(e=[])=>e.find(t=>t.id==="story");var Vi=(e={})=>e?.muteAll?0:e?.musicVolume??50,Q=({variables:e,runtime:t,saveSlots:n=[],dialogueState:r,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,confirmDialog:u,historyDialogue:f=[],characters:d={},dialogueUIHidden:p,skipOnlyViewedLines:g,skipTransitionsAndAnimations:y}={})=>{let I={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,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??a??!1,dialogueUIHidden:t?.dialogueUIHidden??p??!1,isLineCompleted:t?.isLineCompleted??i??!1},b=Bi({dialogueState:r,includeInactiveAdvDialogue:o,characters:d,variables:e}),m={variables:e,runtime:I,saveSlots:n,isChoiceVisible:l,canRollback:c,confirmDialog:u,historyDialogue:f,characters:d};return b&&(m.dialogue=b,m.dialogueLines=b.lines),m},tr=100,rt=(e,t)=>{if(Array.isArray(e))return e.map(r=>rt(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=rt(n[r],t)}),n.type==="text-revealing"?t(n):n},Mi=e=>rt(e,t=>({...t,revealEffect:"none"})),ji=e=>rt(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,tr):tr;return{...t,speed:r,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:r}:{}}}),ge=(e,{isLineCompleted:t=!1,skipMode:n=!1,skipTransitionsAndAnimations:r=!1}={})=>t||r?Mi(e):n?ji(e):e,dr=({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:{}}}}),Yt=e=>{if(Array.isArray(e))return e.map(Yt);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Yt(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,_interactionSource:"choice"}:void 0;return{...t,click:{...t.click,payload:{...n,_interactionSource:"choice",...o?{actions:{...r,nextLine:o}}:{}}}}},Ht=({characterId:e,character:t,characterName:n,characters:r={}}={})=>{let o=e?r?.[e]:void 0,i=t?.name!==void 0?t.name:n!==void 0?n:o?.name||"";return{...o||{},...t||{},name:i}},pr=(e=[],t={})=>e.map(n=>{let r=Ht({characterId:n.characterId,character:n.character,characterName:n.characterName,characters:t}),o=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(i=>i?.text??"").join(""):"";return{...n,text:o,character:r,characterName:r.name}}),Ui=e=>!(!e||e.mode==="adv"&&e.content===void 0),Bi=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:n={},variables:r}={})=>{if(!t&&!Ui(e))return;let o=e.content===void 0?[{text:""}]:Kn(e.content,"dialogue.content"),i=(e.lines||[]).map((a,l)=>{let c=Kn(a.content,`dialogue.lines[${l}].content`),u=Ht({characterId:a.characterId,character:a.character,characterName:a.characterName,characters:n});return{...a,content:c.map(f=>({...f,text:qn(f.text,{variables:r})})),character:u,characterName:u.name}}),s=Ht({characterId:e.characterId,character:e.character,characters:n});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:s,content:o.map(a=>({...a,text:qn(a.text,{variables:r})})),lines:i}},hr=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=J(e,n,{functions:pe});return he(ge(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},Bt=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),nr=({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:Bt(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[r].keyup={payload:Bt(o.keyup)});return}e[r]={...i,[n]:{payload:Bt(o)}}})},Fi=(e={},t={})=>{let n={};return nr({renderStateKeyboard:n,keyboard:e,phase:"keydown"}),nr({renderStateKeyboard:n,keyboard:t,phase:"keyup"}),Object.keys(n).length>0?n:void 0},me=({animationsDef:e,resources:t,previousResourceId:n,currentResourceId:r,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:a,allowIncomingUpdateFallback:l=!1})=>{if(!e)return[];let c=[],u=({instanceId:v,targetId:R})=>{let L=_i({resources:t,animationId:y,playback:I,instanceId:v,targetId:R,animationPath:s});L&&c.push(L)},f=n!=null&&n!==!1,d=r!=null&&r!==!1,p=o&&i&&o===i,g=Ci({hasPrevious:f,hasCurrent:d,previousResourceId:n,currentResourceId:r,sharedTarget:p});Si(e,s);let y=wi(e),I=xi(e),b=t?.animations?.[y],m=Ai(b,{animationId:y,animationPath:s}),w=l&&m==="update"&&g!=="update"&&d&&i;if(w||Ri({animationType:m,animationId:y,animationPath:s,lifecycle:g}),m==="update")return f&&d&&n===r&&p?u({instanceId:`${a}-animation-update`,targetId:i}):w&&u({instanceId:`${a}-animation-update`,targetId:i}),c;if(m==="transition"){let v=`${a}-animation-transition`,R=I?.continuity==="persistent"?v:`${a}-animation-in`;if(f&&d&&p)return u({instanceId:v,targetId:i}),c;f&&u({instanceId:`${a}-animation-out`,targetId:o}),d&&u({instanceId:R,targetId:i})}return c},zi=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Wi=(e,{presentationState:t,previousPresentationState:n,currentLineActions:r,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:a,variables:l,runtime:c,activePersistentAnimations:u,restoredPersistentAnimations:f,autoMode:d,skipMode:p,isChoiceVisible:g,canRollback:y,saveSlots:I=[]})=>{let{elements:b,animations:m}=e;if(t.background){let w=r===void 0?!0:Ei(r?.background??{},"animations"),v=b.find(k=>k.id==="story");if(!v)return e;let R=$i(o,t.background),L=n?.background?.resourceId,_=t.background.resourceId??(t.background.animations?L:void 0),D=Xn(o,L),O=Xn(o,_);if(_){let{images:k={},videos:A={}}=o,E=k[_]||A[_];if(E){let N=A[_]!==void 0,U={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...R},B={id:et({resourceId:_,kind:N?"video":"sprite"}),type:N?"video":"sprite",x:U.x,y:U.y,src:E.fileId,width:E.width,height:E.height,alpha:1,anchorX:U.anchorX,anchorY:U.anchorY,rotation:U.rotation,scaleX:U.scaleX,scaleY:U.scaleY};N&&(B.loop=t.background.loop??!1,B.volume=E.volume??50),v.children.push(B)}}if(_){let{layouts:k={}}=o,A=k[_];if(A){let E={id:et({resourceId:_,kind:"container"}),type:"container",children:A.elements};R&&Object.assign(E,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...R});let N=J(E,Q({variables:l,runtime:c,saveSlots:I,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:g,canRollback:y,characters:o.characters||{},skipTransitionsAndAnimations:a}),{functions:pe});v.children.push(he(ge(N,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:a}),o))}}let $=me({animationsDef:t.background.animations,resources:o,previousResourceId:L,currentResourceId:_,previousTargetId:et({resourceId:L,kind:D}),currentTargetId:et({resourceId:_,kind:O}),animationPath:"background.animations",idPrefix:"bg-cg",allowIncomingUpdateFallback:!0});ne({animationInstances:$,isLineCompleted:s,skipTransitionsAndAnimations:a,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:w})&&m.push(...$)}return e},Yi=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:a,animations:l}=e;if(t.character&&r){let c=a.find(g=>g.id==="story");if(!c)return e;let u=t.character.items||[],f=n?.character?.items||[],d=Gn(u),p=Gn(f);for(let g=0;g<u.length;g++){let y=u[g],{transformId:I,sprites:b}=y,m=f.find(k=>k.id===y.id),w=f.findIndex(k=>k.id===y.id),v=m?.sprites&&m.sprites.length>0,R=b&&b.length>0,L=w>=0?Qe(m,w,p):void 0,_=me({animationsDef:y.animations,resources:r,previousResourceId:L,currentResourceId:R?Qe(y,g,d):void 0,previousTargetId:L,currentTargetId:R?Qe(y,g,d):void 0,animationPath:`character.items[${g}].animations`,idPrefix:"character"});if(y.animations&&!b&&!I&&v&&ne({animationInstances:_,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){l.push(..._);continue}if(y.animations&&!b&&!I)continue;if(!b||b.length===0||!I){console.warn("Character item missing sprites or transformId:",y);continue}let D=Qe(y,g,d),O=r.transforms[I];if(!O){console.warn("Transform not found:",I);continue}let $={type:"container",id:D,x:y.x??O.x,y:y.y??O.y,anchorX:O.anchorX,anchorY:O.anchorY,rotation:O.rotation,scaleX:O.scaleX,scaleY:O.scaleY,children:[]};for(let k of b){let A=r.images[k.resourceId];if(!A){console.warn(`Image resource not found: ${k.resourceId}`);continue}$.children.push({type:"sprite",id:`${D}-${k.id}`,src:A.fileId,width:A.width,height:A.height,x:0,y:0})}c.children.push($),ne({animationInstances:_,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(..._)}}return e},Hi=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:a,activePersistentAnimations:l,autoMode:c,skipMode:u,isChoiceVisible:f,canRollback:d,saveSlots:p=[]})=>{let{elements:g,animations:y}=e;if(t.visual&&r){let I=g.find(m=>m.id==="story");if(!I)return e;let b=t.visual.items;for(let m of b){if(m.resourceId){let{images:L={},videos:_={},spritesheets:D={}}=r,O=D[m.resourceId];if(O){let $=Mt(r,m),k=m.animationName;if(k){let A=O.animations?.[k];if(!A)throw new Error(`Animation '${k}' not found in spritesheet resource '${m.resourceId}'`);let E={id:`visual-${m.id}`,type:"animated-sprite",x:m.x??$.x,y:m.y??$.y,width:m.width??O.width,height:m.height??O.height,alpha:m.alpha??1,anchorX:$.anchorX,anchorY:$.anchorY,rotation:$.rotation,scaleX:$.scaleX,scaleY:$.scaleY,spritesheetSrc:O.fileId,spritesheetData:O.jsonData,animation:{frames:A.frames,animationSpeed:m.animationSpeed??A.animationSpeed??.5,loop:m.loop??A.loop??!0}};I.children.push(structuredClone(E))}}else{let $=L[m.resourceId]||_[m.resourceId];if($){let k=_[m.resourceId]!==void 0,A=Mt(r,m),E={id:`visual-${m.id}`,type:k?"video":"sprite",src:$.fileId,width:$.width,height:$.height,x:A.x,y:A.y,anchorX:A.anchorX,anchorY:A.anchorY,rotation:A.rotation,scaleX:A.scaleX,scaleY:A.scaleY};k&&(E.loop=$.loop??!1,E.volume=$.volume??50),I.children.push(E)}}}if(m.resourceId){let{layouts:L={}}=r,_=L[m.resourceId];if(_){let D=Mt(r,m),O={id:`visual-${m.id}`,type:"container",children:structuredClone(_.elements),x:D.x,y:D.y,anchorX:D.anchorX,anchorY:D.anchorY,rotation:D.rotation,scaleX:D.scaleX,scaleY:D.scaleY},$=J(O,Q({variables:s,runtime:a,saveSlots:p,dialogueState:t.dialogue,isLineCompleted:o,autoMode:c,skipMode:u,isChoiceVisible:f,canRollback:d,characters:r.characters||{},skipTransitionsAndAnimations:i}),{functions:pe});I.children.push(he(ge($,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),r))}}let v=(n?.visual?.items||[]).find(L=>L.id===m.id),R=me({animationsDef:m.animations,resources:r,previousResourceId:v?.resourceId,currentResourceId:m.resourceId,previousTargetId:v?.resourceId?`visual-${m.id}`:void 0,currentTargetId:m.resourceId?`visual-${m.id}`:void 0,animationPath:`visual.items[${m.id}].animations`,idPrefix:m.id});ne({animationInstances:R,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:l})&&y.push(...R)}}return e},_e="dialogue-character-sprite",rr=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,qi=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:a}=e,l=Ne(e.elements);if(!l)return e;let c=t.dialogue?.character?.sprite,u=n?.dialogue?.character?.sprite,f=rr(c),d=rr(u),p=me({animationsDef:c?.animations,resources:r,previousResourceId:d?_e:void 0,currentResourceId:f?_e:void 0,previousTargetId:d?_e:void 0,currentTargetId:f?_e:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!f)return c?.animations&&d&&ne({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...p),e;let g=r.transforms?.[c.transformId];if(!g)return console.warn("Transform not found:",c.transformId),e;let y={type:"container",id:_e,x:g.x,y:g.y,anchorX:g.anchorX,anchorY:g.anchorY,rotation:g.rotation,scaleX:g.scaleX,scaleY:g.scaleY,children:[]};for(let I of c.items){let b=r.images?.[I.resourceId];if(!b){console.warn(`Image resource not found: ${I.resourceId}`);continue}y.children.push({type:"sprite",id:`${_e}-${I.id}`,src:b.fileId,width:b.width,height:b.height,x:0,y:0})}return l.children.push(y),ne({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...p),e},Ki=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,skipOnlyViewedLines:c,isLineCompleted:u,skipTransitionsAndAnimations:f,variables:d,runtime:p,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:I,animations:b}=e;if(!t.dialogue||o)return e;let m=I.find(v=>v.id==="story");if(!m)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:v={}}=r,R=v[t.dialogue.ui.resourceId];if(R){let L={elements:R.elements},_=Q({variables:d,runtime:p,saveSlots:y,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:u,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,characters:r.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:c,skipTransitionsAndAnimations:f}),D={functions:pe},O=tt(L,_,D),$=J(O,_,D),k=he(ge($?.elements,{isLineCompleted:u,skipMode:s,skipTransitionsAndAnimations:f}),r);if(Array.isArray(k))for(let A of k)m.children.push(A);else k&&m.children.push(k)}}qi(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:u,skipTransitionsAndAnimations:f,activePersistentAnimations:g});let w=me({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 ne({animationInstances:w,isLineCompleted:u,skipTransitionsAndAnimations:f,activePersistentAnimations:g})&&b.push(...w),e},Gi=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,runtime:l,autoMode:c,skipMode:u,isChoiceVisible:f,canRollback:d,activePersistentAnimations:p,saveSlots:g=[]})=>{let{elements:y,animations:I}=e;if(t.choice&&r){let b=Ne(y);if(!b)return e;let m=r?.layouts[t.choice.resourceId];if(m&&m.elements){let v={elements:m.elements},R=J(v,{...Q({variables:a,runtime:l,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:c,skipMode:u,isChoiceVisible:f??!!t.choice,canRollback:d,characters:r.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:pe}),L=Yt(he(ge(R?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r));if(Array.isArray(L))for(let _ of L)b.children.push(_);else L&&b.children.push(L)}let w=me({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"});ne({animationInstances:w,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:p})&&I.push(...w)}return e},Xi=(e,{presentationState:t,resources:n={},variables:r,runtime:o,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,saveSlots:u=[],skipTransitionsAndAnimations:f})=>{if(!t.control?.resourceId)return e;let d=n.controls?.[t.control.resourceId];if(!d)return e;let p=Fi(d.keyboard,d.keyup);if(p&&Object.keys(p).length>0&&(e.global.keyboard=p),!Array.isArray(d.elements)||d.elements.length===0)return e;let g=Ne(e.elements);if(!g)return e;let y={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:d.elements};return g.children.push(hr({container:y,resources:n,templateData:Q({variables:r,runtime:o,saveSlots:u,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,characters:n.characters||{},skipTransitionsAndAnimations:f}),isLineCompleted:i,skipMode:a,skipTransitionsAndAnimations:f})),e},Ji=(e,{presentationState:t,resources:n,runtime:r,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&n){if(!Ne(i))return e;let l=n.sounds[t.bgm.resourceId];if(!l)return e;let c=Q({variables:o,runtime:r}).runtime;s.push({id:"bgm",type:"sound",src:l.fileId,loop:t.bgm.loop??!0,volume:Vi(c),delay:t.bgm.delay??null})}return e},Zi=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(t.sfx&&n){let o=t.sfx.items;for(let i of o){let s=n.sounds?.[i.resourceId];s&&r.push({id:i.id,type:"sound",src:s.fileId,loop:i.loop??s.loop??!1,volume:i.volume??s.volume??50,delay:i.delay??s.delay??null})}}return e},Qi=(e,t,n)=>{if(!(!t||!n))return e?.voices?.[t]?.[n]},es=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,ts=(e,{presentationState:t,resources:n,currentSceneId:r,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let a=t.voice,{resourceId:l,loop:c,delay:u}=a,f=Qi(n,r,l);if(!f)return e;let d=Q({variables:i,runtime:o}).runtime;return s.push({id:`voice-${r}-${l}`,type:"sound",src:f.fileId,volume:es(a,d),loop:c??!1,delay:u??null}),e},ns=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,runtime:i,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,saveSlots:u=[],isLineCompleted:f,skipTransitionsAndAnimations:d,activePersistentAnimations:p})=>{let{elements:g,animations:y}=e;if(t.layout){let w=Ne(g);if(!w)return e;let v=r.layouts[t.layout.resourceId];if(!v)return e;Array.isArray(v.transitions)&&!f&&!d&&Kt({animations:y,transitions:v.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let R={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:v.elements||[]};w.children.push(hr({container:R,resources:r,templateData:Q({variables:o,runtime:i,saveSlots:u,dialogueState:t.dialogue,isLineCompleted:f,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,characters:r.characters||{},skipTransitionsAndAnimations:d}),isLineCompleted:f,skipMode:a,skipTransitionsAndAnimations:d}))}let I=n?.layout?.resourceId,b=t.layout?.resourceId,m=me({animationsDef:t.layout?.animations,resources:r,previousResourceId:I,currentResourceId:b,previousTargetId:I?`layout-${I}`:void 0,currentTargetId:b?`layout-${b}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return ne({animationInstances:m,isLineCompleted:f,skipTransitionsAndAnimations:d,activePersistentAnimations:p})&&y.push(...m),e},rs=(e,{presentationState:t,resources:n={},variables:r,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,overlayStack:c=[],dialogueHistory:u=[],saveSlots:f=[],screen:d,isLineCompleted:p,skipTransitionsAndAnimations:g})=>{let{elements:y,animations:I}=e;return c&&c.length>0&&c.forEach((b,m)=>{let w=n.layouts[b.resourceId];if(!w){console.warn(`Overlay layout not found: ${b.resourceId}`);return}Array.isArray(w.transitions)&&(g||Kt({animations:I,transitions:w.transitions,defaultTargetId:`overlayStack-${m}`,idPrefix:`overlayStack-${m}`,animationPathPrefix:`overlayStack[${m}]`}));let v={id:`overlayStack-${m}`,type:"container",x:0,y:0,children:[dr({id:`overlayStack-${m}-blocker`,screen:d}),...w.elements||[]]},R=pr(u,n.characters),L=Q({variables:r,runtime:o,saveSlots:f,dialogueState:t?.dialogue,isLineCompleted:p,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,historyDialogue:R,characters:n.characters||{},skipTransitionsAndAnimations:g}),_=J(v,L,{functions:pe}),[D,...O]=_.children||[],$=he(ge({..._,children:O},{isLineCompleted:p,skipMode:s,skipTransitionsAndAnimations:g}),n);y.push({...$,children:D?[D,...$.children||[]]:$.children})}),e},os=(e,{presentationState:t,resources:n={},variables:r,runtime:o,saveSlots:i=[],autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,confirmDialog:u,dialogueHistory:f=[],screen:d,isLineCompleted:p,skipTransitionsAndAnimations:g})=>{let{elements:y,animations:I}=e;if(!u?.resourceId)return e;let b=n.layouts?.[u.resourceId];if(!b)return console.warn(`ConfirmDialog layout not found: ${u.resourceId}`),e;Array.isArray(b.transitions)&&!g&&Kt({animations:I,transitions:b.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let m={id:"confirmDialog",type:"container",x:0,y:0,children:[dr({id:"confirmDialog-blocker",screen:d}),...b.elements||[]]},w=pr(f,n.characters),v=J(m,Q({variables:r,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:p,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,confirmDialog:u,historyDialogue:w,characters:n.characters||{},skipTransitionsAndAnimations:g}),{functions:pe}),[R,...L]=v.children||[],_=he(ge({...v,children:L},{isLineCompleted:p,skipMode:a,skipTransitionsAndAnimations:g}),n);return y.push({..._,children:R?[R,..._.children||[]]:_.children}),e},gr=e=>Je(zi,[Xi,Wi,Yi,Hi,Ki,Gi,ns,Ji,Zi,ts,rs,os])(e);var is=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},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"}}),ot=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),Ve=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),mr=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"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"}),Xt=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Jt=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),ss=(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]}},Zt=e=>Object.fromEntries(Object.entries(is).map(([t,n])=>{let r=ss(e,n.source),o=r!==void 0?r:ot[t]??Ve[t];return[t,o]})),re=(e,t)=>Zt(e)[t],yr=(e={})=>Object.fromEntries(Xt.map(t=>[t,e[t]??ot[t]]));var it={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},xr=1,at=()=>({manual:{...it.manual},auto:{...it.auto},applyMode:it.applyMode}),Qt=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...at()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},j=e=>{let t=se(e)?Et(e):e;return structuredClone(t)},V=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ct=e=>String(e),Er=()=>({sections:[],resources:[]}),as=e=>V(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Er(),cs=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",ls=()=>({resourceId:void 0}),us=e=>{if(!V(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},en=(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}},vr=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 a=n.get(s);if(a!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${a}" and "${r}". Section IDs must be globally unique.`);n.set(s,r)}}},Sr=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},_r=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==xr)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},fs=(e,t={})=>{let n;try{n=_r(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:Sr(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},ds=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,fs(t,n)])),Cr=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:n})=>Ma(n));return t.length>0?t:void 0},ps=e=>{!V(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!V(t))return;let n=Cr(t.executedActions);if(n){t.executedActions=n;return}delete t.executedActions})},br=(e,t,n,r="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!V(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}},hs=(e,t="viewedRegistry")=>{if(e===void 0)return Er();if(!V(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=br(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(r.map((o,i)=>{let s=br(o,"resources",i,t);return[s.resourceId,s]})))}},Rr=(e,t,n)=>{if(!V(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}=en(t,r);if(!s)throw new Error(`Malformed save slot ${n}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(l=>l.id===o))throw new Error(`Malformed save slot ${n}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},gs=(e,t,n)=>{if(!V(e)||!Array.isArray(e.timeline))return Me({pointer:t,replayStartIndex:1});let r=e.timeline.flatMap((a,l)=>{if(!V(a))return[];try{let c=Rr(a,n,`rollback.timeline[${l}]`),u=st({sectionId:c.sectionId,lineId:c.lineId,rollbackPolicy:a.rollbackPolicy}),f=Cr(j(a.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(r.length===0)return Me({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):r.length-1;(o<0||o>=r.length)&&(o=r.length-1);let i=r[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let a=r.findLastIndex(l=>l.sectionId===t.sectionId&&l.lineId===t.lineId);a>=0?o=a:(r.push(st({sectionId:t.sectionId,lineId:t.lineId})),o=r.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:r}},ms=(e,t,n)=>{if(!V(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=nn(t),o=Rr(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!V(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);if(e.runtime!==void 0&&!V(e.runtime))throw new Error(`Malformed save slot contexts[${n}].runtime entry.`);let i=e.variables?j(e.variables):{},s=ws({loadedContextRuntime:V(e.runtime)?j(e.runtime):{}}),a={currentPointerMode:"read",pointers:{read:o},configuration:V(e.configuration)?j(e.configuration):{},views:Array.isArray(e.views)?j(e.views):[],bgm:V(e.bgm)?j(e.bgm):{resourceId:void 0},variables:{...r,...i},rollback:gs(e.rollback,o,t)};return s&&(a.runtime=s),a},ys=(e,t)=>{if(!V(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)=>ms(n,t,r))}},bs=(e,t)=>{if(!V(e))throw new Error("Malformed save slot.");let n=_r(e.formatVersion);return{...e,formatVersion:n,state:ys(e.state,t)}},Ir=(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=j(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},Is=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Ir(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Ir(e.cancelActions,"cancelActions")}},Re=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},ye=[],Ar="line",tn="interaction",st=({sectionId:e,lineId:t,rollbackPolicy:n})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free"}),nn=e=>{let{contextVariableDefaultValues:t}=kt(e??{});return j(t)},Lr=()=>({...j(Ve)}),$r=({loadedRuntime:e,runtimeIds:t,defaults:n={},path:r})=>{if(e===void 0)return{runtimeState:j(n),hasLoadedValues:!1};if(!V(e))throw new Error(`Malformed ${r}.`);let o=j(n),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Or(s,j(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},As=({loadedGlobalRuntime:e={}})=>$r({loadedRuntime:e,runtimeIds:Xt,defaults:ot,path:"global.runtime"}).runtimeState,ws=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:n}=$r({loadedRuntime:e,runtimeIds:Jt,defaults:Lr(),path:"context.runtime"});return n?t:void 0},kr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},xs=e=>e.runtime?(Jt.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=j(Ve[t]))}),e.runtime):(e.runtime=Lr(),e.runtime),Es=e=>yr(e.global),vs=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Es(e)}})},Ss=e=>mr[e],_s=(e,t)=>{let n=Ss(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}"`)},Or=(e,t)=>(_s(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),Pr=(e,t,n)=>{let r=Or(t,n);if(t in Ve){let o=kr(e);if(!o)return r;let i=xs(o);return i[t]=r,r}return e.global[t]=r,r},Tr=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:j(e)},configuration:{},views:[],bgm:ls(),variables:nn(t),rollback:Me({pointer:e})}),Le=e=>e?(e.currentPointerMode="read",V(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Cs=e=>{let t=e.contexts?.[e.contexts.length-1],n=t?.pointers?.read;if(!t||!n?.sectionId||!n?.lineId)return null;let r=Tr({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=r,Rs(e),r},Rs=e=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,Re(e),e.global.nextLineConfig=at(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})},Dr=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},Me=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[st({sectionId:e.sectionId,lineId:e.lineId})]:[]}},Ie=(e,t={})=>{if(e?.rollback)return Dr(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=Me({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},rn=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=Ie(n);if(r.isRestoring)return;r.currentIndex<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,r.currentIndex+1));let o=r.timeline[r.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){r.currentIndex=r.timeline.length-1;return}r.timeline.push(st(t)),r.currentIndex=r.timeline.length-1},Ls=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=ye[ye.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)},$s=({state:e},t={})=>{let n=t?.source===Ar?Ar:tn,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?(ye.push({checkpointIndex:null,source:n}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),ye.push({checkpointIndex:o.currentIndex,source:n}),e)},ks=({state:e})=>(ye.pop(),e),oe=(e,t,n)=>{let o=ye[ye.length-1]?.source??tn;if(!ja(t,o))return;let i=Ls(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:j(n)}))},wr=(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}of r){let a=e.projectData.resources?.variables?.[o],l=a?.scope,c=a?.type;Ot(l,o),Pt(c,i,o),l==="context"&&(n.variables[o]=Tt(n.variables[o],i,s))}},Os=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:n,payload:r})=>{Ua(e,n,r)})},Ps=(e,t)=>{let{sectionId:n,lineId:r}=t,s=H({state:e},{sectionId:n})?.lines?.find(a=>a.id===r)?.actions;s&&Object.entries(s).forEach(([a,l])=>{Ba(e,a,l)})},Nr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=Ie(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Ue({state:e}),e.global.skipMode&&be({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=nn(e.projectData),delete n.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=j(it),e.global.overlayStack=[],Re(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let a=i;a<=t;a++)a>i&&Qt(e),Ps(e,r.timeline[a]),Os(e,r.timeline[a]);let s=Le(n);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(a=>a?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},Ts=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=n;vr(t);let a=t.story.initialSceneId,l=t.story.scenes[a],c=l.initialSectionId,u=l.sections[c],f={sceneId:a,sectionId:c,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:d}=kt(t),p={...d,...o};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,accountViewedRegistry:hs(s,"accountViewedRegistry"),nextLineConfig:at(),saveSlots:ds(r),overlayStack:[],variables:p,...As({loadedGlobalRuntime:i})},contexts:[Tr({pointer:f,projectData:t})]}},Ds=({state:e})=>e.global.overlayStack||[],Ns=({state:e})=>e.global.pendingEffects,Vr=({state:e})=>e.global.skipMode,Vs=({state:e})=>e.global.autoMode,Mr=({state:e})=>e.global.dialogueUIHidden,jr=({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=H({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),a=i.lines.slice(0,s+1),l=[],c={};for(let u of a){let f=u.actions||{};if(c=Se([c,f]),!f.dialogue)continue;let d=c.dialogue||{},p="";d.character?.name!==void 0?p=d.character.name:d.characterId&&(p=e.projectData.resources?.characters?.[d.characterId]?.name||""),l.push({sectionId:r,lineId:u.id,content:f.dialogue.content,text:cs(f.dialogue.content),characterId:d.characterId,character:{...d.character||{},name:p},characterName:p})}return l},Ms=({state:e})=>e.global.confirmDialog??null,js=({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 a=H({state:e},{sectionId:r});if(!a||!a.lines||!Array.isArray(a.lines))return s.lastLineId===o;let l=a.lines.findIndex(u=>u.id===s.lastLineId),c=a.lines.findIndex(u=>u.id===o);return l===-1||c===-1?s.lastLineId===o:c<=l},Us=({registry:e},t)=>{let{resourceId:n}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===n)},on=({state:e},t)=>js({state:e,registry:e.global.accountViewedRegistry},t),Bs=({state:e},t)=>Us({registry:e.global.accountViewedRegistry},t),Fs=({state:e})=>e.global.nextLineConfig,Ur=({state:e,pointer:t}={})=>{let n=t??ee({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=H({state:e},{sectionId:r})?.lines||[],a=s.findIndex(c=>c.id===o);if(a<0)return;let l;for(let c of s.slice(0,a+1)){let u=c?.actions;if(u?.cleanAll&&(l=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){l=void 0;continue}let f=u.choice;if(f?.resourceId){l=f.resourceId;continue}f?.animations||(l=void 0)}return l},te=({state:e})=>!!Ur({state:e}),zs=({state:e})=>structuredClone(e),Br=({state:e})=>e.global.saveSlots,Ws=({state:e},t)=>{let n=t?.slotId,r=ct(n);return e.global.saveSlots[r]},sn=({state:e})=>Zt(e),Ys=({state:e},t)=>re(e,t?.runtimeId),Fr=({state:e})=>({...e.global?.variables??{},...kr(e)?.variables??{}}),ee=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(n)return{currentPointerMode:"read",pointer:n.pointers?.read}},H=({state:e},t)=>{let{sectionId:n}=t;return en(e.projectData,n).section},an=({state:e})=>{let t=ee({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=H({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},zr=({state:e})=>{let{sectionId:t,lineId:n}=ee({state:e}).pointer,o=H({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n),a=o.slice(0,i+1).map(c=>{let u=c.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return Se(a)},Hs=({state:e})=>{let t=Wr({state:e}),r=an({state:e})?.actions??{},o=Se([t??{},r]);return Dt(t??{},o??{})},qs=({state:e},{sectionId:t})=>{let n=H({state:e},{sectionId:t});if(!n?.lines)return[];let r=[],o={};for(let i of n.lines){let s=i.actions||{},a=Se([o,s]),l=Dt(o,a);r.push({id:i.id,changes:l,presentationState:a}),o=Nt(a)}return r},Ks=({state:e},{sectionId:t,includePresentationState:n=!1})=>{let r=qs({state:e},{sectionId:t});return n?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},Wr=({state:e})=>{let{sectionId:t,lineId:n}=ee({state:e}).pointer,o=H({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===n);if(i<=0)return null;let a=o.slice(0,i).map(l=>{let c=l.actions||{},u={};return Object.keys(c).forEach(f=>{u[f]=c[f]}),u});return Nt(Se(a))},cn=({state:e},{slotsPerPage:t=6}={})=>{let o=((sn({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let a=o+s,l=e.global.saveSlots&&e.global.saveSlots[ct(a)]||{};i.push({...l,slotId:a})}return{saveSlots:i}},Gs=Br,Xs=cn,Js=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},Zs=({state:e},t={})=>{let n=zr({state:e}),r=Wr({state:e}),o=an({state:e})?.actions??{},{sectionId:i}=ee({state:e}).pointer,{sceneId:s}=en(e.projectData,i),a=sn({state:e}),l=t?.activePersistentAnimations??[],c=t?.restoredPersistentAnimations??[],u=Fr({state:e}),{saveSlots:f}=cn({state:e}),d=Js(e);return gr({presentationState:n,previousPresentationState:r,currentLineActions:o,resources:e.projectData.resources,currentSceneId:s,screen:e.projectData.screen,dialogueUIHidden:a.dialogueUIHidden,autoMode:a.autoMode,skipMode:a.skipMode,isChoiceVisible:te({state:e}),canRollback:eo({state:e}),skipOnlyViewedLines:!a.skipUnseenText,isLineCompleted:a.isLineCompleted,skipTransitionsAndAnimations:!!a.skipTransitionsAndAnimations||d,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,dialogueHistory:jr({state:e}),saveSlots:f,variables:u,runtime:a,activePersistentAnimations:l,restoredPersistentAnimations:c})},Qs=({state:e},t)=>(e.global.confirmDialog=Is(t),e.global.pendingEffects.push({name:"render"}),e),ea=({state:e})=>(e.global.confirmDialog&&(Re(e),e.global.pendingEffects.push({name:"render"})),e),ta=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),oe(e,"pushOverlay",t),e),na=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),oe(e,"popOverlay",void 0),e),ra=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),oe(e,"replaceLastOverlay",t),e),oa=({state:e})=>(e.global.overlayStack=[],Re(e),e.global.pendingEffects.push({name:"render"}),oe(e,"clearOverlays",void 0),e),ia=e=>{e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},lt=(e,t)=>{e.global.isLineCompleted=!1;let n=!!Ur({state:e,pointer:t});return n&&ia(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:n}},Yr=({state:e})=>(te({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:re(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),Ue=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),sa=({state:e})=>{let t=e.global.autoMode;return te({state:e})&&!t||(t?Ue({state:e}):Yr({state:e})),e},Hr=({state:e})=>(te({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),be=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),aa=({state:e})=>{let t=Vr({state:e});return te({state:e})&&!t||(t?be({state:e}):Hr({state:e})),e},ut=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),oe(e,"showDialogueUI",void 0),e),qr=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),oe(e,"hideDialogueUI",void 0),e),ca=({state:e})=>(Mr({state:e})?ut({state:e}):qr({state:e}),e),Ae=(e,t,n)=>(Pr(e,t,n),vs(e),e.global.pendingEffects.push({name:"render"}),e),Be=(e,t,n,r)=>{let o=Pr(e,t,n);return e.global.pendingEffects.push({name:"render"}),oe(e,r,{value:o}),e},la=({state:e},t)=>Ae(e,"dialogueTextSpeed",t?.value),ua=({state:e},t)=>Ae(e,"autoForwardDelay",t?.value),fa=({state:e},t)=>Ae(e,"skipUnseenText",t?.value),da=({state:e},t)=>Ae(e,"skipTransitionsAndAnimations",t?.value),pa=({state:e},t)=>Ae(e,"soundVolume",t?.value),ha=({state:e},t)=>Ae(e,"musicVolume",t?.value),ga=({state:e},t)=>Ae(e,"muteAll",t?.value),ma=({state:e},t)=>Be(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),ya=({state:e})=>{let t=re(e,"saveLoadPagination")+1;return Be(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},ba=({state:e})=>{let t=re(e,"saveLoadPagination")-1;return Be(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},Ia=({state:e},t)=>Be(e,"menuPage",t?.value,"setMenuPage"),Aa=({state:e},t)=>Be(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),wa=({state:e})=>(e.global.pendingEffects=[],e),xa=({state:e},t)=>(e.global.pendingEffects.push(t),e),Kr=(e,{sectionId:t,resetStoryState:n=!1})=>{let r=H({state:e},{sectionId:t});if(!r)return console.warn(`Section not found: ${t}`),e;let o=r.lines?.[0];if(!o)return console.warn(`Section ${t} has no lines`),e;if(n&&!Cs(e))return e;e.global.autoMode&&Ue({state:e}),e.global.skipMode&&be({state:e});let i=e.contexts?.[e.contexts.length-1];if(i){let s=Le(i);i.rollback||Ie(i,{compatibilityAnchor:!0}),s.read={sectionId:t,lineId:o.id},n?i.rollback=Me({pointer:s.read}):rn(e,{sectionId:t,lineId:o.id})}return lt(e,i?.pointers?.read),e},Ea=({state:e},t)=>Kr(e,{sectionId:t?.sectionId,resetStoryState:!0}),Gr=e=>(e.global.accountViewedRegistry=as(e.global.accountViewedRegistry),e.global.accountViewedRegistry),Xr=(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:j(n.value)}))}})},Jr=(e,t)=>{Xr(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:[]}}])},va=(e,t,{sectionId:n,lineId:r})=>{if(!n||!r)return!1;let o=V(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=H({state:e},{sectionId:n});if(s?.lines){let a=s.lines.findIndex(c=>c.id===i.lastLineId),l=s.lines.findIndex(c=>c.id===r);if(a===-1||l>a)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},je=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;va(e,Gr(e),t)&&Jr(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},Sa=({state:e},t)=>(je(e,t),e.global.pendingEffects.push({name:"render"}),e),_a=({state:e},t)=>{let{resourceId:n}=t;if(e.global.accountViewedRegistry!==void 0){let r=Gr(e);r.resources.find(i=>i.resourceId===n)||(r.resources.push({resourceId:n}),Jr(e,{sections:[],resources:[{resourceId:n}]}))}return e.global.pendingEffects.push({name:"render"}),e},Zr=({state:e},t)=>{let n=us(t.manual),{auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,a=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 l=e.global.nextLineConfig.auto?.enabled,c=te({state:e});return!a&&!c&&l===!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}}):!a&&l===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),oe(e,"setNextLineConfig",t),e},Ca=({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=ct(n),s=j(e.contexts);s?.forEach(c=>{Le(c),Dr(c.rollback),ps(c.rollback)});let a={contexts:s},l={formatVersion:xr,slotId:Sr(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:a};return e.global.saveSlots[i]=l,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Ra=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=ct(n),o=e.global.saveSlots[r];if(o){let i=bs(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=at(),e.global.overlayStack=[],e.global.isLineCompleted=!0,Re(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},La=({state:e},t)=>{let{projectData:n}=t;return vr(n),e.projectData=n,Re(e),e.global.pendingEffects.push({name:"render"}),e},$a=({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&&!H({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=H({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(c=>c.id===r))return console.warn(`Line not found: ${r} in section ${i}`),e;let l=Le(o);return l.read={sectionId:i,lineId:r},lt(e,l.read),e},ka=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return ut({state:e}),e;if(te({state:e})&&t?._interactionSource!=="choice")return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0;let c=ee({state:e})?.pointer,u=c?.sectionId,f=c?.lineId;u&&f&&je(e,{sectionId:u,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:re(e,"autoForwardDelay")}});let d=e.global.nextLineConfig;return d?.auto?.enabled&&d.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:d.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=ee({state:e})?.pointer,r=n?.sectionId,o=H({state:e},{sectionId:r}),i=e.contexts[e.contexts.length-1],s=o?.lines||[],l=s.findIndex(c=>c.id===n?.lineId)+1;if(l<s.length){let c=s[l],u=!re(e,"skipUnseenText");if(e.global.skipMode&&u&&!on({state:e},{sectionId:r,lineId:c.id}))return be({state:e}),e;if(i&&!i.rollback&&Ie(i,{compatibilityAnchor:!0}),i){let p=Le(i),g=p.read?.lineId;g&&r&&je(e,{sectionId:r,lineId:g}),p.read={sectionId:r,lineId:c.id}}rn(e,{sectionId:r,lineId:c.id}),Qt(e);let{isChoiceVisible:f}=lt(e,{sectionId:r,lineId:c.id}),d=e.global.nextLineConfig;d?.auto?.enabled&&!f&&d.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:d.auto.delay}})}else e.global.autoMode&&Ue({state:e}),e.global.skipMode&&be({state:e});return e},Oa=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0;let t=te({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:re(e,"autoForwardDelay")}});let n=ee({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&je(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},Pa=({state:e},t)=>Kr(e,{sectionId:t?.sectionId}),Ta=({state:e})=>{if(e.global.dialogueUIHidden)return ut({state:e}),e;if(te({state:e}))return e;let t=ee({state:e})?.pointer,n=t?.sectionId,r=H({state:e},{sectionId:n}),o=e.contexts[e.contexts.length-1],i=r?.lines||[],a=i.findIndex(l=>l.id===t?.lineId)+1;if(a<i.length){let l=i[a],c=!re(e,"skipUnseenText");if(e.global.skipMode&&c&&!on({state:e},{sectionId:n,lineId:l.id}))return be({state:e}),e;if(o&&!o.rollback&&Ie(o,{compatibilityAnchor:!0}),o){let f=Le(o),d=f.read?.lineId;d&&n&&je(e,{sectionId:n,lineId:d}),f.read={sectionId:n,lineId:l.id}}rn(e,{sectionId:n,lineId:l.id}),Qt(e);let{isChoiceVisible:u}=lt(e,{sectionId:n,lineId:l.id});e.global.nextLineConfig.auto?.enabled&&!u&&e.global.nextLineConfig.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})}else e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},Da=({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=[],a=[];return r.forEach(({variableId:l,op:c,value:u})=>{let f=e.projectData.resources?.variables?.[l],d=f?.scope,p=f?.type;Ot(d,l),Pt(p,c,l);let g=d==="context"?o.variables:e.global.variables;d==="context"&&(i=!0,a.push({variableId:l,op:c,value:u})),g[l]=Tt(g[l],c,u),(d==="device"||d==="account")&&s.push({scope:d,path:`variables.${l}`,op:"set",value:j(g[l])})}),i&&oe(e,"updateVariable",{id:n,operations:a}),Xr(e,s),e.global.pendingEffects.push({name:"render"}),e},Na=e=>(t,n)=>e({state:t},n),Va={updateVariable:{recordSources:[tn],replayLine:wr,replayRecorded:wr,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Na(Zr)}},ft=e=>Va[e]??null,Ma=e=>ft(e)?.persistInSaveSlot===!0,ja=(e,t)=>{let n=ft(e)?.recordSources;return Array.isArray(n)&&n.includes(t)},Ua=(e,t,n)=>{ft(t)?.replayRecorded?.(e,n)},Ba=(e,t,n)=>{ft(t)?.replayLine?.(e,n)},Qr=({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=o.currentIndex+n;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},eo=({state:e})=>Qr({state:e},{offset:-1})!==null,Fa=({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=Ie(r,{compatibilityAnchor:!r.rollback}),i=o.currentIndex+n;return i<0||i>=o.timeline.length?e:Nr(e,i)},za=({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=Ie(o,{compatibilityAnchor:!o.rollback}),a=i.timeline.slice(0,i.currentIndex+1).findLastIndex(l=>l.sectionId===n&&l.lineId===r);if(a===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return a===i.currentIndex?e:Nr(e,a)},to=e=>{let t=Ts(e);return Mn(t,{selectPendingEffects:Ns,selectSkipMode:Vr,selectAutoMode:Vs,selectIsChoiceVisible:te,selectDialogueUIHidden:Mr,selectDialogueHistory:jr,selectConfirmDialog:Ms,selectIsLineAccountViewed:on,selectIsResourceAccountViewed:Bs,selectNextLineConfig:Fs,selectSystemState:zs,selectSaveSlotMap:Br,selectSaveSlots:Gs,selectSaveSlot:Ws,selectRuntime:sn,selectRuntimeValue:Ys,selectAllVariables:Fr,selectCurrentPointer:ee,selectSection:H,selectCurrentLine:an,selectPresentationState:zr,selectPresentationChanges:Hs,selectSectionLineChanges:Ks,selectSaveSlotPage:cn,selectCurrentPageSlots:Xs,selectRenderState:Zs,selectOverlayStack:Ds,selectLineIdByOffset:Qr,selectCanRollback:eo,startAutoMode:Yr,stopAutoMode:Ue,toggleAutoMode:sa,startSkipMode:Hr,stopSkipMode:be,toggleSkipMode:aa,showDialogueUI:ut,hideDialogueUI:qr,toggleDialogueUI:ca,setDialogueTextSpeed:la,setAutoForwardDelay:ua,setSkipUnseenText:fa,setSkipTransitionsAndAnimations:da,setSoundVolume:pa,setMusicVolume:ha,setMuteAll:ga,setSaveLoadPagination:ma,incrementSaveLoadPagination:ya,decrementSaveLoadPagination:ba,setMenuPage:Ia,setMenuEntryPoint:Aa,showConfirmDialog:Qs,hideConfirmDialog:ea,resetStoryAtSection:Ea,clearPendingEffects:wa,appendPendingEffect:xa,beginRollbackActionBatch:$s,endRollbackActionBatch:ks,addViewedLine:Sa,addViewedResource:_a,setNextLineConfig:Zr,saveSlot:Ca,loadSlot:Ra,updateProjectData:La,sectionTransition:Pa,jumpToLine:$a,nextLine:ka,markLineCompleted:Oa,rollbackToLine:za,rollbackByOffset:Fa,pushOverlay:ta,popOverlay:na,replaceLastOverlay:ra,clearOverlays:oa,updateVariable:Da,nextLineFromSystem:Ta},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var Wa="route-engine",Ya="projectPersistence";var ro=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),F=e=>Object.prototype.toString.call(e)==="[object Object]",no="variables.",Ha=(e={})=>{let t=F(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!F(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)}:!F(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},qa=(e={})=>{let t=F(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!F(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)}:!F(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},Ka=(e,t)=>{let n=qa(e),r=Ha(t),o=n.sections.map(s=>({...s})),i=n.resources.map(s=>({...s}));return r.sections.forEach(s=>{let a=o.find(l=>l.sectionId===s.sectionId);if(!a){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(a.lastLineId!==void 0){if(s.lineId===void 0){delete a.lastLineId;return}a.lastLineId=s.lineId}}),r.resources.forEach(s=>{i.find(l=>l.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},oo=(e={})=>{let t=F(e)?e:{};return{saveSlots:F(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:F(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:F(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:F(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:F(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Ga=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,n)=>{if(!F(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${n}] entry.`);let r=t.path?.startsWith(no)?t.path.slice(no.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}].`)})},Xa=(e,t)=>{let n={};return Ga(t).forEach(r=>{if(r.path==="viewedRegistry"){n.accountViewedRegistry=Ka(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},ln=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},Ja=e=>{let t=ln(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Za=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},Qa=({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}".`))}}),ec=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let l=r.transaction(t,"readonly").objectStore(t).get(n);l.onsuccess=()=>{o(l.result??null)},l.onerror=()=>{i(l.error??new Error(`Failed to read persisted namespace "${n}" from IndexedDB.`))}})},Fe=async({databasePromise:e,objectStoreName:t,namespace:n,patch:r})=>{let o=await e;return new Promise((i,s)=>{let a=o.transaction(t,"readwrite"),l=a.objectStore(t),c=l.get(n),u=!1,f=p=>{u||(u=!0,s(p))},d=()=>{u||(u=!0,i())};c.onerror=()=>{f(c.error??new Error(`Failed to read persisted namespace "${n}" before updating IndexedDB.`))},c.onsuccess=()=>{let p=oo(c.result),g=typeof r=="function"?r(p):r,y={namespace:n,version:1,...ro(),...p,...g},I=l.put(y);I.onerror=()=>{f(I.error??new Error(`Failed to persist namespace "${n}" to IndexedDB.`))}},a.oncomplete=()=>{d()},a.onerror=()=>{f(a.error??new Error(`IndexedDB transaction failed while updating namespace "${n}".`))},a.onabort=()=>{f(a.error??new Error(`IndexedDB transaction aborted while updating namespace "${n}".`))}})},tc=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let s=r.transaction(t,"readwrite"),l=s.objectStore(t).delete(n),c=!1,u=d=>{c||(c=!0,i(d))},f=()=>{c||(c=!0,o())};l.onerror=()=>{u(l.error??new Error(`Failed to clear persisted namespace "${n}" from IndexedDB.`))},s.oncomplete=()=>{f()},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}".`))}})},un=(e={})=>{let{indexedDB:t,databaseName:n=Wa,objectStoreName:r=Ya,namespace:o}=e,i=Za(t),s=Ja(o),a=Qa({indexedDB:i,databaseName:n,objectStoreName:r});return{namespace:s,load:async()=>{let l=await ec({databasePromise:a,objectStoreName:r,namespace:s});return{...ro(),...oo(l)}},clear:async()=>tc({databasePromise:a,objectStoreName:r,namespace:s}),saveSlots:async l=>Fe({databasePromise:a,objectStoreName:r,namespace:s,patch:{saveSlots:F(l)?l:{}}}),saveGlobalDeviceVariables:async l=>Fe({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:F(l)?l:{}}}),saveGlobalAccountVariables:async l=>Fe({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalAccountVariables:F(l)?l:{}}}),saveGlobalRuntime:async l=>Fe({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalRuntime:F(l)?l:{}}}),applyScopedDataUpdates:async l=>Fe({databasePromise:a,objectStoreName:r,namespace:s,patch:c=>Xa(c,l)})}},nc=un;var rc=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),oc=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]);function fn(e){let t,n=0,r=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:a}=e,l=(S=new Map,P=Date.now())=>new Map(Array.from(S.entries()).filter(([,z])=>P<z.expiresAt).map(([z,K])=>[z,{animation:structuredClone(K.animation),startedAt:K.startedAt,expiresAt:K.expiresAt}])),c=(S=new Map)=>Array.from(S.values()).map(P=>structuredClone(P.animation)),u=(S=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,P])=>S<P.expiresAt))},f=()=>{for(;t.selectPendingEffects().length>0;){let S=[...t.selectPendingEffects()];t.clearPendingEffects();try{a(S)}catch(P){throw t.clearPendingEffects(),S.forEach(z=>{t.appendPendingEffect(z)}),P}}},d=({initialState:S,namespace:P})=>{t=to(S),n=0,r=ln(P),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),f()},p=()=>r,g=()=>t.selectPresentationState(),y=()=>t.selectPresentationChanges(),I=S=>t.selectSectionLineChanges(S),b=(S={})=>{n+=1;let P=Date.now();u(P);let z=i.size>0,K=l(o,P),ie=z?l(i,P):new Map,we={...t.selectRenderState({activePersistentAnimations:c(K),restoredPersistentAnimations:c(ie)}),id:`render-${n}`};return s.set(we.id,{builtAt:P,persistentAnimationSessions:new Map([...ie.entries(),...K.entries()]),usedRestoredPersistentAnimationSessions:z}),we},m=(S={})=>b(S),w=(S={})=>b(S),v=S=>{let P=typeof S?.id=="string"&&S.id.length>0?S.id:null,z=P?s.get(P):null;P&&s.delete(P);let K=new Map;ir(S?.animations).forEach(ie=>{let ce=nt(ie);if(!ce)return;let we=z?.persistentAnimationSessions?.get(ce)??o.get(ce),ao=Math.max(0,ar(ie)),pn=we?.startedAt??z?.builtAt??Date.now();K.set(ce,{animation:structuredClone(ie),startedAt:pn,expiresAt:pn+ao})}),o=K,z?.usedRestoredPersistentAnimationSessions&&(i=new Map)},R=()=>t.selectSystemState(),L=()=>t.selectSaveSlotMap(),_=S=>t.selectSaveSlot(S),D=S=>t.selectSaveSlotPage(S),O=()=>t.selectSkipMode(),$=()=>t.selectAutoMode(),k=()=>t.selectRuntime(),A=()=>t.selectIsChoiceVisible(),E=(S,P)=>{t[S]&&(rc.has(S)&&(oc.has(S)?i=l(o):i=new Map,o=new Map),t[S](P),f())},N=(S,P)=>{E(S,P)},U=S=>{if(!S)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(S,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:P,...z}=S,K=t.selectAllVariables?t.selectAllVariables():void 0;return{...z,_event:P,variables:K,runtime:t.selectRuntime?t.selectRuntime():{}}},B=(S,P,z={})=>{let K=U(P),ie=Bn(S,K);t.beginRollbackActionBatch({source:z.rollbackSource});try{Object.entries(ie).forEach(([ce,we])=>{E(ce,we)})}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:E,handleInternalAction:N,handleActions:B,selectRenderState:m,prepareRenderState:w,commitRenderState:v,selectPresentationState:g,selectPresentationChanges:y,selectSectionLineChanges:I,selectSystemState:R,selectSaveSlotMap:L,selectSaveSlot:_,selectSaveSlotPage:D,selectSaveSlots:L,selectRuntime:k,selectIsChoiceVisible:A,handleLineActions:()=>{let S=t.selectCurrentLine();return S?.actions?(B(S.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var dn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},ic=80,so=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{let o=e.prepareRenderState?.(r)??e.selectRenderState(r);n?.(o),t.render(o),e.commitRenderState?.(o)},sc=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&so({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},ac=({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 a=r.delay??1e3;n.getElapsed()>=a&&(t.remove(i),n.setCallback(null),n.setElapsed(0),dt(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},cc=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},lc=({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 a=r?.delay??ic;n.getElapsed()>=a&&(n.setElapsed(0),dt(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},uc=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},fc=({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 a=r.delay??1e3;n.getElapsed()>=a&&(n.setElapsed(0),dt(e,"nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},dc=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},pc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveSlots(t?.saveSlots))},hc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalDeviceVariables(t?.globalDeviceVariables))},gc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalAccountVariables(t?.globalAccountVariables))},mc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalRuntime(t?.globalRuntime))},yc=({enqueuePersistenceWrite:e},t)=>{e(n=>{if(typeof n.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return n.applyScopedDataUpdates(t?.updates)})},io={render:so,saveSlots:pc,saveGlobalDeviceVariables:hc,saveGlobalAccountVariables:gc,saveGlobalRuntime:mc,applyScopedDataUpdates:yc,handleLineActions:sc,startAutoNextTimer:ac,clearAutoNextTimer:cc,startSkipNextTimer:lc,clearSkipNextTimer:uc,nextLineConfigTimer:fc,clearNextLineConfigTimer:dc},bc=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),dt=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},Ic=(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(!bc.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},Ac=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:a})=>{let l=dn(),c=dn(),u=dn(),f=s??null,d=Promise.resolve(),p=null,g=null,y=!1,I=0,b=A=>{if(o){o(A);return}console.error("RouteEngine persistence write failed.",A)},m=()=>{if(f)return f;let A=e();return f=un({indexedDB:i,namespace:a??A?.getNamespace?.()}),f},w=A=>{d=d.catch(()=>{}).then(()=>{let E=m();return A(E)}).catch(E=>{b(E)})},v=A=>{let E=typeof A?.id=="string"&&A.id.length>0?A.id:null;I+=1,p=E,y=!1},R=()=>I,L=(A={})=>{if(A?.aborted===!0)return!1;let E=typeof A?.id=="string"&&A.id.length>0?A.id:null;return E?E!==p||E===g?!1:(g=E,!0):p!==null||y?!1:(y=!0,!0)},_=(A,E={})=>{if(A!=="renderComplete"||!L(E))return!1;let N=e();return dt(N,"markLineCompleted",{}),!0},D=(A={})=>{if(A?._interactionSource==="choice")return!0;let E=A?.actions;return!E||typeof E!="object"||Array.isArray(E)?!1:Object.values(E).some(N=>N?._interactionSource==="choice")},O=(A,E={})=>!E?.actions||typeof A?.selectIsChoiceVisible!="function"||!A.selectIsChoiceVisible()?!1:!D(E),$=({preprocessPayload:A,onEvent:E}={})=>async(N,U={})=>{let B=e();if(O(B,U))return E?.(N,U);let q=await A?.(N,U)??U;if(O(B,q))return E?.(N,q);if(_(N,q),q?.actions){let S=q?._event?{_event:q._event}:q?.event?{_event:q.event}:void 0;B.handleActions(q.actions,S)}return E?.(N,q)},k=A=>{let E=e(),N=Ic(A);N.forEach(B=>{if(!io[B.name]&&!r)throw new Error(`Unhandled pending effect "${B.name}".`)});let U={engine:E,routeGraphics:t,ticker:n,autoTimer:l,skipTimer:c,nextLineConfigTimerState:u,trackRenderDispatch:v,getRenderDispatchCount:R,enqueuePersistenceWrite:w};for(let B of N){let q=io[B.name];if(q){q(U,B.payload);continue}r(B,U)}};return k.handleRouteGraphicsEvent=_,k.createRouteGraphicsEventHandler=$,k},wc=Ac;var xc=(e,t={})=>{let{resources:n={}}=t;return Gt(e,n)};var Ll=fn;export{wc as createEffectsHandler,nc as createIndexedDbPersistence,Ll as default,xc as resolveLayoutReferences};
|
|
1
|
+
var Ro=Object.defineProperty;var Lo=(e,t)=>{for(var n in t)Ro(e,n,{get:t[n],enumerable:!0})};var Tn=Symbol.for("immer-nothing"),Ln=Symbol.for("immer-draftable"),X=Symbol.for("immer-state");function ee(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Ce=Object.getPrototypeOf;function ue(e){return!!e&&!!e[X]}function ge(e){return e?Nn(e)||Array.isArray(e)||!!e[Ln]||!!e.constructor?.[Ln]||et(e)||tt(e):!1}var $o=Object.prototype.constructor.toString();function Nn(e){if(!e||typeof e!="object")return!1;let t=Ce(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)===$o}function Ge(e,t){Ze(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function Ze(e){let t=e[X];return t?t.type_:Array.isArray(e)?1:et(e)?2:tt(e)?3:0}function vt(e,t){return Ze(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Dn(e,t,n){let r=Ze(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Oo(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function et(e){return e instanceof Map}function tt(e){return e instanceof Set}function he(e){return e.copy_||e.base_}function St(e,t){if(et(e))return new Map(e);if(tt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=Nn(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[X];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let s=o[i],a=r[s];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(r[s]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[s]})}return Object.create(Ce(e),r)}else{let r=Ce(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function $t(e,t=!1){return nt(e)||ue(e)||!ge(e)||(Ze(e)>1&&(e.set=e.add=e.clear=e.delete=ko),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>$t(r,!0))),e}function ko(){ee(2)}function nt(e){return Object.isFrozen(e)}var Po={};function me(e){let t=Po[e];return t||ee(0,e),t}var Te;function Vn(){return Te}function To(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function $n(e,t){t&&(me("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Ct(e){_t(e),e.drafts_.forEach(No),e.drafts_=null}function _t(e){e===Te&&(Te=e.parent_)}function On(e){return Te=To(Te,e)}function No(e){let t=e[X];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function kn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[X].modified_&&(Ct(t),ee(4)),ge(e)&&(e=Xe(t,e),t.parent_||Qe(t,e)),t.patches_&&me("Patches").generateReplacementPatches_(n[X].base_,e,t.patches_,t.inversePatches_)):e=Xe(t,n,[]),Ct(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Tn?e:void 0}function Xe(e,t,n){if(nt(t))return t;let r=t[X];if(!r)return Ge(t,(o,i)=>Pn(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Qe(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),Ge(i,(a,l)=>Pn(e,r,o,a,l,n,s)),Qe(e,o,!1),n&&e.patches_&&me("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function Pn(e,t,n,r,o,i,s){if(ue(o)){let a=i&&t&&t.type_!==3&&!vt(t.assigned_,r)?i.concat(r):void 0,l=Xe(e,o,a);if(Dn(n,r,l),ue(l))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(ge(o)&&!nt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Xe(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&Qe(e,o)}}function Qe(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&$t(t,n)}function Do(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Vn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=Ot;n&&(o=[r],i=Ne);let{revoke:s,proxy:a}=Proxy.revocable(o,i);return r.draft_=a,r.revoke_=s,a}var Ot={get(e,t){if(t===X)return e;let n=he(e);if(!vt(n,t))return Vo(e,n,t);let r=n[t];return e.finalized_||!ge(r)?r:r===xt(e.base_,t)?(Et(e),e.copy_[t]=Lt(r,e)):r},has(e,t){return t in he(e)},ownKeys(e){return Reflect.ownKeys(he(e))},set(e,t,n){let r=jn(he(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=xt(he(e),t),i=o?.[X];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Oo(n,o)&&(n!==void 0||vt(e.base_,t)))return!0;Et(e),Rt(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 xt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Et(e),Rt(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=he(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ee(11)},getPrototypeOf(e){return Ce(e.base_)},setPrototypeOf(){ee(12)}},Ne={};Ge(Ot,(e,t)=>{Ne[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Ne.deleteProperty=function(e,t){return Ne.set.call(this,e,t,void 0)};Ne.set=function(e,t,n){return Ot.set.call(this,e[0],t,n,e[0])};function xt(e,t){let n=e[X];return(n?he(n):e)[t]}function Vo(e,t,n){let r=jn(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function jn(e,t){if(!(t in e))return;let n=Ce(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=Ce(n)}}function Rt(e){e.modified_||(e.modified_=!0,e.parent_&&Rt(e.parent_))}function Et(e){e.copy_||(e.copy_=St(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var jo=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(l=i,...c){return s.produce(l,u=>n.call(this,u,...c))}}typeof n!="function"&&ee(6),r!==void 0&&typeof r!="function"&&ee(7);let o;if(ge(t)){let i=On(this),s=Lt(t,void 0),a=!0;try{o=n(s),a=!1}finally{a?Ct(i):_t(i)}return $n(i,r),kn(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===Tn&&(o=void 0),this.autoFreeze_&&$t(o,!0),r){let i=[],s=[];me("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ee(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...a)=>this.produceWithPatches(s,l=>t(l,...a));let r,o;return[this.produce(t,n,(s,a)=>{r=s,o=a}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){ge(e)||ee(8),ue(e)&&(e=kt(e));let t=On(this),n=Lt(e,void 0);return n[X].isManual_=!0,_t(t),n}finishDraft(e,t){let n=e&&e[X];(!n||!n.isManual_)&&ee(9);let{scope_:r}=n;return $n(r,t),kn(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=me("Patches").applyPatches_;return ue(e)?r(e,t):this.produce(e,o=>r(o,t))}};function Lt(e,t){let n=et(e)?me("MapSet").proxyMap_(e,t):tt(e)?me("MapSet").proxySet_(e,t):Do(e,t);return(t?t.scope_:Vn()).drafts_.push(n),n}function kt(e){return ue(e)||ee(10,e),Mn(e)}function Mn(e){if(!ge(e)||nt(e))return e;let t=e[X],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=St(e,t.scope_.immer_.useStrictShallowCopy_)}else n=St(e,!0);return Ge(n,(r,o)=>{Dn(n,r,Mn(o))}),t&&(t.finalized_=!1),n}var Q=new jo,Pt=Q.produce,tl=Q.produceWithPatches.bind(Q),nl=Q.setAutoFreeze.bind(Q),rl=Q.setUseStrictShallowCopy.bind(Q),ol=Q.applyPatches.bind(Q),il=Q.createDraft.bind(Q),sl=Q.finishDraft.bind(Q);var p={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},R={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},_e={NOT:0};var w=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},K=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Tt=e=>{if(!e||e.trim()==="")throw new w("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new w(`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 w(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Un=e=>{if(e.trim().endsWith(" in"))throw new w(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new w(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new w(`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 w(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new w(`Invalid loop syntax (got: '$for ${e}')`)}};var Bn=(e,t,n=!1)=>{if(t===null)return new K(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new K(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new K(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new K(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},Fn=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new K(`Unknown function '${e}' (${n})`)};var Mo=(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 B(e.var,n,r);if(e.type===p.LITERAL)return e.value;if(e.type===p.VARIABLE)return B(e.path,n,r);if(e.type===p.INTERPOLATION)return Bo(e.parts,t,n,r);switch(e.type){case p.FUNCTION:return Wn(e,t,n,r);case p.BINARY:return Yn(e,t,n,r);case p.UNARY:return qn(e,t,n,r);case p.CONDITIONAL:return zo(e,t,n,r);case p.LOOP:return Jo(e,t,n,r);case p.OBJECT:return Go(e,t,n,r);case p.ARRAY:return Xo(e,t,n,r);case p.PARTIAL:return Qo(e,t,n,r);case p.PATH_REFERENCE:return Zo(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},zn=new Map,Uo=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 a=s.slice(1,-1);t.push({type:"property",value:a})}else t.push({type:"property",value:s});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},B=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=zn.get(e);if(!r){let i=[],s="",a=0;for(let l=0;l<e.length;l++){let c=e[l];c==="["?(a++,s+=c):c==="]"?(a--,s+=c):c==="."&&a===0?s&&(i.push(s),s=""):s+=c}s&&i.push(s),r=[];for(let l of i){let c=Uo(l.trim());r.push(...c)}zn.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},Bo=(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("")},Wn=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Fn(e.name,o);let s=e.args.map(a=>L(a,t,n,r));return i(...s)},fe=(e,t,n,r)=>{if(e.var&&!e.type)return B(e.var,n,r);switch(e.type){case p.VARIABLE:return B(e.path,n,r);case p.LITERAL:return e.value;case p.BINARY:return Yn(e,t,n,r);case p.UNARY:return qn(e,t,n,r);case p.FUNCTION:return Wn(e,t,n,r);default:return L(e,t,n,r)}},Yn=(e,t,n,r)=>{if(e.op===R.AND||e.op===R.OR){let s=fe(e.left,t,n,r),a=fe(e.right,t,n,r);switch(e.op){case R.AND:return s&&a;case R.OR:return s||a}}let o=L(e.left,t,n,r),i=L(e.right,t,n,r);switch(e.op){case R.EQ:return o==i;case R.NEQ:return o!=i;case R.GT:return o>i;case R.LT:return o<i;case R.GTE:return o>=i;case R.LTE:return o<=i;case R.IN:return Array.isArray(i)?i.includes(o):!1;case R.ADD:if(typeof o!="number"||typeof i!="number")throw new K(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case R.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new K(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},qn=(e,t,n,r)=>{let o=e.op===_e.NOT?fe(e.operand,t,n,r):L(e.operand,t,n,r);if(e.op===_e.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Fo=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===p.VARIABLE)if(B(o.path,n,r)){let s=e.bodies[0];if(s.type===p.OBJECT&&s.properties.length<=5){let a={};for(let l of s.properties){let c=l.parsedKey?L(l.parsedKey,t,n,r):l.key,u=l.value;if(u.type===p.LITERAL)a[c]=u.value;else if(u.type===p.VARIABLE)a[c]=B(u.path,n,r);else if(u.type===p.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===p.VARIABLE){let h=B(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=L(d,t,n,r);f.push(h!=null?String(h):"")}a[c]=f.join("")}else a[c]=L(u,t,n,r)}return a}}else{let s=e.bodies[1];if(s.type===p.OBJECT&&s.properties.length<=5){let a={};for(let l of s.properties){let c=l.parsedKey?L(l.parsedKey,t,n,r):l.key,u=l.value;if(u.type===p.LITERAL)a[c]=u.value;else if(u.type===p.VARIABLE)a[c]=B(u.path,n,r);else if(u.type===p.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===p.VARIABLE){let h=B(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=L(d,t,n,r);f.push(h!=null?String(h):"")}a[c]=f.join("")}else a[c]=L(u,t,n,r)}return a}}}return null},zo=(e,t,n,r)=>{let o=Fo(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||fe(s,t,n,r))return L(e.bodies[i],t,n,r)}return Hn},Wo=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===p.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===p.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===p.OBJECT&&i.properties.length<=5){for(let l of i.properties)if(l.parsedKey)return null;let a=[];for(let l=0;l<t.length;l++){let c=t[l];if(c[s]){let u={};for(let f of i.properties){let d=f.key,h=f.value;if(h.type===p.LITERAL)u[d]=h.value;else if(h.type===p.VARIABLE){let g=h.path;if(g===r)u[d]=c;else if(g.startsWith(r+".")){let y=g.substring(r.length+1);u[d]=c[y]}else return null}else if(h.type===p.INTERPOLATION){let g=[],y=!0;for(let I of h.parts)if(typeof I=="string")g.push(I);else if(I.type===p.VARIABLE){let b=I.path;if(b===r)g.push(c!=null?String(c):"");else if(b.startsWith(r+".")){let m=b.substring(r.length+1),E=c[m];g.push(E!=null?String(E):"")}else{y=!1;break}}else{y=!1;break}if(!y)return null;u[d]=g.join("")}else return null}a.push(u)}}return a}}}return null},Yo=(e,t)=>{let n=e.body,r=e.itemVar,o=Wo(e,t);if(o!==null)return o;if(n.type===p.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let a of n.properties)if(a.parsedKey)return null;let i=[],s=!0;for(let a of n.properties){let l=a.key,c=a.value;if(c.type===p.LITERAL)i.push({key:l,type:"literal",value:c.value});else if(c.type===p.VARIABLE){let u=c.path;if(u===r)i.push({key:l,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:l,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(c.type===p.INTERPOLATION&&c.parts.length===1){let u=c.parts[0];if(u.type===p.VARIABLE){let f=u.path;if(f===r)i.push({key:l,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:l,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let a=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 l=0;l<t.length;l++){let c=t[l];a[l]={id:c.id,title:c.title!=null?String(c.title):"",completed:c.completed}}else for(let l=0;l<t.length;l++){let c=t[l],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=c;else if(f.type==="prop")u[f.key]=c[f.prop];else if(f.type==="item_string")u[f.key]=c!=null?String(c):"";else if(f.type==="prop_string"){let d=c[f.prop];u[f.key]=d!=null?String(d):""}a[l]=u}return a}}return null},qo=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===p.OBJECT&&s.fast!==!1){let a=e.itemVar,l=e.indexVar;for(let c=0;c<o.length;c++){let u=o[c],f={},d={...r,[a]:u,...l&&{[l]:c}};d.__paths__||(d.__paths__=r.__paths__||{});let h=e.iterable.path||"";if(r&&r.__paths__&&h){let g=h.split("."),y=g[0];y in r.__paths__&&(h=r.__paths__[y],g.length>1&&(h+="."+g.slice(1).join(".")))}d.__paths__={...d.__paths__,[a]:`${h}[${c}]`,...l&&{[l]:c}};for(let g of s.properties){let y=g.parsedKey?L(g.parsedKey,t,n,d):g.key,I=g.value;if(I.type===p.LITERAL)f[y]=I.value;else if(I.type===p.VARIABLE){let b=I.path;if(b===a)f[y]=u;else if(b===l)f[y]=c;else if(b.startsWith(a+".")){let m=b.substring(a.length+1);!m.includes(".")&&!m.includes("[")?f[y]=u[m]:f[y]=B(b,n,{...r,[a]:u,...l&&{[l]:c}})}else f[y]=B(b,n,{...r,[a]:u,...l&&{[l]:c}})}else if(I.type===p.INTERPOLATION){let b=[];for(let m of I.parts)if(typeof m=="string")b.push(m);else if(m.type===p.VARIABLE){let E=m.path,S;if(E===a)S=u;else if(E===l)S=c;else if(E.startsWith(a+".")){let $=E.substring(a.length+1);!$.includes(".")&&!$.includes("[")?S=u[$]:S=B(E,n,{...r,[a]:u,...l&&{[l]:c}})}else S=B(E,n,{...r,[a]:u,...l&&{[l]:c}});b.push(S!=null?String(S):"")}else{let E={...r,[a]:u,...l&&{[l]:c}},S=L(m,t,n,E);b.push(S!=null?String(S):"")}f[y]=b.join("")}else{let b={...r,[a]:u,...l&&{[l]:c}};f[y]=L(I,t,n,b)}}i.push(f)}return i}return null},Ho=(e,t,n)=>{let r=e.body;if(r.type===p.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===p.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===p.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===p.OBJECT&&s.properties.length===2){let a=s.properties[0],l=s.properties[1];if(a.key==="id"&&a.value.type===p.VARIABLE&&a.value.path==="item.id"&&l.key==="$if item.highlighted"&&l.value.type===p.CONDITIONAL){let c=[];for(let u=0;u<t.length;u++){let f=t[u];if(f.visible){let d={id:f.id};f.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${f.name}`):(d.highlight=!1,d.message=f.name),c.push(d)}}return c}}}}return null},Jo=(e,t,n,r)=>{let o=L(e.iterable,t,n,r);if(!Array.isArray(o)){let c,u=!1;if(e.iterable.type===p.FUNCTION){u=!0;let d=e.iterable.args.map(h=>h.type===p.LITERAL?typeof h.value=="string"?`'${h.value}'`:String(h.value):h.type===p.VARIABLE?h.path:h.type===p.FUNCTION?`${h.name}(...)`:"?").join(", ");c=`${e.iterable.name}(${d})`}else c=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${c}`;throw Bn(f,o,u)}if(!e.indexVar){let c=Ho(e,o,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=Yo(e,o);if(c!==null)return c}let i=qo(e,t,n,r,o);if(i!==null)return i;let s=[],a=e.iterable.path||"";if(r&&r.__paths__&&a){let c=a.split("."),u=c[0];u in r.__paths__&&(a=r.__paths__[u],c.length>1&&(a+="."+c.slice(1).join(".")))}let l=!1;e.body.type===p.ARRAY&&(e.body.items.length<=1?l=!1:l=e.body._shouldPreserveArray??=e.body.items.some(c=>c.type===p.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]:`${a}[${c}]`},e.indexVar&&(u.__paths__[e.indexVar]=c);let f=L(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!l){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},Ko=(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===p.OBJECT&&s.properties.length<=10&&!s.whenCondition){let a={},l={},c=!0;for(let u of s.properties){let f=u.parsedKey?L(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)l[f]=d.value;else if(d.type===p.VARIABLE)l[f]=B(d.path,n,r);else if(d.type===p.INTERPOLATION){let h=[];for(let g of d.parts)if(typeof g=="string")h.push(g);else if(g.type===p.VARIABLE){let y=B(g.path,n,r);h.push(y!=null?String(y):"")}else{c=!1;break}if(!c)break;l[f]=h.join("")}else if(d.type===p.OBJECT&&d.properties.length<=5){let h={};for(let g of d.properties){let y=g.key,I=g.value;if(I.type===p.LITERAL)h[y]=I.value;else if(I.type===p.VARIABLE)h[y]=B(I.path,n,r);else if(I.type===p.INTERPOLATION){let b=[];for(let m of I.parts)if(typeof m=="string")b.push(m);else if(m.type===p.VARIABLE){let E=B(m.path,n,r);b.push(E!=null?String(E):"")}else{c=!1;break}if(!c)break;h[y]=b.join("")}else{c=!1;break}}if(!c)break;l[f]=h}else{c=!1;break}}if(c)return a[i]=l,a}}return null},Go=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!fe(e.whenCondition,o,n,r))return;let i=Ko(e,t,n,r);if(i!==null)return i;if(e.fast){let c={};for(let u of e.properties){let f=u.parsedKey?L(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)c[f]=d.value;else if(d.type===p.VARIABLE)c[f]=B(d.path,n,r);else if(d.type===p.INTERPOLATION){let h=[];for(let g of d.parts)if(typeof g=="string")h.push(g);else if(g.type===p.VARIABLE){let y=B(g.path,n,r);h.push(y!=null?String(y):"")}else{let y=L(g,t,n,r);h.push(y!=null?String(y):"")}c[f]=h.join("")}else c[f]=L(d,t,n,r)}return c}let s={},a=null,l=!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 ")){l=!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(!l&&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===p.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=L(f.value,t,n,r);d!==void 0&&(s[c.key]=d)}else{let d=L(c.value,t,n,r);d!==void 0&&(s[c.key]=d)}}else{let f=c.parsedKey?L(c.parsedKey,t,n,r):c.key,d=L(c.value,t,n,r);d!==void 0&&(s[f]=d)}}return s},Hn={},Xo=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===p.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!==Hn&&s!==void 0&&o.push(s)}return o},Qo=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,a=t.partials||{},l=t.functions||t;if(s&&!fe(s,l,n,r))return;if(!a[o])throw new K(`Partial '${o}' is not defined`);let c=r._partialStack||[];if(c.includes(o))throw new K(`Circular partial reference detected: ${o}`);let u=a[o],f=n,d={...r,_partialStack:[...c,o]};if(r){f={...n};for(let h of Object.keys(r))h.startsWith("_")||(f[h]=r[h])}if(i){let h=L(i,t,n,r);f={...f,...h}}return L(u,t,f,d)},Zo=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),s=i[0],a=i.slice(1);if(!r||!(s in r))throw new K(`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 K(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let l=r.__paths__[s];if(typeof l=="number"){if(a.length>0)throw new K(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(l)}return a.length>0&&(l+="."+a.join(".")),l};var Nt=Mo;var ei=/\$\{([^}]*)\}/g,ti=/#\{([^}]*)\}/g,Kn=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=ni(o,t);return{isFunction:!0,type:p.FUNCTION,name:r,args:i}},ni=(e,t={})=>e.trim()?ri(e).map(r=>oi(r.trim(),t)):[],ri=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let a=e[s],l=s>0?e[s-1]:"";!o&&(a==='"'||a==="'")?(o=!0,i=a,n+=a):o&&a===i&&l!=="\\"?(o=!1,i="",n+=a):!o&&a==="("?(r++,n+=a):!o&&a===")"?(r--,n+=a):!o&&a===","&&r===0?(t.push(n),n=""):n+=a}return n&&t.push(n),t},oi=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:p.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:p.LITERAL,value:parseFloat(e)};if(e==="true")return{type:p.LITERAL,value:!0};if(e==="false")return{type:p.LITERAL,value:!1};if(e==="null")return{type:p.LITERAL,value:null};let n=Kn(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:a,type:l}of o){let c=0;for(;c<r.length;){let u=ye(r.substring(c),a);if(u===-1)break;let f=c+u;f>i&&(i=f,s={op:a,type:l}),c=f+a.length}}if(i!==-1)try{return W(r,t)}catch{return{type:p.VARIABLE,path:r}}return{type:p.VARIABLE,path:r}},Gn=/^\w+\(.*\)$/,ii=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,si=e=>{if(!(!e||e.trim()===""||Gn.test(e))&&ii.test(e))throw e.includes("?")&&e.includes(":")?new w(`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 w(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new w(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Jn=e=>{let t=e.trim();if(Gn.test(t))throw new w(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new w(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new w(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new w(`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 w(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:p.PATH_REFERENCE,path:t}},De=(e,t={})=>{let n=e.trim();si(n);let r=Kn(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:p.VARIABLE,path:n}},Dt=(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 f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\(#\{[^}]*\})/g,(c,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...n.matchAll(ei)],i=[...n.matchAll(ti)],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:p.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"?De(c[1],t):Jn(c[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:p.LITERAL,value:n};throw f}}let a=[],l=0;for(let{match:c,type:u}of s){let[f,d]=c,h=c.index;if(h>l){let g=n.substring(l,h);for(let y=0;y<r.length;y++)g=g.replace(`__ESCAPED_${y}__`,r[y]);g&&a.push(g)}try{let g;u==="variable"?g=De(d.trim(),t):g=Jn(d.trim()),a.push(g)}catch(g){if(g.message==="Invalid array index syntax")a.push(f);else throw g}l=h+f.length}if(l<n.length){let c=n.substring(l);for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);c&&a.push(c)}return{type:p.INTERPOLATION,parts:a}};var Mt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Zn=e=>Object.keys(e),J=e=>e.join("."),de=(e,t,n)=>{let r=Zn(e).filter(o=>!t.has(o));if(r.length>0)throw new w(`Unexpected key '${r[0]}' in condition JSON at '${J(n)}'`)},pe=(e,t)=>typeof e=="string"?Dt(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?ci(e,t):li(e,t):{type:p.LITERAL,value:e},ai=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new w("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new w("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new w("Empty $each body not allowed");if(n.$partial!==void 0)throw new w("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},ci=(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 l=ai(i),c=Object.keys(l);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let u=Qn(c[0],l[c[0]],t,!0);n.push(u),r=!0;continue}}catch(l){throw l instanceof w?l:new w(l.message)}let a=Object.keys(i);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let l=Qn(a[0],i[a[0]],t);n.push(l),r=!0;continue}}let s=pe(i,t);n.push(s),(s.type===p.FUNCTION||s.type===p.CONDITIONAL||s.type===p.LOOP||s.type===p.PARTIAL||s.type===p.OBJECT&&!s.fast||s.type===p.ARRAY&&!s.fast)&&(r=!0)}return{type:p.ARRAY,items:n,fast:!r}},li=(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 w("$partial value must be a string");if(e.$partial.trim()==="")throw new w("$partial value cannot be an empty string");let l=["$if","$elif","$else","$for"],c=[];for(let[b]of i)for(let m of l)if(b===m||b.startsWith(m+" ")||b.startsWith(m+"#")){c.push(m);break}if(c.length>0)throw new w(`Cannot use $partial with ${c.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...d}=e,h={},g=!1;for(let[b,m]of Object.entries(d)){let E=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(E=b.slice(1)),h[E]=m,g=!0}let y=null;if(g&&(y=pe(h,t),y.type===p.OBJECT)){let b=!1;for(let m of y.properties)if(m.value.type===p.VARIABLE||m.value.type===p.INTERPOLATION||m.value.type===p.FUNCTION||m.value.type===p.CONDITIONAL||m.value.type===p.OBJECT&&!m.value.fast||m.value.type===p.ARRAY&&!m.value.fast){b=!0;break}b&&(y.fast=!1)}let I={type:p.PARTIAL,name:u,data:y};return f!==void 0&&(I.whenCondition=Xn(f,t)),I}for(let[l,c]of i)if(l==="$when"){if(o!==null)throw new w("Multiple '$when' directives on the same object are not allowed");if(c==null)throw new w("Missing condition expression after '$when'");o=Xn(c,t),r=!0}else if(l.startsWith("$when#")||l.startsWith("$when "))throw new w("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[l,c]=i[s];if(l==="$when"){s++;continue}if(l==="$each")throw new w("$each can only be used inside arrays");if(l.startsWith("$if ")||l.match(/^\$if#\w+\s/)||l.match(/^\$if\s+\w+.*:$/)){let u=ui(i,s,t);n.push({key:l,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(l)){let u=l.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new w(`$for loops must be inside arrays - use '- $for${f} item in items:' instead of '$for${f} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(l.startsWith("$elif ")||l.startsWith("$else"))throw new w(`'${l.split(" ")[0]}' without matching '$if'`);if(l==="$if"||l==="$if:")throw new w("Missing condition expression after '$if'");{let u=pe(c,t);(u.type===p.FUNCTION||u.type===p.CONDITIONAL||u.type===p.PARTIAL||u.type===p.OBJECT&&!u.fast||u.type===p.ARRAY&&!u.fast)&&(r=!0);let f=Dt(l,t),d={key:l,value:u};(f.type!==p.LITERAL||f.value!==l)&&(d.parsedKey=f),n.push(d),s++}}}let a={type:p.OBJECT,properties:n,fast:!r};return o&&(a.whenCondition=o),a},ui=(e,t,n={})=>{let r=[],o=[],i=t,[s,a]=e[i],l=null,c;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)l=f[1],c=f[2];else throw new w(`Invalid conditional syntax: ${s}`)}else c=s.substring(4),c.endsWith(":")&&(c=c.slice(0,-1).trim());Tt(c);let u=W(c,n);for(r.push(u),o.push(pe(a,n)),i++;i<e.length;){let[f,d]=e[i],h=!1,g;if(l?f.startsWith(`$elif#${l} `)?(g=f.substring(`$elif#${l} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f===`$else#${l}`||f===`$else#${l}:`)&&(h=!0,g=null):f.startsWith("$elif ")?(g=f.substring(6),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f==="$else"||f==="$else:")&&(h=!0,g=null),h){if(g===null)r.push(null);else{Tt(g);let y=W(g,n);r.push(y)}if(o.push(pe(d,n)),i++,g===null)break}else break}return{node:{type:p.CONDITIONAL,conditions:r,bodies:o,id:l},nextIndex:i}},Vt={eq:R.EQ,neq:R.NEQ,gt:R.GT,gte:R.GTE,lt:R.LT,lte:R.LTE,in:R.IN,add:R.ADD,sub:R.SUBTRACT},jt={all:R.AND,any:R.OR},fi=new Set(["var","literal","call","not",...Object.keys(Vt),...Object.keys(jt)]),di=(e,t,n)=>{if(!Array.isArray(e))throw new w(`Condition JSON operator '${t}' at '${J(n)}' requires an array`);if(e.length!==2)throw new w(`Condition JSON operator '${t}' at '${J(n)}' requires exactly 2 operands`);return e},pi=(e,t,n,r,o)=>{if(!Array.isArray(e))throw new w(`Condition JSON operator '${t}' at '${J(o)}' requires an array`);if(e.length===0)throw new w(`Condition JSON operator '${t}' at '${J(o)}' requires at least 1 condition`);return e.map((s,a)=>ne(s,r,[...o,a])).reduce((s,a)=>({type:p.BINARY,op:n,left:s,right:a}))},hi=(e,t,n)=>{let r,o;if(typeof e.call=="string")r=e.call,o=e.args??[],de(e,new Set(["call","args"]),n);else if(Mt(e.call))r=e.call.name,o=e.call.args??[],de(e,new Set(["call"]),n),de(e.call,new Set(["name","args"]),[...n,"call"]);else throw new w(`Condition JSON call at '${J(n)}' requires a function name`);if(typeof r!="string"||r.trim()==="")throw new w(`Condition JSON call at '${J(n)}' requires a non-empty function name`);if(!/^\w+$/.test(r))throw new w(`Invalid condition JSON function name '${r}' at '${J(n)}'`);if(!Array.isArray(o))throw new w(`Condition JSON call '${r}' at '${J(n)}' requires args to be an array`);return{type:p.FUNCTION,name:r,args:o.map((i,s)=>ne(i,t,[...n,"args",s]))}},ne=(e,t={},n=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:p.LITERAL,value:e};if(Array.isArray(e))throw new w(`Condition JSON array at '${J(n)}' must be wrapped in an operator or { literal: [...] }`);if(!Mt(e))throw new w(`Invalid condition JSON value at '${J(n)}'`);let r=Zn(e);if(r.length===0)throw new w(`Condition JSON object at '${J(n)}' must contain an operator`);let o=r.filter(s=>fi.has(s));if(o.length===0)throw new w(`Unknown condition JSON operator '${r[0]}' at '${J(n)}'`);if(o.length>1)throw new w(`Condition JSON at '${J(n)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(de(e,new Set(["var"]),n),typeof e.var!="string"||e.var.trim()==="")throw new w(`Condition JSON var at '${J(n)}' requires a non-empty path`);return{type:p.VARIABLE,path:e.var}}if(i==="literal")return de(e,new Set(["literal"]),n),{type:p.LITERAL,value:e.literal};if(i==="call")return hi(e,t,n);if(i==="not")return de(e,new Set(["not"]),n),{type:p.UNARY,op:_e.NOT,operand:ne(e.not,t,[...n,"not"])};if(i in jt)return de(e,new Set([i]),n),pi(e[i],i,jt[i],t,[...n,i]);if(i in Vt){de(e,new Set([i]),n);let s=di(e[i],i,[...n,i]);return{type:p.BINARY,op:Vt[i],left:ne(s[0],t,[...n,i,0]),right:ne(s[1],t,[...n,i,1])}}throw new w(`Unknown condition JSON operator '${i}' at '${J(n)}'`)},Xn=(e,t={})=>{if(e==null)throw new w("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new w("Empty condition expression after '$when'");return W(e,t)}return Mt(e)||Array.isArray(e)?ne(e,t):{type:p.LITERAL,value:e}},W=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let c=e.slice(1,-1),u=0,f=!0;for(let d=0;d<c.length;d++)if(c[d]==="("?u++:c[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return W(c,t)}let n=ye(e,"||");if(n!==-1)return{type:p.BINARY,op:R.OR,left:W(e.substring(0,n).trim(),t),right:W(e.substring(n+2).trim(),t)};let r=ye(e,"&&");if(r!==-1)return{type:p.BINARY,op:R.AND,left:W(e.substring(0,r).trim(),t),right:W(e.substring(r+2).trim(),t)};let o=[{op:">=",type:R.GTE},{op:"<=",type:R.LTE},{op:"==",type:R.EQ},{op:"!=",type:R.NEQ},{op:">",type:R.GT},{op:"<",type:R.LT},{op:" in ",type:R.IN}];for(let{op:c,type:u}of o){let f=ye(e,c);if(f!==-1)return{type:p.BINARY,op:u,left:W(e.substring(0,f).trim(),t),right:W(e.substring(f+c.length).trim(),t)}}let i=-1,s=null,a=[{op:" + ",type:R.ADD},{op:" - ",type:R.SUBTRACT}];for(let{op:c,type:u}of a){let f=0;for(;f<e.length;){let d=ye(e.substring(f),c);if(d===-1)break;let h=f+d;h>i&&(i=h,s={op:c,type:u}),f=h+c.length}}if(i!==-1&&s)return{type:p.BINARY,op:s.type,left:W(e.substring(0,i).trim(),t),right:W(e.substring(i+s.op.length).trim(),t)};let l=[" * "," / "," % "];for(let c of l)if(ye(e,c)!==-1)throw new w(`Arithmetic operations are not allowed in conditionals: "${c}"`);return e.startsWith("!")?{type:p.UNARY,op:_e.NOT,operand:W(e.substring(1).trim(),t)}:er(e,t)},ye=(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},gi=e=>{if(e=e.trim(),e==="true")return{type:p.LITERAL,value:!0};if(e==="false")return{type:p.LITERAL,value:!1};if(e==="null")return{type:p.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:p.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:p.LITERAL,value:""};if(e==="{}")return{type:p.LITERAL,value:{}};if(e==="[]")return{type:p.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:p.LITERAL,value:t}:{type:p.VARIABLE,path:e}},er=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return De(n,t);let o=gi(n);if(o.type===p.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:p.VARIABLE,path:n};try{return De(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},mi=(e,t=!1)=>{let n=t?"$each":"$for";try{Un(e)}catch(r){if(r instanceof w&&t){let o=r.message.replace(/\$for/g,"$each");throw new w(o.replace("Parse Error: ",""))}throw r}},Qn=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let I=r?"$each":"$for";throw new w(`Invalid loop syntax (got: '${e.replace("$for",I)}')`)}let s=i[1],a=i[2].trim();mi(a,r);let l=a.match(/^(.+?)\s+in\s+(.+)$/);if(!l){let I=r?"$each":"$for";throw new w(`Invalid loop syntax - missing 'in' keyword (got: '${I} ${a}')`)}let c=l[1].trim(),u=l[2].trim(),f,d=null;if(c.includes(",")){let I=c.split(",").map(b=>b.trim());if(I.length!==2)throw new w(`Invalid loop variables: ${c}. Expected format: "item" or "item, index"`);f=I[0],d=I[1]}else f=c;let h=["this","undefined","null","true","false"];if(h.includes(f))throw new w(`Reserved variable name: ${f}`);if(d&&h.includes(d))throw new w(`Reserved variable name: ${d}`);let g=er(u,n),y=pe(t,n);return{type:p.LOOP,itemVar:f,indexVar:d,iterable:g,body:y,flatten:s!=="nested"}};var yi=(e,t={})=>{let{functions:n={}}=t;return pe(e,n)},rt=yi;var Ve={};Lo(Ve,{now:()=>bi});var bi=()=>Date.now();var Ii=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...Ve,...r},s=rt(e,{functions:i}),a={};for(let[l,c]of Object.entries(o))a[l]=rt(c,{functions:i});return Nt(s,t,{functions:i,partials:a})},Z=Ii;var Ai=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",wi=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,xi=(e,t)=>{if(Ai(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new w("Empty condition expression");return W(e,t)}return ne(e,t)},Ei=(e,t={},n={})=>{let r=wi(n),o={...Ve,...r},i=xi(e,o);return!!fe(i,{functions:o,partials:{}},t,{})},je=Ei;var tr=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=l=>l,transformActionFirstArgument:a=l=>l}=n;for(let[l,c]of Object.entries(t))l!=="createInitialState"&&(l.startsWith("select")?o[l]=(...u)=>c(s(r),...u):i[l]=(...u)=>{r=Pt(r,d=>c(a(d),...u))});return{...o,...i}},ot=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return Pt(r,i=>{o.forEach(s=>{t.forEach(a=>{a(i,s)})})})};var vi=(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{}}},Ft=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{let i=vi(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(", ")}`)},Wt=(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(", ")}`)},Yt=(e,t,n)=>{switch(t){case"set":return n;case"multiply":return(e??1)*n;case"divide":return(e??0)/n;case"increment":return(e??0)+(n??1);case"decrement":return(e??0)-(n??1);case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var nr=(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()))},Si=(e,t)=>{let n=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let a=i.character?.sprite;return a&&Object.keys(a).length>0&&(s.sprite=a),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},qt=(e={},t={})=>{let n={},r=["sfx","voice"],o=s=>{let a=e[s],l=t[s];l&&!a?n[s]={changeType:"add",data:l}:a&&!l?r.includes(s)||(n[s]={changeType:"delete",data:a}):a&&l&&JSON.stringify(a)!==JSON.stringify(l)&&(n[s]={changeType:"update",data:l})};o("background"),o("bgm"),o("voice");let i=Si(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},Ht=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,t.background.resourceId||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"),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(a=>{let l={...a};return delete l.animations,i(l)?l: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},Ci=(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},_i=(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=Ci(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},Ri={conditional:new Set(["branches"]),updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"])},rr=(e,t)=>{let n=e[e.length-1];return n?Ri[n]?.has(t)===!0:!1},Ut=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Ut(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,rr(n,r)?o:Ut(o,t,[...n,r])])):_i(e,t),Bt=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Bt(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,rr(n,r)?o:Bt(o,t,[...n,r])])):typeof e=="string"?Z(e,t):e,Jt=(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=Ut(e,t._event);return Bt(n,t)};var it=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:structuredClone(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},sr=(e,t)=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let n=e.map(r=>structuredClone(r)).filter(r=>t(r)||r.animations);return{hasValidItems:n.length>0,processedItems:n}},Re=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),or=e=>e?.animations?.playback?.continuity==="persistent",Li=e=>{if(e){if(e.character&&Re(e.character,"name"))return e.character.name;if(Re(e,"characterName"))return e.characterName}},ar=e=>!!e?.character&&Re(e.character,"sprite"),$i=e=>{let t={},n=!1,r=Li(e);return r!==void 0&&(t.name=r,n=!0),ar(e)&&(t.sprite=structuredClone(e.character.sprite),n=!0),n?t:void 0},ir=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Oi=()=>({}),ki=(e,t)=>{if(t.background){let{animationsOnly:n,state:r}=it(t.background,s=>!!s.resourceId);if(n){e.background=e.background?.resourceId?{...structuredClone(e.background),...r}:r;return}if(!t.background.resourceId){delete e.background;return}let o=structuredClone(t.background),i=e.background;i?.resourceId===o.resourceId&&i?.transformId===o.transformId&&!Re(o,"animations")&&or(i)&&(o.animations=structuredClone(i.animations)),e.background=o}else e.background?.animations&&!or(e.background)&&(e.background.animations={})},Pi=(e,t)=>{if(!t.dialogue){e.dialogue&&(ir(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}if(e.dialogue||(e.dialogue={}),t.dialogue.ui){let{animationsOnly:a,state:l}=it(t.dialogue.ui,c=>!!c.resourceId);a?e.dialogue.ui={...e.dialogue.ui,...l}: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"),t.dialogue.content!==void 0&&(e.dialogue.content=t.dialogue.content);let n=Re(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;n?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let r=Re(t.dialogue,"characterId"),o=$i(t.dialogue),i=o!==void 0,s=ar(t.dialogue);if(r?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:n||delete e.dialogue.characterId,i?e.dialogue.character=!r&&n&&e.dialogue.character?{...structuredClone(e.dialogue.character),...o}:o:(r||!n)&&delete e.dialogue.character,s||ir(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 a={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(a.character=structuredClone(e.dialogue.character)),e.dialogue.lines.push(a)}},Ti=(e,t)=>{if(t.sfx){if(!t.sfx.items||t.sfx.items.length===0){delete e.sfx;return}e.sfx=t.sfx}else e.sfx&&delete e.sfx},Ni=(e,t)=>{if(t.bgm){if(!t.bgm.resourceId){e.bgm=void 0;return}e.bgm={...t.bgm,loop:t.bgm.loop||t.bgm.loop===void 0}}},Di=(e,t)=>{if(t.visual){let{hasValidItems:n,processedItems:r}=sr(t.visual.items,o=>!!o.resourceId);n?e.visual={items:r}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},Vi=(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}=sr(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);n?e.character={items:r}:delete e.character},ji=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Mi=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=it(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},Ui=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=it(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},Bi=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},Fi=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},zi=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},Le=e=>ot(Oi,[zi,ki,Ti,Ni,Di,Pi,Vi,ji,Mi,Ui,Bi,Fi])(e);var be={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:nr},Wi=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,Yi=(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},ct=(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),a=Wi.exec(s);if(a){let[,l,c,u]=a,f=Yi(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((h,g)=>{let y={...t,[l]:h};c&&(y[c]=g),d.forEach(I=>{let b=ct(I,y,n),m=Z(b,y,n);Array.isArray(m)?o.push(...m):o.push(m)})});continue}}o.push(ct(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=ct(i,t,n)}),r},sn=({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".`)},qi=({id:e,targetId:t,animation:n,playback:r,animationPath:o="animation"})=>{let i=structuredClone(n);return sn({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,r&&(i.playback=structuredClone(r)),i},Hi=(e,{animationId:t="animation",animationPath:n="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return sn({animationType:e.type,animationId:t,animationPath:n}),e.type},Ji=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Ki=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Gi=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ar=e=>e?.playback?.continuity==="persistent",en=e=>Array.isArray(e)?e.map(en):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,n)=>(t[n]=en(e[n]),t),{}),lt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify(en(t))},wr=(e=[])=>e.filter(t=>Ar(t)).map(t=>structuredClone(t)),xr=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,Kt=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,n)=>Math.max(t,xr(n)),0),Er=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(Kt(e.tween),Kt(e.prev?.tween),Kt(e.next?.tween),xr(e.mask?.progress)),cr=({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(lt).filter(Boolean));return e.some(r=>{if(!Ar(r))return!1;let o=lt(r);return o?n.has(o):!1})},se=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:n,activePersistentAnimations:r,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||n?!1:i&&!t||cr({animationInstances:e,activePersistentAnimations:r})?!0:i?!1:cr({animationInstances:e,activePersistentAnimations:o}),Xi=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Qi=(e,t)=>{if(Xi(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},Zi=({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?qi({id:r,targetId:o,animation:s,playback:n,animationPath:i}):null},es=({hasPrevious:e,hasCurrent:t,previousResourceId:n,currentResourceId:r,sharedTarget:o})=>!e&&t?"enter":e&&!t?"exit":e&&t?n===r&&o?"update":"replace":"none",ts=({animationType:e,animationId:t,animationPath:n,lifecycle:r})=>{if(!(e!=="update"||r==="update"))throw new Error(`[${n}] Animation "${t}" has type "update", but update animations can only be used when the same target persists across the state change. Use type "transition" for enter, exit, and replace.`)},ns=(e,{defaultTargetId:t,defaultId:n,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return sn({animationType:o.type,animationId:o.id??n,animationPath:r}),o.id??=n,o.targetId??=t,o},an=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r,animationPathPrefix:o=r})=>{t.forEach((i,s)=>{e.push(ns(i,{defaultTargetId:n,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},lr=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=Z(e,t);return n&&typeof n=="object"?e:n},ur=(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},fr=(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))},st=(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("-")}`},Gt=(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},rs=(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},dr=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},at=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},os=(e={})=>e.textStyles||{},is=(e={})=>e.images||{},ss=(e={})=>e.colors||{},as=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Me=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,Oe=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},pr=(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},vr=(e,t)=>{if(typeof e!="string"||!as.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},hr=(e,t,n)=>{let r=vr(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})`},cs=(e={},t)=>{let n=os(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=pr(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:hr(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 a=e.colors?.[n.strokeColorId];if(!a)throw new Error(`Stroke color "${n.strokeColorId}" not found for text style "${t}"`);let l=pr(n.strokeAlpha,"strokeAlpha",t);s.strokeColor=hr(a.hex,l,`Stroke color "${n.strokeColorId}" for text style "${t}"`)}else if(n.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return n.strokeWidth!==void 0&&(s.strokeWidth=n.strokeWidth),s},tn=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>tn(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]=tn(i,t,Me(n,o)));return e.textStyleId!==void 0&&(Oe(e.textStyleId,n,"textStyleId"),r.textStyle=cs(t,e.textStyleId)),r},Sr=(e={},t)=>{let n=ss(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return vr(n.hex,`Color "${t}"`)},Cr=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Xt=(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 ${Cr(`${t}.fill`)} instead`)},ls=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Ue(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]=Ue(i,t,Me(n,o)));return e.colorId!==void 0&&(Oe(e.colorId,n,"colorId"),r.fill=Sr(t,e.colorId)),r},Ue=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Ue(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 ${Cr("fill")} instead`);Xt(e,"hover",n),Xt(e,"click",n),Xt(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]=ls(i,t,Me(n,o));continue}r[o]=Ue(i,t,Me(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(Oe(e.colorId,n,"colorId"),r.fill=Sr(t,e.colorId)),r},Qt=(e={},t)=>{let n=is(e)?.[t];return n||null},_r=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",gr=(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 ${_r(`${t}.${r}`)} instead`)},mr=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},nn=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>nn(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 ${_r(o)} instead`);gr(e,"hover",n,"src"),gr(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]=nn(i,t,Me(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){Oe(e.imageId,n,"imageId");let o=Qt(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&&(Oe(e.hoverImageId,n,"hoverImageId"),mr(r,"hover",Qt(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(Oe(e.clickImageId,n,"clickImageId"),mr(r,"click",Qt(t,e.clickImageId)?.fileId??e.clickImageId)),r},cn=(e,t={},n="root")=>nn(Ue(tn(e,t,n),t,n),t,n),Ie=cn,Be=(e=[])=>e.find(t=>t.id==="story");var us=(e={})=>e?.muteAll?0:e?.musicVolume??50,re=({variables:e,runtime:t,saveSlots:n=[],dialogueState:r,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,confirmDialog:u,historyDialogue:f=[],characters:d={},dialogueUIHidden:h,skipOnlyViewedLines:g,skipTransitionsAndAnimations:y}={})=>{let I={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,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??a??!1,dialogueUIHidden:t?.dialogueUIHidden??h??!1,isLineCompleted:t?.isLineCompleted??i??!1},b=hs({dialogueState:r,includeInactiveAdvDialogue:o,characters:d,variables:e}),m={variables:e,runtime:I,saveSlots:n,isChoiceVisible:l,canRollback:c,confirmDialog:u,historyDialogue:f,characters:d};return b&&(m.dialogue=b,m.dialogueLines=b.lines),m},yr=100,ut=(e,t)=>{if(Array.isArray(e))return e.map(r=>ut(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=ut(n[r],t)}),n.type==="text-revealing"?t(n):n},fs=e=>ut(e,t=>({...t,revealEffect:"none"})),ds=e=>ut(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,yr):yr;return{...t,speed:r,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:r}:{}}}),Ae=(e,{isLineCompleted:t=!1,skipMode:n=!1,skipTransitionsAndAnimations:r=!1}={})=>t||r?fs(e):n?ds(e):e,Rr=({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:{}}}}),rn=e=>{if(Array.isArray(e))return e.map(rn);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=rn(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,_interactionSource:"choice"}:void 0;return{...t,click:{...t.click,payload:{...n,_interactionSource:"choice",...o?{actions:{...r,nextLine:o}}:{}}}}},on=({characterId:e,character:t,characterName:n,characters:r={}}={})=>{let o=e?r?.[e]:void 0,i=t?.name!==void 0?t.name:n!==void 0?n:o?.name||"";return{...o||{},...t||{},name:i}},Lr=(e=[],t={})=>e.map(n=>{let r=on({characterId:n.characterId,character:n.character,characterName:n.characterName,characters:t}),o=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(i=>i?.text??"").join(""):"";return{...n,text:o,character:r,characterName:r.name}}),ps=e=>!(!e||e.mode==="adv"&&e.content===void 0),hs=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:n={},variables:r}={})=>{if(!t&&!ps(e))return;let o=e.content===void 0?[{text:""}]:ur(e.content,"dialogue.content"),i=(e.lines||[]).map((a,l)=>{let c=ur(a.content,`dialogue.lines[${l}].content`),u=on({characterId:a.characterId,character:a.character,characterName:a.characterName,characters:n});return{...a,content:c.map(f=>({...f,text:lr(f.text,{variables:r})})),character:u,characterName:u.name}}),s=on({characterId:e.characterId,character:e.character,characters:n});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:s,content:o.map(a=>({...a,text:lr(a.text,{variables:r})})),lines:i}},$r=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=Z(e,n,{functions:be});return Ie(Ae(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},Zt=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),br=({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:Zt(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[r].keyup={payload:Zt(o.keyup)});return}e[r]={...i,[n]:{payload:Zt(o)}}})},gs=(e={},t={})=>{let n={};return br({renderStateKeyboard:n,keyboard:e,phase:"keydown"}),br({renderStateKeyboard:n,keyboard:t,phase:"keyup"}),Object.keys(n).length>0?n:void 0},we=({animationsDef:e,resources:t,previousResourceId:n,currentResourceId:r,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:a,allowIncomingUpdateFallback:l=!1})=>{if(!e)return[];let c=[],u=({instanceId:S,targetId:$})=>{let O=Zi({resources:t,animationId:y,playback:I,instanceId:S,targetId:$,animationPath:s});O&&c.push(O)},f=n!=null&&n!==!1,d=r!=null&&r!==!1,h=o&&i&&o===i,g=es({hasPrevious:f,hasCurrent:d,previousResourceId:n,currentResourceId:r,sharedTarget:h});Qi(e,s);let y=Ji(e),I=Ki(e),b=t?.animations?.[y],m=Hi(b,{animationId:y,animationPath:s}),E=l&&m==="update"&&g!=="update"&&d&&i;if(E||ts({animationType:m,animationId:y,animationPath:s,lifecycle:g}),m==="update")return f&&d&&n===r&&h?u({instanceId:`${a}-animation-update`,targetId:i}):E&&u({instanceId:`${a}-animation-update`,targetId:i}),c;if(m==="transition"){let S=`${a}-animation-transition`,$=I?.continuity==="persistent"?S:`${a}-animation-in`;if(f&&d&&h)return u({instanceId:S,targetId:i}),c;f&&u({instanceId:`${a}-animation-out`,targetId:o}),d&&u({instanceId:$,targetId:i})}return c},ms=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),ys=(e,{presentationState:t,previousPresentationState:n,currentLineActions:r,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:a,variables:l,runtime:c,activePersistentAnimations:u,restoredPersistentAnimations:f,autoMode:d,skipMode:h,isChoiceVisible:g,canRollback:y,saveSlots:I=[]})=>{let{elements:b,animations:m}=e;if(t.background){let E=r===void 0?!0:Gi(r?.background??{},"animations"),S=b.find(P=>P.id==="story");if(!S)return e;let $=rs(o,t.background),O=n?.background?.resourceId,_=t.background.resourceId??(t.background.animations?O:void 0),D=dr(o,O),N=dr(o,_);if(_){let{images:P={},videos:x={}}=o,C=P[_]||x[_];if(C){let M=x[_]!==void 0,z={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...$},Y={id:at({resourceId:_,kind:M?"video":"sprite"}),type:M?"video":"sprite",x:z.x,y:z.y,src:C.fileId,width:C.width,height:C.height,alpha:1,anchorX:z.anchorX,anchorY:z.anchorY,rotation:z.rotation,scaleX:z.scaleX,scaleY:z.scaleY};M&&(Y.loop=t.background.loop??!1,Y.volume=C.volume??50),S.children.push(Y)}}if(_){let{layouts:P={}}=o,x=P[_];if(x){let C={id:at({resourceId:_,kind:"container"}),type:"container",children:x.elements};$&&Object.assign(C,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...$});let M=Z(C,re({variables:l,runtime:c,saveSlots:I,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:h,isChoiceVisible:g,canRollback:y,characters:o.characters||{},skipTransitionsAndAnimations:a}),{functions:be});S.children.push(Ie(Ae(M,{isLineCompleted:s,skipMode:h,skipTransitionsAndAnimations:a}),o))}}let k=we({animationsDef:t.background.animations,resources:o,previousResourceId:O,currentResourceId:_,previousTargetId:at({resourceId:O,kind:D}),currentTargetId:at({resourceId:_,kind:N}),animationPath:"background.animations",idPrefix:"bg-cg",allowIncomingUpdateFallback:!0});se({animationInstances:k,isLineCompleted:s,skipTransitionsAndAnimations:a,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:E})&&m.push(...k)}return e},bs=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:a,animations:l}=e;if(t.character&&r){let c=a.find(g=>g.id==="story");if(!c)return e;let u=t.character.items||[],f=n?.character?.items||[],d=fr(u),h=fr(f);for(let g=0;g<u.length;g++){let y=u[g],{transformId:I,sprites:b}=y,m=f.find(P=>P.id===y.id),E=f.findIndex(P=>P.id===y.id),S=m?.sprites&&m.sprites.length>0,$=b&&b.length>0,O=E>=0?st(m,E,h):void 0,_=we({animationsDef:y.animations,resources:r,previousResourceId:O,currentResourceId:$?st(y,g,d):void 0,previousTargetId:O,currentTargetId:$?st(y,g,d):void 0,animationPath:`character.items[${g}].animations`,idPrefix:"character"});if(y.animations&&!b&&!I&&S&&se({animationInstances:_,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){l.push(..._);continue}if(y.animations&&!b&&!I)continue;if(!b||b.length===0||!I){console.warn("Character item missing sprites or transformId:",y);continue}let D=st(y,g,d),N=r.transforms[I];if(!N){console.warn("Transform not found:",I);continue}let k={type:"container",id:D,x:y.x??N.x,y:y.y??N.y,anchorX:N.anchorX,anchorY:N.anchorY,rotation:N.rotation,scaleX:N.scaleX,scaleY:N.scaleY,children:[]};for(let P of b){let x=r.images[P.resourceId];if(!x){console.warn(`Image resource not found: ${P.resourceId}`);continue}k.children.push({type:"sprite",id:`${D}-${P.id}`,src:x.fileId,width:x.width,height:x.height,x:0,y:0})}c.children.push(k),se({animationInstances:_,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(..._)}}return e},Is=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:a,activePersistentAnimations:l,autoMode:c,skipMode:u,isChoiceVisible:f,canRollback:d,saveSlots:h=[]})=>{let{elements:g,animations:y}=e;if(t.visual&&r){let I=g.find(m=>m.id==="story");if(!I)return e;let b=t.visual.items;for(let m of b){if(m.resourceId){let{images:O={},videos:_={},spritesheets:D={}}=r,N=D[m.resourceId];if(N){let k=Gt(r,m),P=m.animationName;if(P){let x=N.animations?.[P];if(!x)throw new Error(`Animation '${P}' not found in spritesheet resource '${m.resourceId}'`);let C={id:`visual-${m.id}`,type:"animated-sprite",x:m.x??k.x,y:m.y??k.y,width:m.width??N.width,height:m.height??N.height,alpha:m.alpha??1,anchorX:k.anchorX,anchorY:k.anchorY,rotation:k.rotation,scaleX:k.scaleX,scaleY:k.scaleY,spritesheetSrc:N.fileId,spritesheetData:N.jsonData,animation:{frames:x.frames,animationSpeed:m.animationSpeed??x.animationSpeed??.5,loop:m.loop??x.loop??!0}};I.children.push(structuredClone(C))}}else{let k=O[m.resourceId]||_[m.resourceId];if(k){let P=_[m.resourceId]!==void 0,x=Gt(r,m),C={id:`visual-${m.id}`,type:P?"video":"sprite",src:k.fileId,width:k.width,height:k.height,x:x.x,y:x.y,anchorX:x.anchorX,anchorY:x.anchorY,rotation:x.rotation,scaleX:x.scaleX,scaleY:x.scaleY};P&&(C.loop=k.loop??!1,C.volume=k.volume??50),I.children.push(C)}}}if(m.resourceId){let{layouts:O={}}=r,_=O[m.resourceId];if(_){let D=Gt(r,m),N={id:`visual-${m.id}`,type:"container",children:structuredClone(_.elements),x:D.x,y:D.y,anchorX:D.anchorX,anchorY:D.anchorY,rotation:D.rotation,scaleX:D.scaleX,scaleY:D.scaleY},k=Z(N,re({variables:s,runtime:a,saveSlots:h,dialogueState:t.dialogue,isLineCompleted:o,autoMode:c,skipMode:u,isChoiceVisible:f,canRollback:d,characters:r.characters||{},skipTransitionsAndAnimations:i}),{functions:be});I.children.push(Ie(Ae(k,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),r))}}let S=(n?.visual?.items||[]).find(O=>O.id===m.id),$=we({animationsDef:m.animations,resources:r,previousResourceId:S?.resourceId,currentResourceId:m.resourceId,previousTargetId:S?.resourceId?`visual-${m.id}`:void 0,currentTargetId:m.resourceId?`visual-${m.id}`:void 0,animationPath:`visual.items[${m.id}].animations`,idPrefix:m.id});se({animationInstances:$,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:l})&&y.push(...$)}}return e},$e="dialogue-character-sprite",Ir=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,As=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:a}=e,l=Be(e.elements);if(!l)return e;let c=t.dialogue?.character?.sprite,u=n?.dialogue?.character?.sprite,f=Ir(c),d=Ir(u),h=we({animationsDef:c?.animations,resources:r,previousResourceId:d?$e:void 0,currentResourceId:f?$e:void 0,previousTargetId:d?$e:void 0,currentTargetId:f?$e:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!f)return c?.animations&&d&&se({animationInstances:h,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...h),e;let g=r.transforms?.[c.transformId];if(!g)return console.warn("Transform not found:",c.transformId),e;let y={type:"container",id:$e,x:g.x,y:g.y,anchorX:g.anchorX,anchorY:g.anchorY,rotation:g.rotation,scaleX:g.scaleX,scaleY:g.scaleY,children:[]};for(let I of c.items){let b=r.images?.[I.resourceId];if(!b){console.warn(`Image resource not found: ${I.resourceId}`);continue}y.children.push({type:"sprite",id:`${$e}-${I.id}`,src:b.fileId,width:b.width,height:b.height,x:0,y:0})}return l.children.push(y),se({animationInstances:h,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...h),e},ws=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,skipOnlyViewedLines:c,isLineCompleted:u,skipTransitionsAndAnimations:f,variables:d,runtime:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:I,animations:b}=e;if(!t.dialogue||o)return e;let m=I.find(S=>S.id==="story");if(!m)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:S={}}=r,$=S[t.dialogue.ui.resourceId];if($){let O={elements:$.elements},_=re({variables:d,runtime:h,saveSlots:y,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:u,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,characters:r.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:c,skipTransitionsAndAnimations:f}),D={functions:be},N=ct(O,_,D),k=Z(N,_,D),P=Ie(Ae(k?.elements,{isLineCompleted:u,skipMode:s,skipTransitionsAndAnimations:f}),r);if(Array.isArray(P))for(let x of P)m.children.push(x);else P&&m.children.push(P)}}As(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:u,skipTransitionsAndAnimations:f,activePersistentAnimations:g});let E=we({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 se({animationInstances:E,isLineCompleted:u,skipTransitionsAndAnimations:f,activePersistentAnimations:g})&&b.push(...E),e},xs=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,runtime:l,autoMode:c,skipMode:u,isChoiceVisible:f,canRollback:d,activePersistentAnimations:h,saveSlots:g=[]})=>{let{elements:y,animations:I}=e;if(t.choice&&r){let b=Be(y);if(!b)return e;let m=r?.layouts[t.choice.resourceId];if(m&&m.elements){let S={elements:m.elements},$=Z(S,{...re({variables:a,runtime:l,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:c,skipMode:u,isChoiceVisible:f??!!t.choice,canRollback:d,characters:r.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:be}),O=rn(Ie(Ae($?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r));if(Array.isArray(O))for(let _ of O)b.children.push(_);else O&&b.children.push(O)}let E=we({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"});se({animationInstances:E,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&I.push(...E)}return e},Es=(e,{presentationState:t,resources:n={},variables:r,runtime:o,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,saveSlots:u=[],skipTransitionsAndAnimations:f})=>{if(!t.control?.resourceId)return e;let d=n.controls?.[t.control.resourceId];if(!d)return e;let h=gs(d.keyboard,d.keyup);if(h&&Object.keys(h).length>0&&(e.global.keyboard=h),!Array.isArray(d.elements)||d.elements.length===0)return e;let g=Be(e.elements);if(!g)return e;let y={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:d.elements};return g.children.push($r({container:y,resources:n,templateData:re({variables:r,runtime:o,saveSlots:u,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,characters:n.characters||{},skipTransitionsAndAnimations:f}),isLineCompleted:i,skipMode:a,skipTransitionsAndAnimations:f})),e},vs=(e,{presentationState:t,resources:n,runtime:r,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&n){if(!Be(i))return e;let l=n.sounds[t.bgm.resourceId];if(!l)return e;let c=re({variables:o,runtime:r}).runtime;s.push({id:"bgm",type:"sound",src:l.fileId,loop:t.bgm.loop??!0,volume:us(c),delay:t.bgm.delay??null})}return e},Ss=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(t.sfx&&n){let o=t.sfx.items;for(let i of o){let s=n.sounds?.[i.resourceId];s&&r.push({id:i.id,type:"sound",src:s.fileId,loop:i.loop??s.loop??!1,volume:i.volume??s.volume??50,delay:i.delay??s.delay??null})}}return e},Cs=(e,t,n)=>{if(!(!t||!n))return e?.voices?.[t]?.[n]},_s=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,Rs=(e,{presentationState:t,resources:n,currentSceneId:r,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let a=t.voice,{resourceId:l,loop:c,delay:u}=a,f=Cs(n,r,l);if(!f)return e;let d=re({variables:i,runtime:o}).runtime;return s.push({id:`voice-${r}-${l}`,type:"sound",src:f.fileId,volume:_s(a,d),loop:c??!1,delay:u??null}),e},Ls=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,runtime:i,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,saveSlots:u=[],isLineCompleted:f,skipTransitionsAndAnimations:d,activePersistentAnimations:h})=>{let{elements:g,animations:y}=e;if(t.layout){let E=Be(g);if(!E)return e;let S=r.layouts[t.layout.resourceId];if(!S)return e;Array.isArray(S.transitions)&&!f&&!d&&an({animations:y,transitions:S.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let $={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:S.elements||[]};E.children.push($r({container:$,resources:r,templateData:re({variables:o,runtime:i,saveSlots:u,dialogueState:t.dialogue,isLineCompleted:f,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,characters:r.characters||{},skipTransitionsAndAnimations:d}),isLineCompleted:f,skipMode:a,skipTransitionsAndAnimations:d}))}let I=n?.layout?.resourceId,b=t.layout?.resourceId,m=we({animationsDef:t.layout?.animations,resources:r,previousResourceId:I,currentResourceId:b,previousTargetId:I?`layout-${I}`:void 0,currentTargetId:b?`layout-${b}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return se({animationInstances:m,isLineCompleted:f,skipTransitionsAndAnimations:d,activePersistentAnimations:h})&&y.push(...m),e},$s=(e,{presentationState:t,resources:n={},variables:r,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,overlayStack:c=[],dialogueHistory:u=[],saveSlots:f=[],screen:d,isLineCompleted:h,skipTransitionsAndAnimations:g})=>{let{elements:y,animations:I}=e;return c&&c.length>0&&c.forEach((b,m)=>{let E=n.layouts[b.resourceId];if(!E){console.warn(`Overlay layout not found: ${b.resourceId}`);return}Array.isArray(E.transitions)&&(g||an({animations:I,transitions:E.transitions,defaultTargetId:`overlayStack-${m}`,idPrefix:`overlayStack-${m}`,animationPathPrefix:`overlayStack[${m}]`}));let S={id:`overlayStack-${m}`,type:"container",x:0,y:0,children:[Rr({id:`overlayStack-${m}-blocker`,screen:d}),...E.elements||[]]},$=Lr(u,n.characters),O=re({variables:r,runtime:o,saveSlots:f,dialogueState:t?.dialogue,isLineCompleted:h,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,historyDialogue:$,characters:n.characters||{},skipTransitionsAndAnimations:g}),_=Z(S,O,{functions:be}),[D,...N]=_.children||[],k=Ie(Ae({..._,children:N},{isLineCompleted:h,skipMode:s,skipTransitionsAndAnimations:g}),n);y.push({...k,children:D?[D,...k.children||[]]:k.children})}),e},Os=(e,{presentationState:t,resources:n={},variables:r,runtime:o,saveSlots:i=[],autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,confirmDialog:u,dialogueHistory:f=[],screen:d,isLineCompleted:h,skipTransitionsAndAnimations:g})=>{let{elements:y,animations:I}=e;if(!u?.resourceId)return e;let b=n.layouts?.[u.resourceId];if(!b)return console.warn(`ConfirmDialog layout not found: ${u.resourceId}`),e;Array.isArray(b.transitions)&&!g&&an({animations:I,transitions:b.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let m={id:"confirmDialog",type:"container",x:0,y:0,children:[Rr({id:"confirmDialog-blocker",screen:d}),...b.elements||[]]},E=Lr(f,n.characters),S=Z(m,re({variables:r,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:h,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,confirmDialog:u,historyDialogue:E,characters:n.characters||{},skipTransitionsAndAnimations:g}),{functions:be}),[$,...O]=S.children||[],_=Ie(Ae({...S,children:O},{isLineCompleted:h,skipMode:a,skipTransitionsAndAnimations:g}),n);return y.push({..._,children:$?[$,..._.children||[]]:_.children}),e},Or=e=>ot(ms,[Es,ys,bs,Is,ws,xs,Ls,vs,Ss,Rs,$s,Os])(e);var ks=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},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"}}),ft=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),Fe=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),kr=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"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"}),ln=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),un=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Ps=(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]}},dt=e=>Object.fromEntries(Object.entries(ks).map(([t,n])=>{let r=Ps(e,n.source),o=r!==void 0?r:ft[t]??Fe[t];return[t,o]})),ae=(e,t)=>dt(e)[t],Pr=(e={})=>Object.fromEntries(ln.map(t=>[t,e[t]??ft[t]]));var pt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},jr=1,gt=()=>({manual:{...pt.manual},auto:{...pt.auto},applyMode:pt.applyMode}),fn=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...gt()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},F=e=>{let t=ue(e)?kt(e):e;return structuredClone(t)},j=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),mt=e=>String(e),Mr=()=>({sections:[],resources:[]}),Ts=e=>j(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Mr(),Ns=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Ds=()=>({resourceId:void 0}),Vs=e=>{if(!j(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},dn=(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}},Ur=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 a=n.get(s);if(a!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${a}" and "${r}". Section IDs must be globally unique.`);n.set(s,r)}}},Br=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Fr=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==jr)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},js=(e,t={})=>{let n;try{n=Fr(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:Br(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},Ms=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,js(t,n)])),zr=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:n})=>gc(n));return t.length>0?t:void 0},Us=e=>{!j(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!j(t))return;let n=zr(t.executedActions);if(n){t.executedActions=n;return}delete t.executedActions})},Tr=(e,t,n,r="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!j(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}},Bs=(e,t="viewedRegistry")=>{if(e===void 0)return Mr();if(!j(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=Tr(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Tr(o,"resources",i,t);return[s.resourceId,s]})))}},Wr=(e,t,n)=>{if(!j(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}=dn(t,r);if(!s)throw new Error(`Malformed save slot ${n}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(l=>l.id===o))throw new Error(`Malformed save slot ${n}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},Fs=(e,t,n)=>{if(!j(e)||!Array.isArray(e.timeline))return ze({pointer:t,replayStartIndex:1});let r=e.timeline.flatMap((a,l)=>{if(!j(a))return[];try{let c=Wr(a,n,`rollback.timeline[${l}]`),u=ht({sectionId:c.sectionId,lineId:c.lineId,rollbackPolicy:a.rollbackPolicy}),f=zr(F(a.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(r.length===0)return ze({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):r.length-1;(o<0||o>=r.length)&&(o=r.length-1);let i=r[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let a=r.findLastIndex(l=>l.sectionId===t.sectionId&&l.lineId===t.lineId);a>=0?o=a:(r.push(ht({sectionId:t.sectionId,lineId:t.lineId})),o=r.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:r}},zs=(e,t,n)=>{if(!j(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=hn(t),o=Wr(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!j(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);if(e.runtime!==void 0&&!j(e.runtime))throw new Error(`Malformed save slot contexts[${n}].runtime entry.`);let i=e.variables?F(e.variables):{},s=Js({loadedContextRuntime:j(e.runtime)?F(e.runtime):{}}),a={currentPointerMode:"read",pointers:{read:o},configuration:j(e.configuration)?F(e.configuration):{},views:Array.isArray(e.views)?F(e.views):[],bgm:j(e.bgm)?F(e.bgm):{resourceId:void 0},variables:{...r,...i},rollback:Fs(e.rollback,o,t)};return s&&(a.runtime=s),a},Ws=(e,t)=>{if(!j(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)=>zs(n,t,r))}},Ys=(e,t)=>{if(!j(e))throw new Error("Malformed save slot.");let n=Fr(e.formatVersion);return{...e,formatVersion:n,state:Ws(e.state,t)}},Nr=(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=F(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},qs=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Nr(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Nr(e.cancelActions,"cancelActions")}},ke=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},xe=[],Dr="line",pn="interaction",ht=({sectionId:e,lineId:t,rollbackPolicy:n})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free"}),hn=e=>{let{contextVariableDefaultValues:t}=Ft(e??{});return F(t)},Yr=()=>({...F(Fe)}),qr=({loadedRuntime:e,runtimeIds:t,defaults:n={},path:r})=>{if(e===void 0)return{runtimeState:F(n),hasLoadedValues:!1};if(!j(e))throw new Error(`Malformed ${r}.`);let o=F(n),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Hr(s,F(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Hs=({loadedGlobalRuntime:e={}})=>qr({loadedRuntime:e,runtimeIds:ln,defaults:ft,path:"global.runtime"}).runtimeState,Js=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:n}=qr({loadedRuntime:e,runtimeIds:un,defaults:Yr(),path:"context.runtime"});return n?t:void 0},gn=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Ks=e=>e.runtime?(un.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=F(Fe[t]))}),e.runtime):(e.runtime=Yr(),e.runtime),Gs=e=>Pr(e.global),Xs=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Gs(e)}})},Qs=e=>kr[e],Zs=(e,t)=>{let n=Qs(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}"`)},Hr=(e,t)=>(Zs(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),Jr=(e,t,n)=>{let r=Hr(t,n);if(t in Fe){let o=gn(e);if(!o)return r;let i=Ks(o);return i[t]=r,r}return e.global[t]=r,r},Kr=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:F(e)},configuration:{},views:[],bgm:Ds(),variables:hn(t),rollback:ze({pointer:e})}),Pe=e=>e?(e.currentPointerMode="read",j(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,ea=e=>{let t=e.contexts?.[e.contexts.length-1],n=t?.pointers?.read;if(!t||!n?.sectionId||!n?.lineId)return null;let r=Kr({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=r,ta(e),r},ta=e=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,ke(e),e.global.nextLineConfig=gt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})},Gr=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},ze=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[ht({sectionId:e.sectionId,lineId:e.lineId})]:[]}},ve=(e,t={})=>{if(e?.rollback)return Gr(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=ze({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},mn=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=ve(n);if(r.isRestoring)return;r.currentIndex<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,r.currentIndex+1));let o=r.timeline[r.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){r.currentIndex=r.timeline.length-1;return}r.timeline.push(ht(t)),r.currentIndex=r.timeline.length-1},na=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=xe[xe.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)},ra=({state:e},t={})=>{let n=t?.source===Dr?Dr:pn,o=e.contexts?.[e.contexts.length-1]?.rollback;return!o||o.isRestoring||!Array.isArray(o.timeline)||typeof o.currentIndex!="number"||o.currentIndex<0||o.currentIndex>=o.timeline.length?(xe.push({checkpointIndex:null,source:n}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),xe.push({checkpointIndex:o.currentIndex,source:n}),e)},oa=({state:e})=>(xe.pop(),e),ce=(e,t,n)=>{let o=xe[xe.length-1]?.source??pn;if(!mc(t,o))return;let i=na(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:F(n)}))},Vr=(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}of r){let a=e.projectData.resources?.variables?.[o],l=a?.scope,c=a?.type;zt(l,o),Wt(c,i,o),l==="context"&&(n.variables[o]=Yt(n.variables[o],i,s))}},ia=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:n,payload:r})=>{yc(e,n,r)})},sa=(e,t)=>{let{sectionId:n,lineId:r}=t,s=G({state:e},{sectionId:n})?.lines?.find(a=>a.id===r)?.actions;s&&Object.entries(s).forEach(([a,l])=>{go(e,a,l)})},Xr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=ve(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Ye({state:e}),e.global.skipMode&&Ee({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=hn(e.projectData),delete n.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=F(pt),e.global.overlayStack=[],ke(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let a=i;a<=t;a++)a>i&&fn(e),sa(e,r.timeline[a]),ia(e,r.timeline[a]);let s=Pe(n);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(a=>a?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},aa=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=n;Ur(t);let a=t.story.initialSceneId,l=t.story.scenes[a],c=l.initialSectionId,u=l.sections[c],f={sceneId:a,sectionId:c,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:d}=Ft(t),h={...d,...o};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,accountViewedRegistry:Bs(s,"accountViewedRegistry"),nextLineConfig:gt(),saveSlots:Ms(r),overlayStack:[],variables:h,...Hs({loadedGlobalRuntime:i})},contexts:[Kr({pointer:f,projectData:t})]}},ca=({state:e})=>e.global.overlayStack||[],la=({state:e})=>e.global.pendingEffects,Qr=({state:e})=>e.global.skipMode,ua=({state:e})=>e.global.autoMode,Zr=({state:e})=>e.global.dialogueUIHidden,eo=({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=G({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),a=i.lines.slice(0,s+1),l=[],c={};for(let u of a){let f=u.actions||{};if(c=Le([c,f]),!f.dialogue)continue;let d=c.dialogue||{},h="";d.character?.name!==void 0?h=d.character.name:d.characterId&&(h=e.projectData.resources?.characters?.[d.characterId]?.name||""),l.push({sectionId:r,lineId:u.id,content:f.dialogue.content,text:Ns(f.dialogue.content),characterId:d.characterId,character:{...d.character||{},name:h},characterName:h})}return l},fa=({state:e})=>e.global.confirmDialog??null,da=({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 a=G({state:e},{sectionId:r});if(!a||!a.lines||!Array.isArray(a.lines))return s.lastLineId===o;let l=a.lines.findIndex(u=>u.id===s.lastLineId),c=a.lines.findIndex(u=>u.id===o);return l===-1||c===-1?s.lastLineId===o:c<=l},pa=({registry:e},t)=>{let{resourceId:n}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===n)},yn=({state:e},t)=>da({state:e,registry:e.global.accountViewedRegistry},t),ha=({state:e},t)=>pa({registry:e.global.accountViewedRegistry},t),ga=({state:e})=>e.global.nextLineConfig,to=({state:e,pointer:t}={})=>{let n=t??oe({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=G({state:e},{sectionId:r})?.lines||[],a=s.findIndex(c=>c.id===o);if(a<0)return;let l;for(let c of s.slice(0,a+1)){let u=c?.actions;if(u?.cleanAll&&(l=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){l=void 0;continue}let f=u.choice;if(f?.resourceId){l=f.resourceId;continue}f?.animations||(l=void 0)}return l},ie=({state:e})=>!!to({state:e}),ma=({state:e})=>structuredClone(e),no=({state:e})=>e.global.saveSlots,ya=({state:e},t)=>{let n=t?.slotId,r=mt(n);return e.global.saveSlots[r]},bn=({state:e})=>dt(e),ba=({state:e},t)=>ae(e,t?.runtimeId),ro=({state:e})=>({...e.global?.variables??{},...gn(e)?.variables??{}}),oe=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(n)return{currentPointerMode:"read",pointer:n.pointers?.read}},G=({state:e},t)=>{let{sectionId:n}=t;return dn(e.projectData,n).section},In=({state:e})=>{let t=oe({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=G({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},oo=({state:e})=>{let{sectionId:t,lineId:n}=oe({state:e}).pointer,o=G({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n),a=o.slice(0,i+1).map(c=>{let u=c.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return Le(a)},Ia=({state:e})=>{let t=io({state:e}),r=In({state:e})?.actions??{},o=Le([t??{},r]);return qt(t??{},o??{})},Aa=({state:e},{sectionId:t})=>{let n=G({state:e},{sectionId:t});if(!n?.lines)return[];let r=[],o={};for(let i of n.lines){let s=i.actions||{},a=Le([o,s]),l=qt(o,a);r.push({id:i.id,changes:l,presentationState:a}),o=Ht(a)}return r},wa=({state:e},{sectionId:t,includePresentationState:n=!1})=>{let r=Aa({state:e},{sectionId:t});return n?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},io=({state:e})=>{let{sectionId:t,lineId:n}=oe({state:e}).pointer,o=G({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===n);if(i<=0)return null;let a=o.slice(0,i).map(l=>{let c=l.actions||{},u={};return Object.keys(c).forEach(f=>{u[f]=c[f]}),u});return Ht(Le(a))},An=({state:e},{slotsPerPage:t=6}={})=>{let o=((bn({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let a=o+s,l=e.global.saveSlots&&e.global.saveSlots[mt(a)]||{};i.push({...l,slotId:a})}return{saveSlots:i}},xa=no,Ea=An,va=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},Sa=({state:e},t={})=>{let n=oo({state:e}),r=io({state:e}),o=In({state:e})?.actions??{},{sectionId:i}=oe({state:e}).pointer,{sceneId:s}=dn(e.projectData,i),a=bn({state:e}),l=t?.activePersistentAnimations??[],c=t?.restoredPersistentAnimations??[],u=ro({state:e}),{saveSlots:f}=An({state:e}),d=va(e);return Or({presentationState:n,previousPresentationState:r,currentLineActions:o,resources:e.projectData.resources,currentSceneId:s,screen:e.projectData.screen,dialogueUIHidden:a.dialogueUIHidden,autoMode:a.autoMode,skipMode:a.skipMode,isChoiceVisible:ie({state:e}),canRollback:yo({state:e}),skipOnlyViewedLines:!a.skipUnseenText,isLineCompleted:a.isLineCompleted,skipTransitionsAndAnimations:!!a.skipTransitionsAndAnimations||d,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,dialogueHistory:eo({state:e}),saveSlots:f,variables:u,runtime:a,activePersistentAnimations:l,restoredPersistentAnimations:c})},Ca=({state:e},t)=>(e.global.confirmDialog=qs(t),e.global.pendingEffects.push({name:"render"}),e),_a=({state:e})=>(e.global.confirmDialog&&(ke(e),e.global.pendingEffects.push({name:"render"})),e),Ra=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),ce(e,"pushOverlay",t),e),La=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),ce(e,"popOverlay",void 0),e),$a=({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),Oa=({state:e})=>(e.global.overlayStack=[],ke(e),e.global.pendingEffects.push({name:"render"}),ce(e,"clearOverlays",void 0),e),ka=e=>{e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},yt=(e,t)=>{e.global.isLineCompleted=!1;let n=!!to({state:e,pointer:t});return n&&ka(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:n}},so=({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:ae(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),Ye=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Pa=({state:e})=>{let t=e.global.autoMode;return ie({state:e})&&!t||(t?Ye({state:e}):so({state:e})),e},ao=({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),Ee=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Ta=({state:e})=>{let t=Qr({state:e});return ie({state:e})&&!t||(t?Ee({state:e}):ao({state:e})),e},bt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),ce(e,"showDialogueUI",void 0),e),co=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),ce(e,"hideDialogueUI",void 0),e),Na=({state:e})=>(Zr({state:e})?bt({state:e}):co({state:e}),e),Se=(e,t,n)=>(Jr(e,t,n),Xs(e),e.global.pendingEffects.push({name:"render"}),e),qe=(e,t,n,r)=>{let o=Jr(e,t,n);return e.global.pendingEffects.push({name:"render"}),ce(e,r,{value:o}),e},Da=({state:e},t)=>Se(e,"dialogueTextSpeed",t?.value),Va=({state:e},t)=>Se(e,"autoForwardDelay",t?.value),ja=({state:e},t)=>Se(e,"skipUnseenText",t?.value),Ma=({state:e},t)=>Se(e,"skipTransitionsAndAnimations",t?.value),Ua=({state:e},t)=>Se(e,"soundVolume",t?.value),Ba=({state:e},t)=>Se(e,"musicVolume",t?.value),Fa=({state:e},t)=>Se(e,"muteAll",t?.value),za=({state:e},t)=>qe(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),Wa=({state:e})=>{let t=ae(e,"saveLoadPagination")+1;return qe(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},Ya=({state:e})=>{let t=ae(e,"saveLoadPagination")-1;return qe(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},qa=({state:e},t)=>qe(e,"menuPage",t?.value,"setMenuPage"),Ha=({state:e},t)=>qe(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Ja=({state:e})=>(e.global.pendingEffects=[],e),Ka=({state:e},t)=>(e.global.pendingEffects.push(t),e),lo=(e,{sectionId:t,resetStoryState:n=!1})=>{let r=G({state:e},{sectionId:t});if(!r)return console.warn(`Section not found: ${t}`),e;let o=r.lines?.[0];if(!o)return console.warn(`Section ${t} has no lines`),e;if(n&&!ea(e))return e;e.global.autoMode&&Ye({state:e}),e.global.skipMode&&Ee({state:e});let i=e.contexts?.[e.contexts.length-1];if(i){let s=Pe(i);i.rollback||ve(i,{compatibilityAnchor:!0}),s.read={sectionId:t,lineId:o.id},n?i.rollback=ze({pointer:s.read}):mn(e,{sectionId:t,lineId:o.id})}return yt(e,i?.pointers?.read),e},Ga=({state:e},t)=>lo(e,{sectionId:t?.sectionId,resetStoryState:!0}),uo=e=>(e.global.accountViewedRegistry=Ts(e.global.accountViewedRegistry),e.global.accountViewedRegistry),fo=(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:F(n.value)}))}})},po=(e,t)=>{fo(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:[]}}])},Xa=(e,t,{sectionId:n,lineId:r})=>{if(!n||!r)return!1;let o=j(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=G({state:e},{sectionId:n});if(s?.lines){let a=s.lines.findIndex(c=>c.id===i.lastLineId),l=s.lines.findIndex(c=>c.id===r);if(a===-1||l>a)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},We=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;Xa(e,uo(e),t)&&po(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},Qa=({state:e},t)=>(We(e,t),e.global.pendingEffects.push({name:"render"}),e),Za=({state:e},t)=>{let{resourceId:n}=t;if(e.global.accountViewedRegistry!==void 0){let r=uo(e);r.resources.find(i=>i.resourceId===n)||(r.resources.push({resourceId:n}),po(e,{sections:[],resources:[{resourceId:n}]}))}return e.global.pendingEffects.push({name:"render"}),e},ho=({state:e},t)=>{let n=Vs(t.manual),{auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,a=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 l=e.global.nextLineConfig.auto?.enabled,c=ie({state:e});return!a&&!c&&l===!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}}):!a&&l===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),ce(e,"setNextLineConfig",t),e},ec=({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=mt(n),s=F(e.contexts);s?.forEach(c=>{Pe(c),Gr(c.rollback),Us(c.rollback)});let a={contexts:s},l={formatVersion:jr,slotId:Br(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:a};return e.global.saveSlots[i]=l,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},tc=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=mt(n),o=e.global.saveSlots[r];if(o){let i=Ys(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=gt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,ke(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},nc=({state:e},t)=>{let{projectData:n}=t;return Ur(n),e.projectData=n,ke(e),e.global.pendingEffects.push({name:"render"}),e},rc=({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&&!G({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=G({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(c=>c.id===r))return console.warn(`Line not found: ${r} in section ${i}`),e;let l=Pe(o);return l.read={sectionId:i,lineId:r},yt(e,l.read),e},oc=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return bt({state:e}),e;if(ie({state:e})&&t?._interactionSource!=="choice")return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0;let c=oe({state:e})?.pointer,u=c?.sectionId,f=c?.lineId;u&&f&&We(e,{sectionId:u,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ae(e,"autoForwardDelay")}});let d=e.global.nextLineConfig;return d?.auto?.enabled&&d.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:d.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=oe({state:e})?.pointer,r=n?.sectionId,o=G({state:e},{sectionId:r}),i=e.contexts[e.contexts.length-1],s=o?.lines||[],l=s.findIndex(c=>c.id===n?.lineId)+1;if(l<s.length){let c=s[l],u=!ae(e,"skipUnseenText");if(e.global.skipMode&&u&&!yn({state:e},{sectionId:r,lineId:c.id}))return Ee({state:e}),e;if(i&&!i.rollback&&ve(i,{compatibilityAnchor:!0}),i){let h=Pe(i),g=h.read?.lineId;g&&r&&We(e,{sectionId:r,lineId:g}),h.read={sectionId:r,lineId:c.id}}mn(e,{sectionId:r,lineId:c.id}),fn(e);let{isChoiceVisible:f}=yt(e,{sectionId:r,lineId:c.id}),d=e.global.nextLineConfig;d?.auto?.enabled&&!f&&d.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:d.auto.delay}})}else e.global.autoMode&&Ye({state:e}),e.global.skipMode&&Ee({state:e});return e},ic=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0;let t=ie({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ae(e,"autoForwardDelay")}});let n=oe({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&We(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},sc=({state:e},t)=>lo(e,{sectionId:t?.sectionId}),ac=({state:e})=>{if(e.global.dialogueUIHidden)return bt({state:e}),e;if(ie({state:e}))return e;let t=oe({state:e})?.pointer,n=t?.sectionId,r=G({state:e},{sectionId:n}),o=e.contexts[e.contexts.length-1],i=r?.lines||[],a=i.findIndex(l=>l.id===t?.lineId)+1;if(a<i.length){let l=i[a],c=!ae(e,"skipUnseenText");if(e.global.skipMode&&c&&!yn({state:e},{sectionId:n,lineId:l.id}))return Ee({state:e}),e;if(o&&!o.rollback&&ve(o,{compatibilityAnchor:!0}),o){let f=Pe(o),d=f.read?.lineId;d&&n&&We(e,{sectionId:n,lineId:d}),f.read={sectionId:n,lineId:l.id}}mn(e,{sectionId:n,lineId:l.id}),fn(e);let{isChoiceVisible:u}=yt(e,{sectionId:n,lineId:l.id});e.global.nextLineConfig.auto?.enabled&&!u&&e.global.nextLineConfig.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})}else e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},cc=({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=[],a=[];return r.forEach(({variableId:l,op:c,value:u})=>{let f=e.projectData.resources?.variables?.[l],d=f?.scope,h=f?.type;zt(d,l),Wt(h,c,l);let g=d==="context"?o.variables:e.global.variables;d==="context"&&(i=!0,a.push({variableId:l,op:c,value:u})),g[l]=Yt(g[l],c,u),(d==="device"||d==="account")&&s.push({scope:d,path:`variables.${l}`,op:"set",value:F(g[l])})}),i&&ce(e,"updateVariable",{id:n,operations:a}),fo(e,s),e.global.pendingEffects.push({name:"render"}),e},lc=e=>(t,n)=>e({state:t},n),uc=e=>({variables:{...e.global?.variables??{},...gn(e)?.variables??{}},runtime:dt(e)}),fc=e=>{if(!j(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")},dc=(e,t,n)=>{if(!j(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!j(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")},pc=(e,t)=>{fc(t);for(let n=0;n<t.branches.length;n+=1){let r=t.branches[n];if(dc(r,n,t.branches.length),!(Object.prototype.hasOwnProperty.call(r,"when")&&!je(r.when,uc(e)))){Object.entries(r.actions).forEach(([i,s])=>{go(e,i,s)});return}}},hc={conditional:{replayLine:pc},updateVariable:{recordSources:[pn],replayLine:Vr,replayRecorded:Vr,persistInSaveSlot:!0},setNextLineConfig:{replayLine:lc(ho)}},It=e=>hc[e]??null,gc=e=>It(e)?.persistInSaveSlot===!0,mc=(e,t)=>{let n=It(e)?.recordSources;return Array.isArray(n)&&n.includes(t)},yc=(e,t,n)=>{It(t)?.replayRecorded?.(e,n)},go=(e,t,n)=>{It(t)?.replayLine?.(e,n)},mo=({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=o.currentIndex+n;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},yo=({state:e})=>mo({state:e},{offset:-1})!==null,bc=({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=ve(r,{compatibilityAnchor:!r.rollback}),i=o.currentIndex+n;return i<0||i>=o.timeline.length?e:Xr(e,i)},Ic=({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=ve(o,{compatibilityAnchor:!o.rollback}),a=i.timeline.slice(0,i.currentIndex+1).findLastIndex(l=>l.sectionId===n&&l.lineId===r);if(a===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return a===i.currentIndex?e:Xr(e,a)},bo=e=>{let t=aa(e);return tr(t,{selectPendingEffects:la,selectSkipMode:Qr,selectAutoMode:ua,selectIsChoiceVisible:ie,selectDialogueUIHidden:Zr,selectDialogueHistory:eo,selectConfirmDialog:fa,selectIsLineAccountViewed:yn,selectIsResourceAccountViewed:ha,selectNextLineConfig:ga,selectSystemState:ma,selectSaveSlotMap:no,selectSaveSlots:xa,selectSaveSlot:ya,selectRuntime:bn,selectRuntimeValue:ba,selectAllVariables:ro,selectCurrentPointer:oe,selectSection:G,selectCurrentLine:In,selectPresentationState:oo,selectPresentationChanges:Ia,selectSectionLineChanges:wa,selectSaveSlotPage:An,selectCurrentPageSlots:Ea,selectRenderState:Sa,selectOverlayStack:ca,selectLineIdByOffset:mo,selectCanRollback:yo,startAutoMode:so,stopAutoMode:Ye,toggleAutoMode:Pa,startSkipMode:ao,stopSkipMode:Ee,toggleSkipMode:Ta,showDialogueUI:bt,hideDialogueUI:co,toggleDialogueUI:Na,setDialogueTextSpeed:Da,setAutoForwardDelay:Va,setSkipUnseenText:ja,setSkipTransitionsAndAnimations:Ma,setSoundVolume:Ua,setMusicVolume:Ba,setMuteAll:Fa,setSaveLoadPagination:za,incrementSaveLoadPagination:Wa,decrementSaveLoadPagination:Ya,setMenuPage:qa,setMenuEntryPoint:Ha,showConfirmDialog:Ca,hideConfirmDialog:_a,resetStoryAtSection:Ga,clearPendingEffects:Ja,appendPendingEffect:Ka,beginRollbackActionBatch:ra,endRollbackActionBatch:oa,addViewedLine:Qa,addViewedResource:Za,setNextLineConfig:ho,saveSlot:ec,loadSlot:tc,updateProjectData:nc,sectionTransition:sc,jumpToLine:rc,nextLine:oc,markLineCompleted:ic,rollbackToLine:Ic,rollbackByOffset:bc,pushOverlay:Ra,popOverlay:La,replaceLastOverlay:$a,clearOverlays:Oa,updateVariable:cc,nextLineFromSystem:ac},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var Ac="route-engine",wc="projectPersistence";var Ao=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),H=e=>Object.prototype.toString.call(e)==="[object Object]",Io="variables.",xc=(e={})=>{let t=H(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!H(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)}:!H(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},Ec=(e={})=>{let t=H(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!H(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)}:!H(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},vc=(e,t)=>{let n=Ec(e),r=xc(t),o=n.sections.map(s=>({...s})),i=n.resources.map(s=>({...s}));return r.sections.forEach(s=>{let a=o.find(l=>l.sectionId===s.sectionId);if(!a){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(a.lastLineId!==void 0){if(s.lineId===void 0){delete a.lastLineId;return}a.lastLineId=s.lineId}}),r.resources.forEach(s=>{i.find(l=>l.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},wo=(e={})=>{let t=H(e)?e:{};return{saveSlots:H(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:H(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:H(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:H(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:H(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Sc=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,n)=>{if(!H(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${n}] entry.`);let r=t.path?.startsWith(Io)?t.path.slice(Io.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}].`)})},Cc=(e,t)=>{let n={};return Sc(t).forEach(r=>{if(r.path==="viewedRegistry"){n.accountViewedRegistry=vc(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},wn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},_c=e=>{let t=wn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Rc=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},Lc=({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}".`))}}),$c=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let l=r.transaction(t,"readonly").objectStore(t).get(n);l.onsuccess=()=>{o(l.result??null)},l.onerror=()=>{i(l.error??new Error(`Failed to read persisted namespace "${n}" from IndexedDB.`))}})},He=async({databasePromise:e,objectStoreName:t,namespace:n,patch:r})=>{let o=await e;return new Promise((i,s)=>{let a=o.transaction(t,"readwrite"),l=a.objectStore(t),c=l.get(n),u=!1,f=h=>{u||(u=!0,s(h))},d=()=>{u||(u=!0,i())};c.onerror=()=>{f(c.error??new Error(`Failed to read persisted namespace "${n}" before updating IndexedDB.`))},c.onsuccess=()=>{let h=wo(c.result),g=typeof r=="function"?r(h):r,y={namespace:n,version:1,...Ao(),...h,...g},I=l.put(y);I.onerror=()=>{f(I.error??new Error(`Failed to persist namespace "${n}" to IndexedDB.`))}},a.oncomplete=()=>{d()},a.onerror=()=>{f(a.error??new Error(`IndexedDB transaction failed while updating namespace "${n}".`))},a.onabort=()=>{f(a.error??new Error(`IndexedDB transaction aborted while updating namespace "${n}".`))}})},Oc=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let s=r.transaction(t,"readwrite"),l=s.objectStore(t).delete(n),c=!1,u=d=>{c||(c=!0,i(d))},f=()=>{c||(c=!0,o())};l.onerror=()=>{u(l.error??new Error(`Failed to clear persisted namespace "${n}" from IndexedDB.`))},s.oncomplete=()=>{f()},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}".`))}})},xn=(e={})=>{let{indexedDB:t,databaseName:n=Ac,objectStoreName:r=wc,namespace:o}=e,i=Rc(t),s=_c(o),a=Lc({indexedDB:i,databaseName:n,objectStoreName:r});return{namespace:s,load:async()=>{let l=await $c({databasePromise:a,objectStoreName:r,namespace:s});return{...Ao(),...wo(l)}},clear:async()=>Oc({databasePromise:a,objectStoreName:r,namespace:s}),saveSlots:async l=>He({databasePromise:a,objectStoreName:r,namespace:s,patch:{saveSlots:H(l)?l:{}}}),saveGlobalDeviceVariables:async l=>He({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:H(l)?l:{}}}),saveGlobalAccountVariables:async l=>He({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalAccountVariables:H(l)?l:{}}}),saveGlobalRuntime:async l=>He({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalRuntime:H(l)?l:{}}}),applyScopedDataUpdates:async l=>He({databasePromise:a,objectStoreName:r,namespace:s,patch:c=>Cc(c,l)})}},kc=xn;var Pc=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Tc=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),xo="conditional",Eo="choice",At=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function En(e){let t,n=0,r=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:a}=e,l=(A=new Map,v=Date.now())=>new Map(Array.from(A.entries()).filter(([,T])=>v<T.expiresAt).map(([T,V])=>[T,{animation:structuredClone(V.animation),startedAt:V.startedAt,expiresAt:V.expiresAt}])),c=(A=new Map)=>Array.from(A.values()).map(v=>structuredClone(v.animation)),u=(A=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,v])=>A<v.expiresAt))},f=()=>{for(;t.selectPendingEffects().length>0;){let A=[...t.selectPendingEffects()];t.clearPendingEffects();try{a(A)}catch(v){throw t.clearPendingEffects(),A.forEach(T=>{t.appendPendingEffect(T)}),v}}},d=({initialState:A,namespace:v})=>{t=bo(A),n=0,r=wn(v),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),f()},h=()=>r,g=()=>t.selectPresentationState(),y=()=>t.selectPresentationChanges(),I=A=>t.selectSectionLineChanges(A),b=(A={})=>{n+=1;let v=Date.now();u(v);let T=i.size>0,V=l(o,v),q=T?l(i,v):new Map,le={...t.selectRenderState({activePersistentAnimations:c(V),restoredPersistentAnimations:c(q)}),id:`render-${n}`};return s.set(le.id,{builtAt:v,persistentAnimationSessions:new Map([...q.entries(),...V.entries()]),usedRestoredPersistentAnimationSessions:T}),le},m=(A={})=>b(A),E=(A={})=>b(A),S=A=>{let v=typeof A?.id=="string"&&A.id.length>0?A.id:null,T=v?s.get(v):null;v&&s.delete(v);let V=new Map;wr(A?.animations).forEach(q=>{let te=lt(q);if(!te)return;let le=T?.persistentAnimationSessions?.get(te)??o.get(te),_o=Math.max(0,Er(q)),Rn=le?.startedAt??T?.builtAt??Date.now();V.set(te,{animation:structuredClone(q),startedAt:Rn,expiresAt:Rn+_o})}),o=V,T?.usedRestoredPersistentAnimationSessions&&(i=new Map)},$=()=>t.selectSystemState(),O=()=>t.selectSaveSlotMap(),_=A=>t.selectSaveSlot(A),D=A=>t.selectSaveSlotPage(A),N=()=>t.selectSkipMode(),k=()=>t.selectAutoMode(),P=()=>t.selectRuntime(),x=()=>t.selectIsChoiceVisible(),C=(A,v,T={})=>T.interactionSource!==Eo||A!=="nextLine"||!At(v)?v:{...v,_interactionSource:Eo},M=(A,v)=>{t[A]&&(Pc.has(A)&&(Tc.has(A)?i=l(o):i=new Map,o=new Map),t[A](v),f())},z=(A,v,T,V={})=>{if(A===xo){let q=U(T),te=Jt({[A]:v},q);Sn(te[A],T,V);return}M(A,v)},Y=(A,v)=>{z(A,v)},U=A=>{if(!A)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(A,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:v,...T}=A,V=t.selectAllVariables?t.selectAllVariables():void 0;return{...T,_event:v,variables:V,runtime:t.selectRuntime?t.selectRuntime():{}}},Je=A=>{if(!At(A))throw new Error("conditional action payload must be an object");if(!Array.isArray(A.branches))throw new Error("conditional action requires branches array");if(A.branches.length===0)throw new Error("conditional action requires at least one branch")},Ke=(A,v,T)=>{if(!At(A))throw new Error(`conditional branch at index ${v} must be an object`);if(!At(A.actions))throw new Error(`conditional branch at index ${v} requires actions object`);if(!Object.prototype.hasOwnProperty.call(A,"when")&&v!==T-1)throw new Error("conditional else branch must be the last branch")},Sn=(A,v,T)=>{Je(A);for(let V=0;V<A.branches.length;V+=1){let q=A.branches[V];Ke(q,V,A.branches.length);let te=U(v);if(!(Object.prototype.hasOwnProperty.call(q,"when")&&!je(q.when,te))){Cn(q.actions,v,T);return}}},Co=(A,v,T,V)=>{let q=U(T),le=Jt({[A]:v},q)[A];if(A===xo){Sn(le,T,V);return}M(A,C(A,le,V))},Cn=(A,v,T)=>{Object.entries(A).forEach(([V,q])=>{Co(V,q,v,T)})},_n=(A,v,T={})=>{t.beginRollbackActionBatch({source:T.rollbackSource});try{Cn(A,v,T)}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:z,handleInternalAction:Y,handleActions:_n,selectRenderState:m,prepareRenderState:E,commitRenderState:S,selectPresentationState:g,selectPresentationChanges:y,selectSectionLineChanges:I,selectSystemState:$,selectSaveSlotMap:O,selectSaveSlot:_,selectSaveSlotPage:D,selectSaveSlots:O,selectRuntime:P,selectIsChoiceVisible:x,handleLineActions:()=>{let A=t.selectCurrentLine();return A?.actions?(_n(A.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:h}}var vn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},Nc=80,So=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{let o=e.prepareRenderState?.(r)??e.selectRenderState(r);n?.(o),t.render(o),e.commitRenderState?.(o)},Dc=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&So({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},Vc=({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 a=r.delay??1e3;n.getElapsed()>=a&&(t.remove(i),n.setCallback(null),n.setElapsed(0),wt(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},jc=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Mc=({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 a=r?.delay??Nc;n.getElapsed()>=a&&(n.setElapsed(0),wt(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Uc=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Bc=({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 a=r.delay??1e3;n.getElapsed()>=a&&(n.setElapsed(0),wt(e,"nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},Fc=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},zc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveSlots(t?.saveSlots))},Wc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalDeviceVariables(t?.globalDeviceVariables))},Yc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalAccountVariables(t?.globalAccountVariables))},qc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalRuntime(t?.globalRuntime))},Hc=({enqueuePersistenceWrite:e},t)=>{e(n=>{if(typeof n.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return n.applyScopedDataUpdates(t?.updates)})},vo={render:So,saveSlots:zc,saveGlobalDeviceVariables:Wc,saveGlobalAccountVariables:Yc,saveGlobalRuntime:qc,applyScopedDataUpdates:Hc,handleLineActions:Dc,startAutoNextTimer:Vc,clearAutoNextTimer:jc,startSkipNextTimer:Mc,clearSkipNextTimer:Uc,nextLineConfigTimer:Bc,clearNextLineConfigTimer:Fc},Jc=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),wt=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},Kc=(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(!Jc.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},Gc=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:a})=>{let l=vn(),c=vn(),u=vn(),f=s??null,d=Promise.resolve(),h=null,g=null,y=!1,I=0,b=x=>{if(o){o(x);return}console.error("RouteEngine persistence write failed.",x)},m=()=>{if(f)return f;let x=e();return f=xn({indexedDB:i,namespace:a??x?.getNamespace?.()}),f},E=x=>{d=d.catch(()=>{}).then(()=>{let C=m();return x(C)}).catch(C=>{b(C)})},S=x=>{let C=typeof x?.id=="string"&&x.id.length>0?x.id:null;I+=1,h=C,y=!1},$=()=>I,O=(x={})=>{if(x?.aborted===!0)return!1;let C=typeof x?.id=="string"&&x.id.length>0?x.id:null;return C?C!==h||C===g?!1:(g=C,!0):h!==null||y?!1:(y=!0,!0)},_=(x,C={})=>{if(x!=="renderComplete"||!O(C))return!1;let M=e();return wt(M,"markLineCompleted",{}),!0},D=(x={})=>{if(x?._interactionSource==="choice")return!0;let C=x?.actions;return!C||typeof C!="object"||Array.isArray(C)?!1:Object.values(C).some(M=>M?._interactionSource==="choice")},N=(x,C={})=>!C?.actions||typeof x?.selectIsChoiceVisible!="function"||!x.selectIsChoiceVisible()?!1:!D(C),k=({preprocessPayload:x,onEvent:C}={})=>async(M,z={})=>{let Y=e();if(N(Y,z))return C?.(M,z);let U=await x?.(M,z)??z;if(N(Y,U))return C?.(M,U);if(_(M,U),U?.actions){let Je=U?._event?{_event:U._event}:U?.event?{_event:U.event}:void 0,Ke=U?._interactionSource?{interactionSource:U._interactionSource}:void 0;Ke?Y.handleActions(U.actions,Je,Ke):Y.handleActions(U.actions,Je)}return C?.(M,U)},P=x=>{let C=e(),M=Kc(x);M.forEach(Y=>{if(!vo[Y.name]&&!r)throw new Error(`Unhandled pending effect "${Y.name}".`)});let z={engine:C,routeGraphics:t,ticker:n,autoTimer:l,skipTimer:c,nextLineConfigTimerState:u,trackRenderDispatch:S,getRenderDispatchCount:$,enqueuePersistenceWrite:E};for(let Y of M){let U=vo[Y.name];if(U){U(z,Y.payload);continue}r(Y,z)}};return P.handleRouteGraphicsEvent=_,P.createRouteGraphicsEventHandler=k,P},Xc=Gc;var Qc=(e,t={})=>{let{resources:n={}}=t;return cn(e,n)};var hu=En;export{Xc as createEffectsHandler,kc as createIndexedDbPersistence,hu as default,Qc as resolveLayoutReferences};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "route-engine-js",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.10.0",
|
|
4
4
|
"description": "A lightweight Visual Novel engine built in JavaScript for creating interactive narrative games with branching storylines",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
50
|
"immer": "^10.1.1",
|
|
51
|
-
"jempl": "1.
|
|
51
|
+
"jempl": "1.1.1",
|
|
52
52
|
"js-yaml": "^4.1.0",
|
|
53
53
|
"puty": "^0.1.1"
|
|
54
54
|
},
|