route-engine-js 1.3.0 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/RouteEngine.js +1 -1
- package/package.json +1 -1
package/dist/RouteEngine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Pr=Object.defineProperty;var Nr=(e,t)=>{for(var n in t)Pr(e,n,{get:t[n],enumerable:!0})};var rn=Symbol.for("immer-nothing"),Zt=Symbol.for("immer-draftable"),U=Symbol.for("immer-state");function G(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var he=Object.getPrototypeOf;function ee(e){return!!e&&!!e[U]}function re(e){return e?on(e)||Array.isArray(e)||!!e[Zt]||!!e.constructor?.[Zt]||Ne(e)||De(e):!1}var Dr=Object.prototype.constructor.toString();function on(e){if(!e||typeof e!="object")return!1;let t=he(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)===Dr}function ke(e,t){Pe(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function Pe(e){let t=e[U];return t?t.type_:Array.isArray(e)?1:Ne(e)?2:De(e)?3:0}function ot(e,t){return Pe(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function sn(e,t,n){let r=Pe(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Vr(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Ne(e){return e instanceof Map}function De(e){return e instanceof Set}function ne(e){return e.copy_||e.base_}function it(e,t){if(Ne(e))return new Map(e);if(De(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=on(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[U];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(he(e),r)}else{let r=he(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function ut(e,t=!1){return Ve(e)||ee(e)||!re(e)||(Pe(e)>1&&(e.set=e.add=e.clear=e.delete=Mr),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>ut(r,!0))),e}function Mr(){G(2)}function Ve(e){return Object.isFrozen(e)}var jr={};function oe(e){let t=jr[e];return t||G(0,e),t}var be;function ln(){return be}function Br(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Qt(e,t){t&&(oe("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function st(e){lt(e),e.drafts_.forEach(Fr),e.drafts_=null}function lt(e){e===be&&(be=e.parent_)}function en(e){return be=Br(be,e)}function Fr(e){let t=e[U];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function tn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[U].modified_&&(st(t),G(4)),re(e)&&(e=Oe(t,e),t.parent_||Te(t,e)),t.patches_&&oe("Patches").generateReplacementPatches_(n[U].base_,e,t.patches_,t.inversePatches_)):e=Oe(t,n,[]),st(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==rn?e:void 0}function Oe(e,t,n){if(Ve(t))return t;let r=t[U];if(!r)return ke(t,(o,i)=>nn(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Te(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),ke(i,(a,c)=>nn(e,r,o,a,c,n,s)),Te(e,o,!1),n&&e.patches_&&oe("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function nn(e,t,n,r,o,i,s){if(ee(o)){let a=i&&t&&t.type_!==3&&!ot(t.assigned_,r)?i.concat(r):void 0,c=Oe(e,o,a);if(sn(n,r,c),ee(c))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(re(o)&&!Ve(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Oe(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&Te(e,o)}}function Te(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ut(t,n)}function Ur(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:ln(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=ft;n&&(o=[r],i=Ie);let{revoke:s,proxy:a}=Proxy.revocable(o,i);return r.draft_=a,r.revoke_=s,a}var ft={get(e,t){if(t===U)return e;let n=ne(e);if(!ot(n,t))return zr(e,n,t);let r=n[t];return e.finalized_||!re(r)?r:r===nt(e.base_,t)?(rt(e),e.copy_[t]=at(r,e)):r},has(e,t){return t in ne(e)},ownKeys(e){return Reflect.ownKeys(ne(e))},set(e,t,n){let r=cn(ne(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=nt(ne(e),t),i=o?.[U];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Vr(n,o)&&(n!==void 0||ot(e.base_,t)))return!0;rt(e),ct(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 nt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,rt(e),ct(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=ne(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){G(11)},getPrototypeOf(e){return he(e.base_)},setPrototypeOf(){G(12)}},Ie={};ke(ft,(e,t)=>{Ie[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Ie.deleteProperty=function(e,t){return Ie.set.call(this,e,t,void 0)};Ie.set=function(e,t,n){return ft.set.call(this,e[0],t,n,e[0])};function nt(e,t){let n=e[U];return(n?ne(n):e)[t]}function zr(e,t,n){let r=cn(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function cn(e,t){if(!(t in e))return;let n=he(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=he(n)}}function ct(e){e.modified_||(e.modified_=!0,e.parent_&&ct(e.parent_))}function rt(e){e.copy_||(e.copy_=it(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Wr=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(c=i,...l){return s.produce(c,u=>n.call(this,u,...l))}}typeof n!="function"&&G(6),r!==void 0&&typeof r!="function"&&G(7);let o;if(re(t)){let i=en(this),s=at(t,void 0),a=!0;try{o=n(s),a=!1}finally{a?st(i):lt(i)}return Qt(i,r),tn(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===rn&&(o=void 0),this.autoFreeze_&&ut(o,!0),r){let i=[],s=[];oe("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else G(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...a)=>this.produceWithPatches(s,c=>t(c,...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){re(e)||G(8),ee(e)&&(e=dt(e));let t=en(this),n=at(e,void 0);return n[U].isManual_=!0,lt(t),n}finishDraft(e,t){let n=e&&e[U];(!n||!n.isManual_)&&G(9);let{scope_:r}=n;return Qt(r,t),tn(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=oe("Patches").applyPatches_;return ee(e)?r(e,t):this.produce(e,o=>r(o,t))}};function at(e,t){let n=Ne(e)?oe("MapSet").proxyMap_(e,t):De(e)?oe("MapSet").proxySet_(e,t):Ur(e,t);return(t?t.scope_:ln()).drafts_.push(n),n}function dt(e){return ee(e)||G(10,e),an(e)}function an(e){if(!re(e)||Ve(e))return e;let t=e[U],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=it(e,t.scope_.immer_.useStrictShallowCopy_)}else n=it(e,!0);return ke(n,(r,o)=>{sn(n,r,an(o))}),t&&(t.finalized_=!1),n}var z=new Wr,pt=z.produce,Rl=z.produceWithPatches.bind(z),$l=z.setAutoFreeze.bind(z),kl=z.setUseStrictShallowCopy.bind(z),Ol=z.applyPatches.bind(z),Tl=z.createDraft.bind(z),Pl=z.finishDraft.bind(z);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},O={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},xe={NOT:0};var v=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},F=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var ht=e=>{if(!e||e.trim()==="")throw new v("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new v(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${n}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let n of t)if(e.trim().endsWith(n))throw new v(`Incomplete comparison expression - missing right operand (got: '${e}')`)},un=e=>{if(e.trim().endsWith(" in"))throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new v(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);let r=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of r){if(!o)throw new v(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new v(`Invalid loop syntax (got: '$for ${e}')`)}};var fn=(e,t,n=!1)=>{if(t===null)return new F(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new F(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new F(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new F(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},dn=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new F(`Unknown function '${e}' (${n})`)};var Yr=(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=_(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},_=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return P(e.var,n,r);if(e.type===h.LITERAL)return e.value;if(e.type===h.VARIABLE)return P(e.path,n,r);if(e.type===h.INTERPOLATION)return Gr(e.parts,t,n,r);switch(e.type){case h.FUNCTION:return hn(e,t,n,r);case h.BINARY:return gn(e,t,n,r);case h.UNARY:return mn(e,t,n,r);case h.CONDITIONAL:return Kr(e,t,n,r);case h.LOOP:return eo(e,t,n,r);case h.OBJECT:return no(e,t,n,r);case h.ARRAY:return ro(e,t,n,r);case h.PARTIAL:return oo(e,t,n,r);case h.PATH_REFERENCE:return io(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},pn=new Map,Hr=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},P=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=pn.get(e);if(!r){let i=[],s="",a=0;for(let c=0;c<e.length;c++){let l=e[c];l==="["?(a++,s+=l):l==="]"?(a--,s+=l):l==="."&&a===0?s&&(i.push(s),s=""):s+=l}s&&i.push(s),r=[];for(let c of i){let l=Hr(c.trim());r.push(...l)}pn.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},Gr=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=_(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},hn=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw dn(e.name,o);let s=e.args.map(a=>_(a,t,n,r));return i(...s)},ge=(e,t,n,r)=>{if(e.var&&!e.type)return P(e.var,n,r);switch(e.type){case h.VARIABLE:return P(e.path,n,r);case h.LITERAL:return e.value;case h.BINARY:return gn(e,t,n,r);case h.UNARY:return mn(e,t,n,r);case h.FUNCTION:return hn(e,t,n,r);default:return _(e,t,n,r)}},gn=(e,t,n,r)=>{if(e.op===O.AND||e.op===O.OR){let s=ge(e.left,t,n,r),a=ge(e.right,t,n,r);switch(e.op){case O.AND:return s&&a;case O.OR:return s||a}}let o=_(e.left,t,n,r),i=_(e.right,t,n,r);switch(e.op){case O.EQ:return o==i;case O.NEQ:return o!=i;case O.GT:return o>i;case O.LT:return o<i;case O.GTE:return o>=i;case O.LTE:return o<=i;case O.IN:return Array.isArray(i)?i.includes(o):!1;case O.ADD:if(typeof o!="number"||typeof i!="number")throw new F(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case O.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new F(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},mn=(e,t,n,r)=>{let o=e.op===xe.NOT?ge(e.operand,t,n,r):_(e.operand,t,n,r);if(e.op===xe.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},qr=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===h.VARIABLE)if(P(o.path,n,r)){let s=e.bodies[0];if(s.type===h.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?_(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===h.LITERAL)a[l]=u.value;else if(u.type===h.VARIABLE)a[l]=P(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=P(d.path,n,r);f.push(p!=null?String(p):"")}else{let p=_(d,t,n,r);f.push(p!=null?String(p):"")}a[l]=f.join("")}else a[l]=_(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 c of s.properties){let l=c.parsedKey?_(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===h.LITERAL)a[l]=u.value;else if(u.type===h.VARIABLE)a[l]=P(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=P(d.path,n,r);f.push(p!=null?String(p):"")}else{let p=_(d,t,n,r);f.push(p!=null?String(p):"")}a[l]=f.join("")}else a[l]=_(u,t,n,r)}return a}}}return null},Kr=(e,t,n,r)=>{let o=qr(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||ge(s,t,n,r))return _(e.bodies[i],t,n,r)}return yn},Xr=(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 c of i.properties)if(c.parsedKey)return null;let a=[];for(let c=0;c<t.length;c++){let l=t[c];if(l[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]=l;else if(g.startsWith(r+".")){let y=g.substring(r.length+1);u[d]=l[y]}else return null}else if(p.type===h.INTERPOLATION){let g=[],y=!0;for(let b of p.parts)if(typeof b=="string")g.push(b);else if(b.type===h.VARIABLE){let m=b.path;if(m===r)g.push(l!=null?String(l):"");else if(m.startsWith(r+".")){let I=m.substring(r.length+1),x=l[I];g.push(x!=null?String(x):"")}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},Jr=(e,t)=>{let n=e.body,r=e.itemVar,o=Xr(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 c=a.key,l=a.value;if(l.type===h.LITERAL)i.push({key:c,type:"literal",value:l.value});else if(l.type===h.VARIABLE){let u=l.path;if(u===r)i.push({key:c,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(l.type===h.INTERPOLATION&&l.parts.length===1){let u=l.parts[0];if(u.type===h.VARIABLE){let f=u.path;if(f===r)i.push({key:c,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,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 c=0;c<t.length;c++){let l=t[c];a[c]={id:l.id,title:l.title!=null?String(l.title):"",completed:l.completed}}else for(let c=0;c<t.length;c++){let l=t[c],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=l;else if(f.type==="prop")u[f.key]=l[f.prop];else if(f.type==="item_string")u[f.key]=l!=null?String(l):"";else if(f.type==="prop_string"){let d=l[f.prop];u[f.key]=d!=null?String(d):""}a[c]=u}return a}}return null},Zr=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===h.OBJECT&&s.fast!==!1){let a=e.itemVar,c=e.indexVar;for(let l=0;l<o.length;l++){let u=o[l],f={},d={...r,[a]:u,...c&&{[c]:l}};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}[${l}]`,...c&&{[c]:l}};for(let g of s.properties){let y=g.parsedKey?_(g.parsedKey,t,n,d):g.key,b=g.value;if(b.type===h.LITERAL)f[y]=b.value;else if(b.type===h.VARIABLE){let m=b.path;if(m===a)f[y]=u;else if(m===c)f[y]=l;else if(m.startsWith(a+".")){let I=m.substring(a.length+1);!I.includes(".")&&!I.includes("[")?f[y]=u[I]:f[y]=P(m,n,{...r,[a]:u,...c&&{[c]:l}})}else f[y]=P(m,n,{...r,[a]:u,...c&&{[c]:l}})}else if(b.type===h.INTERPOLATION){let m=[];for(let I of b.parts)if(typeof I=="string")m.push(I);else if(I.type===h.VARIABLE){let x=I.path,w;if(x===a)w=u;else if(x===c)w=l;else if(x.startsWith(a+".")){let R=x.substring(a.length+1);!R.includes(".")&&!R.includes("[")?w=u[R]:w=P(x,n,{...r,[a]:u,...c&&{[c]:l}})}else w=P(x,n,{...r,[a]:u,...c&&{[c]:l}});m.push(w!=null?String(w):"")}else{let x={...r,[a]:u,...c&&{[c]:l}},w=_(I,t,n,x);m.push(w!=null?String(w):"")}f[y]=m.join("")}else{let m={...r,[a]:u,...c&&{[c]:l}};f[y]=_(b,t,n,m)}}i.push(f)}return i}return null},Qr=(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],c=s.properties[1];if(a.key==="id"&&a.value.type===h.VARIABLE&&a.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===h.CONDITIONAL){let l=[];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),l.push(d)}}return l}}}}return null},eo=(e,t,n,r)=>{let o=_(e.iterable,t,n,r);if(!Array.isArray(o)){let l,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(", ");l=`${e.iterable.name}(${d})`}else l=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw fn(f,o,u)}if(!e.indexVar){let l=Qr(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=Jr(e,o);if(l!==null)return l}let i=Zr(e,t,n,r,o);if(i!==null)return i;let s=[],a=e.iterable.path||"";if(r&&r.__paths__&&a){let l=a.split("."),u=l[0];u in r.__paths__&&(a=r.__paths__[u],l.length>1&&(a+="."+l.slice(1).join(".")))}let c=!1;e.body.type===h.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(l=>l.type===h.OBJECT&&l.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let l=0;l<o.length;l++){let u=e.indexVar?{...r,[e.itemVar]:o[l],[e.indexVar]:l}:{...r,[e.itemVar]:o[l]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${a}[${l}]`},e.indexVar&&(u.__paths__[e.indexVar]=l);let f=_(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!c){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},to=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?_(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===h.OBJECT&&s.properties.length<=10&&!s.whenCondition){let a={},c={},l=!0;for(let u of s.properties){let f=u.parsedKey?_(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]=P(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=P(g.path,n,r);p.push(y!=null?String(y):"")}else{l=!1;break}if(!l)break;c[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,b=g.value;if(b.type===h.LITERAL)p[y]=b.value;else if(b.type===h.VARIABLE)p[y]=P(b.path,n,r);else if(b.type===h.INTERPOLATION){let m=[];for(let I of b.parts)if(typeof I=="string")m.push(I);else if(I.type===h.VARIABLE){let x=P(I.path,n,r);m.push(x!=null?String(x):"")}else{l=!1;break}if(!l)break;p[y]=m.join("")}else{l=!1;break}}if(!l)break;c[f]=p}else{l=!1;break}}if(l)return a[i]=c,a}}return null},no=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!ge(e.whenCondition,o,n,r))return;let i=to(e,t,n,r);if(i!==null)return i;if(e.fast){let l={};for(let u of e.properties){let f=u.parsedKey?_(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]=P(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=P(g.path,n,r);p.push(y!=null?String(y):"")}else{let y=_(g,t,n,r);p.push(y!=null?String(y):"")}l[f]=p.join("")}else l[f]=_(d,t,n,r)}return l}let s={},a=null,c=!1;for(let l of e.properties)if(!l.key.startsWith("$if ")&&!l.key.match(/^\$if\s+\w+.*:?$/)&&!l.key.startsWith("$elif")&&!l.key.startsWith("$else")&&!l.key.startsWith("$for ")){c=!0;break}for(let l of e.properties)if(l.key.startsWith("$if ")||l.key.match(/^\$if\s+\w+.*:?$/)){let u=_(l.value,t,n,r);if(!c&&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(l.key.startsWith("$for ")){if(e.properties.length===1)return _(l.value,t,n,r)}else{let u=l.value;if(u&&u.type===h.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=_(f.value,t,n,r);d!==void 0&&(s[l.key]=d)}else{let d=_(l.value,t,n,r);d!==void 0&&(s[l.key]=d)}}else{let f=l.parsedKey?_(l.parsedKey,t,n,r):l.key,d=_(l.value,t,n,r);d!==void 0&&(s[f]=d)}}return s},yn={},ro=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===h.LOOP){let s=_(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=_(i,t,n,r);s!==yn&&s!==void 0&&o.push(s)}return o},oo=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,a=t.partials||{},c=t.functions||t;if(s&&!ge(s,c,n,r))return;if(!a[o])throw new F(`Partial '${o}' is not defined`);let l=r._partialStack||[];if(l.includes(o))throw new F(`Circular partial reference detected: ${o}`);let u=a[o],f=n,d={...r,_partialStack:[...l,o]};if(r){f={...n};for(let p of Object.keys(r))p.startsWith("_")||(f[p]=r[p])}if(i){let p=_(i,t,n,r);f={...f,...p}}return _(u,t,f,d)},io=(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 F(`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 F(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=r.__paths__[s];if(typeof c=="number"){if(a.length>0)throw new F(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return a.length>0&&(c+="."+a.join(".")),c},gt=Yr;var so=/\$\{([^}]*)\}/g,lo=/#\{([^}]*)\}/g,In=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=co(o,t);return{isFunction:!0,type:h.FUNCTION,name:r,args:i}},co=(e,t={})=>e.trim()?ao(e).map(r=>uo(r.trim(),t)):[],ao=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let a=e[s],c=s>0?e[s-1]:"";!o&&(a==='"'||a==="'")?(o=!0,i=a,n+=a):o&&a===i&&c!=="\\"?(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},uo=(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=In(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:c}of o){let l=0;for(;l<r.length;){let u=ie(r.substring(l),a);if(u===-1)break;let f=l+u;f>i&&(i=f,s={op:a,type:c}),l=f+a.length}}if(i!==-1)try{return M(r,t)}catch{return{type:h.VARIABLE,path:r}}return{type:h.VARIABLE,path:r}},xn=/^\w+\(.*\)$/,fo=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,po=e=>{if(!(!e||e.trim()===""||xn.test(e))&&fo.test(e))throw e.includes("?")&&e.includes(":")?new v(`Complex expressions not supported in variable replacements - consider calculating the value in your data instead. Offending expression: "${e}"`):e.includes("||")||e.includes("&&")||e.includes("??")?new v(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new v(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},bn=e=>{let t=e.trim();if(xn.test(t))throw new v(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new v(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new v(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new v(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("?")&&t.includes(":"))throw new v(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:h.PATH_REFERENCE,path:t}},Ae=(e,t={})=>{let n=e.trim();po(n);let r=In(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}},mt=(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,(l,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\(#\{[^}]*\})/g,(l,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(so)],i=[...n.matchAll(lo)],s=[...o.map(l=>({match:l,type:"variable"})),...i.map(l=>({match:l,type:"pathref"}))].sort((l,u)=>l.match.index-u.match.index);if(s.length===0){let l=n;for(let u=0;u<r.length;u++)l=l.replace(`__ESCAPED_${u}__`,r[u]);return{type:h.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===n&&r.length===0){let{match:l,type:u}=s[0];try{return u==="variable"?Ae(l[1],t):bn(l[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:h.LITERAL,value:n};throw f}}let a=[],c=0;for(let{match:l,type:u}of s){let[f,d]=l,p=l.index;if(p>c){let g=n.substring(c,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=Ae(d.trim(),t):g=bn(d.trim()),a.push(g)}catch(g){if(g.message==="Invalid array index syntax")a.push(f);else throw g}c=p+f.length}if(c<n.length){let l=n.substring(c);for(let u=0;u<r.length;u++)l=l.replace(`__ESCAPED_${u}__`,r[u]);l&&a.push(l)}return{type:h.INTERPOLATION,parts:a}};var te=(e,t)=>typeof e=="string"?mt(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?go(e,t):mo(e,t):{type:h.LITERAL,value:e},ho=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new v("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new v("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new v("Empty $each body not allowed");if(n.$partial!==void 0)throw new v("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},go=(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 c=ho(i),l=Object.keys(c);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let u=An(l[0],c[l[0]],t,!0);n.push(u),r=!0;continue}}catch(c){throw c instanceof v?c:new v(c.message)}let a=Object.keys(i);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let c=An(a[0],i[a[0]],t);n.push(c),r=!0;continue}}let s=te(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}},mo=(e,t)=>{let n=[],r=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new v("$partial value must be a string");if(e.$partial.trim()==="")throw new v("$partial value cannot be an empty string");let c=["$if","$elif","$else","$for"],l=[];for(let[m]of i)for(let I of c)if(m===I||m.startsWith(I+" ")||m.startsWith(I+"#")){l.push(I);break}if(l.length>0)throw new v(`Cannot use $partial with ${l.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[m,I]of Object.entries(d)){let x=m;(m.startsWith("\\$")||m.startsWith("$$"))&&(x=m.slice(1)),p[x]=I,g=!0}let y=null;if(g&&(y=te(p,t),y.type===h.OBJECT)){let m=!1;for(let I of y.properties)if(I.value.type===h.VARIABLE||I.value.type===h.INTERPOLATION||I.value.type===h.FUNCTION||I.value.type===h.CONDITIONAL||I.value.type===h.OBJECT&&!I.value.fast||I.value.type===h.ARRAY&&!I.value.fast){m=!0;break}m&&(y.fast=!1)}let b={type:h.PARTIAL,name:u,data:y};if(f!==void 0){let m;if(typeof f=="string"){if(f.trim()==="")throw new v("Empty condition expression after '$when'");m=M(f,t)}else m={type:h.LITERAL,value:f};b.whenCondition=m}return b}for(let[c,l]of i)if(c==="$when"){if(o!==null)throw new v("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new v("Missing condition expression after '$when'");let u=typeof l=="string"?l:JSON.stringify(l);if(u.trim()==="")throw new v("Empty condition expression after '$when'");o=M(u,t),r=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new v("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[c,l]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new v("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=yo(i,s,t);n.push({key:c,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(c)){let u=c.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new v(`$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(c.startsWith("$elif ")||c.startsWith("$else"))throw new v(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new v("Missing condition expression after '$if'");{let u=te(l,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=mt(c,t),d={key:c,value:u};(f.type!==h.LITERAL||f.value!==c)&&(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],c=null,l;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=f[1],l=f[2];else throw new v(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());ht(l);let u=M(l,n);for(r.push(u),o.push(te(a,n)),i++;i<e.length;){let[f,d]=e[i],p=!1,g;if(c?f.startsWith(`$elif#${c} `)?(g=f.substring(`$elif#${c} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),p=!0):(f===`$else#${c}`||f===`$else#${c}:`)&&(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{ht(g);let y=M(g,n);r.push(y)}if(o.push(te(d,n)),i++,g===null)break}else break}return{node:{type:h.CONDITIONAL,conditions:r,bodies:o,id:c},nextIndex:i}},M=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let l=e.slice(1,-1),u=0,f=!0;for(let d=0;d<l.length;d++)if(l[d]==="("?u++:l[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return M(l,t)}let n=ie(e,"||");if(n!==-1)return{type:h.BINARY,op:O.OR,left:M(e.substring(0,n).trim(),t),right:M(e.substring(n+2).trim(),t)};let r=ie(e,"&&");if(r!==-1)return{type:h.BINARY,op:O.AND,left:M(e.substring(0,r).trim(),t),right:M(e.substring(r+2).trim(),t)};let o=[{op:">=",type:O.GTE},{op:"<=",type:O.LTE},{op:"==",type:O.EQ},{op:"!=",type:O.NEQ},{op:">",type:O.GT},{op:"<",type:O.LT},{op:" in ",type:O.IN}];for(let{op:l,type:u}of o){let f=ie(e,l);if(f!==-1)return{type:h.BINARY,op:u,left:M(e.substring(0,f).trim(),t),right:M(e.substring(f+l.length).trim(),t)}}let i=-1,s=null,a=[{op:" + ",type:O.ADD},{op:" - ",type:O.SUBTRACT}];for(let{op:l,type:u}of a){let f=0;for(;f<e.length;){let d=ie(e.substring(f),l);if(d===-1)break;let p=f+d;p>i&&(i=p,s={op:l,type:u}),f=p+l.length}}if(i!==-1&&s)return{type:h.BINARY,op:s.type,left:M(e.substring(0,i).trim(),t),right:M(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let l of c)if(ie(e,l)!==-1)throw new v(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:h.UNARY,op:xe.NOT,operand:M(e.substring(1).trim(),t)}:vn(e,t)},ie=(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},bo=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 Ae(n,t);let o=bo(n);if(o.type===h.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:h.VARIABLE,path:n};try{return Ae(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Io=(e,t=!1)=>{let n=t?"$each":"$for";try{un(e)}catch(r){if(r instanceof v&&t){let o=r.message.replace(/\$for/g,"$each");throw new v(o.replace("Parse Error: ",""))}throw r}},An=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let b=r?"$each":"$for";throw new v(`Invalid loop syntax (got: '${e.replace("$for",b)}')`)}let s=i[1],a=i[2].trim();Io(a,r);let c=a.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let b=r?"$each":"$for";throw new v(`Invalid loop syntax - missing 'in' keyword (got: '${b} ${a}')`)}let l=c[1].trim(),u=c[2].trim(),f,d=null;if(l.includes(",")){let b=l.split(",").map(m=>m.trim());if(b.length!==2)throw new v(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);f=b[0],d=b[1]}else f=l;let p=["this","undefined","null","true","false"];if(p.includes(f))throw new v(`Reserved variable name: ${f}`);if(d&&p.includes(d))throw new v(`Reserved variable name: ${d}`);let g=vn(u,n),y=te(t,n);return{type:h.LOOP,itemVar:f,indexVar:d,iterable:g,body:y,flatten:s!=="nested"}};var xo=(e,t={})=>{let{functions:n={}}=t;return te(e,n)},Me=xo;var yt={};Nr(yt,{now:()=>Ao});var Ao=()=>Date.now();var vo=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...yt,...r},s=Me(e,{functions:i}),a={};for(let[c,l]of Object.entries(o))a[c]=Me(l,{functions:i});return gt(s,t,{functions:i,partials:a})},W=vo;var wn=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:a=c=>c}=n;for(let[c,l]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>l(s(r),...u):i[c]=(...u)=>{r=pt(r,d=>l(a(d),...u))});return{...o,...i}},je=(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 wo=(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{}}},xt=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{let i=wo(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},At=(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(", ")}`)},vt=(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(", ")}`)},wt=(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}`)}},Et=(e,t,n)=>Object.fromEntries(Object.entries(e).filter(([r])=>t?.[r]?.scope===n)),En=(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()))},Eo=(e,t)=>{let n=e?.ui,r=t?.ui;return JSON.stringify(n)===JSON.stringify(r)?null:n&&!r?{changeType:"delete",data:e}:r&&!e?{changeType:"add",data:t}:r&&e?{changeType:"update",data:t}:null},_t=(e={},t={})=>{let n={},r=["sfx","voice"],o=s=>{let a=e[s],c=t[s];c&&!a?n[s]={changeType:"add",data:c}:a&&!c?r.includes(s)||(n[s]={changeType:"delete",data:a}):a&&c&&JSON.stringify(a)!==JSON.stringify(c)&&(n[s]={changeType:"update",data:c})};o("background"),o("bgm"),o("voice");let i=Eo(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},Lt=(e={})=>{let t=structuredClone(e);t.background&&(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);let r=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(a=>{let c={...a};return delete c.animations,i(c)?c: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},_o=(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},Lo=(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=_o(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},So={updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"])},_n=(e,t)=>{let n=e[e.length-1];return n?So[n]?.has(t)===!0:!1},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,_n(n,r)?o:bt(o,t,[...n,r])])):Lo(e,t),It=(e,t,n=[])=>Array.isArray(e)?e.map(r=>It(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,_n(n,r)?o:It(o,t,[...n,r])])):typeof e=="string"?W(e,t):e,Ln=(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=bt(e,t._event);return It(n,t)};var Be=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:structuredClone(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Sn=(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}},Co=()=>({}),Ro=(e,t)=>{if(t.background){let{animationsOnly:n,state:r}=Be(t.background,o=>!!o.resourceId);if(n){e.background=e.background?.resourceId?{...structuredClone(e.background),...r}:r;return}if(!t.background.resourceId){delete e.background;return}e.background=structuredClone(t.background)}else e.background?.animations&&(e.background.animations={})},$o=(e,t)=>{if(!t.dialogue){e.dialogue&&e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,e.dialogue.characterId=void 0);return}if(e.dialogue||(e.dialogue={}),t.dialogue.ui){let{animationsOnly:n,state:r}=Be(t.dialogue.ui,o=>!!o.resourceId);n?e.dialogue.ui={...e.dialogue.ui,...r}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});if(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),delete e.dialogue.characterId,t.dialogue.characterId&&(e.dialogue.characterId=t.dialogue.characterId),t.dialogue.character?e.dialogue.character={...t.dialogue.character}:delete e.dialogue.character,t.dialogue.clear){delete e.dialogue;return}t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0&&e.dialogue.lines.push({content:t.dialogue.content,characterId:t.dialogue.characterId||null})},ko=(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},Oo=(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}}},To=(e,t)=>{if(t.visual){let{hasValidItems:n,processedItems:r}=Sn(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))},Po=(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}=Sn(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);n?e.character={items:r}:delete e.character},No=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Do=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=Be(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},Vo=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=Be(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},Mo=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},jo=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},Bo=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},ve=e=>je(Co,[Bo,Ro,ko,Oo,To,$o,Po,No,Do,Vo,Mo,jo])(e);var le={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:En},Fo=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,Uo=(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},Ue=(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=Fo.exec(s);if(a){let[,c,l,u]=a,f=Uo(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((p,g)=>{let y={...t,[c]:p};l&&(y[l]=g),d.forEach(b=>{let m=Ue(b,y,n),I=W(m,y,n);Array.isArray(I)?o.push(...I):o.push(I)})});continue}}o.push(Ue(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=Ue(i,t,n)}),r},Tt=({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".`)},zo=({id:e,targetId:t,animation:n,animationPath:r="animation"})=>{let o=structuredClone(n);return Tt({animationType:o.type,animationId:e,animationPath:r}),delete o.name,o.id=e,o.targetId=t,o},Wo=(e,{animationId:t="animation",animationPath:n="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Tt({animationType:e.type,animationId:t,animationPath:n}),e.type},Yo=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Ho=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Go=(e,t)=>{if(Ho(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},we=({animations:e,resources:t,animationId:n,instanceId:r,targetId:o,animationPath:i="animation"})=>{if(!n||!o)return!1;let s=t?.animations?.[n];return s?(e.push(zo({id:r,targetId:o,animation:s,animationPath:i})),!0):!1},qo=({hasPrevious:e,hasCurrent:t,previousResourceId:n,currentResourceId:r,sharedTarget:o})=>!e&&t?"enter":e&&!t?"exit":e&&t?n===r&&o?"update":"replace":"none",Ko=({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.`)},Xo=(e,{defaultTargetId:t,defaultId:n,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Tt({animationType:o.type,animationId:o.id??n,animationPath:r}),o.id??=n,o.targetId??=t,o},Pt=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r,animationPathPrefix:o=r})=>{t.forEach((i,s)=>{e.push(Xo(i,{defaultTargetId:n,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Cn=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=W(e,t);return n&&typeof n=="object"?e:n},Rn=(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},$n=(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))},kn=(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("-")}`},St=(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},Jo=(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},On=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},Fe=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Zo=(e={})=>e.textStyles||{},Qo=(e={})=>e.images||{},ei=(e={})=>e.colors||{},ti=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Ee=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,me=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},Tn=(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},Mn=(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},Pn=(e,t,n)=>{let r=Mn(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})`},ni=(e={},t)=>{let n=Zo(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=Tn(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:Pn(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 c=Tn(n.strokeAlpha,"strokeAlpha",t);s.strokeColor=Pn(a.hex,c,`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},$t=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>$t(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]=$t(i,t,Ee(n,o)));return e.textStyleId!==void 0&&(me(e.textStyleId,n,"textStyleId"),r.textStyle=ni(t,e.textStyleId)),r},jn=(e={},t)=>{let n=ei(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return Mn(n.hex,`Color "${t}"`)},Bn=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Ct=(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 ${Bn(`${t}.fill`)} instead`)},ri=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>_e(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]=_e(i,t,Ee(n,o)));return e.colorId!==void 0&&(me(e.colorId,n,"colorId"),r.fill=jn(t,e.colorId)),r},_e=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>_e(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 ${Bn("fill")} instead`);Ct(e,"hover",n),Ct(e,"click",n),Ct(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]=ri(i,t,Ee(n,o));continue}r[o]=_e(i,t,Ee(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(me(e.colorId,n,"colorId"),r.fill=jn(t,e.colorId)),r},Rt=(e={},t)=>{let n=Qo(e)?.[t];return n||null},Fn=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",Nn=(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 ${Fn(`${t}.${r}`)} instead`)},Dn=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},kt=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>kt(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="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 ${Fn(o)} instead`);Nn(e,"hover",n,"src"),Nn(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]=kt(i,t,Ee(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){me(e.imageId,n,"imageId");let o=Rt(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&&(me(e.hoverImageId,n,"hoverImageId"),Dn(r,"hover",Rt(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(me(e.clickImageId,n,"clickImageId"),Dn(r,"click",Rt(t,e.clickImageId)?.fileId??e.clickImageId)),r},Nt=(e,t={},n="root")=>kt(_e($t(e,t,n),t,n),t,n),ce=Nt,We=(e=[])=>e.find(t=>t.id==="story");var oi=(e={})=>e?.muteAll?0:e?.musicVolume??50,X=({variables:e,runtime:t,saveSlots:n=[],isLineCompleted:r,autoMode:o,skipMode:i,isChoiceVisible:s,canRollback:a,confirmDialog:c,historyDialogue:l=[],characters:u={},dialogueUIHidden:f,skipOnlyViewedLines:d,skipTransitionsAndAnimations:p}={})=>{let g={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??o??!1,skipMode:t?.skipMode??i??!1,dialogueUIHidden:t?.dialogueUIHidden??f??!1,isLineCompleted:t?.isLineCompleted??r??!1};return{variables:e,runtime:g,saveSlots:n,isChoiceVisible:s,canRollback:a,confirmDialog:c,historyDialogue:l,characters:u}},Vn=100,ze=(e,t)=>{if(Array.isArray(e))return e.map(r=>ze(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=ze(n[r],t)}),n.type==="text-revealing"?t(n):n},ii=e=>ze(e,t=>({...t,revealEffect:"none"})),si=e=>ze(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,Vn):Vn;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?ii(e):n?si(e):e,Un=({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:{}}}}),Ot=e=>{if(Array.isArray(e))return e.map(Ot);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Ot(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}}:{}}}}},zn=(e=[],t={})=>e.map(n=>{let r=t?.[n.characterId],o=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(i=>i?.text??"").join(""):"";return{...n,text:o,characterName:r?.name||""}}),Wn=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=W(e,n,{functions:le});return ce(ae(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},li=(e={})=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{payload:{actions:structuredClone(n?.actions||{})}}]))},se=({animations:e,animationsDef:t,resources:n,previousResourceId:r,currentResourceId:o,previousTargetId:i,currentTargetId:s,animationPath:a,idPrefix:c,allowIncomingUpdateFallback:l=!1})=>{if(!t)return;let u=r!=null&&r!==!1,f=o!=null&&o!==!1,d=i&&s&&i===s,p=qo({hasPrevious:u,hasCurrent:f,previousResourceId:r,currentResourceId:o,sharedTarget:d});Go(t,a);let g=Yo(t),y=n?.animations?.[g],b=Wo(y,{animationId:g,animationPath:a}),m=l&&b==="update"&&p!=="update"&&f&&s;if(m||Ko({animationType:b,animationId:g,animationPath:a,lifecycle:p}),b==="update"){u&&f&&r===o&&d?we({animations:e,resources:n,animationId:g,instanceId:`${c}-animation-update`,targetId:s,animationPath:a}):m&&we({animations:e,resources:n,animationId:g,instanceId:`${c}-animation-update`,targetId:s,animationPath:a});return}if(b==="transition"){if(u&&f&&d){we({animations:e,resources:n,animationId:g,instanceId:`${c}-animation-transition`,targetId:s,animationPath:a});return}u&&we({animations:e,resources:n,animationId:g,instanceId:`${c}-animation-out`,targetId:i,animationPath:a}),f&&we({animations:e,resources:n,animationId:g,instanceId:`${c}-animation-in`,targetId:s,animationPath:a})}},ci=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),ai=(e,{presentationState:t,previousPresentationState:n,resources:r={},screen:o={width:1920,height:1080},isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,runtime:c,autoMode:l,skipMode:u,isChoiceVisible:f,canRollback:d,saveSlots:p=[]})=>{let{elements:g,animations:y}=e;if(t.background){let b=g.find(E=>E.id==="story");if(!b)return e;let m=Jo(r,t.background),I=n?.background?.resourceId,x=t.background.resourceId??(t.background.animations?I:void 0),w=On(r,I),R=On(r,x);if(x){let{images:E={},videos:L={}}=r,$=E[x]||L[x];if($){let A=L[x]!==void 0,k={x:(o?.width??1920)/2,y:(o?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...m},B={id:Fe({resourceId:x,kind:A?"video":"sprite"}),type:A?"video":"sprite",x:k.x,y:k.y,src:$.fileId,width:$.width,height:$.height,alpha:1,anchorX:k.anchorX,anchorY:k.anchorY,rotation:k.rotation,scaleX:k.scaleX,scaleY:k.scaleY};A&&(B.loop=t.background.loop??!1,B.volume=$.volume??50),b.children.push(B)}}if(x){let{layouts:E={}}=r,L=E[x];if(L){let $={id:Fe({resourceId:x,kind:"container"}),type:"container",children:L.elements};m&&Object.assign($,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...m});let A=W($,X({variables:a,runtime:c,saveSlots:p,isLineCompleted:i,autoMode:l,skipMode:u,isChoiceVisible:f,canRollback:d,skipTransitionsAndAnimations:s}),{functions:le});b.children.push(ce(ae(A,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r))}}t.background.animations&&!i&&!s&&se({animations:y,animationsDef:t.background.animations,resources:r,previousResourceId:I,currentResourceId:x,previousTargetId:Fe({resourceId:I,kind:w}),currentTargetId:Fe({resourceId:x,kind:R}),animationPath:"background.animations",idPrefix:"bg-cg",allowIncomingUpdateFallback:!0})}return e},ui=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i})=>{let{elements:s,animations:a}=e;if(t.character&&r){let c=s.find(p=>p.id==="story");if(!c)return e;let l=t.character.items||[],u=n?.character?.items||[],f=$n(l),d=$n(u);for(let p=0;p<l.length;p++){let g=l[p],{transformId:y,sprites:b}=g,m=u.find(A=>A.id===g.id),I=u.findIndex(A=>A.id===g.id),x=m?.sprites&&m.sprites.length>0,w=b&&b.length>0,R=I>=0?kn(m,I,d):void 0;if(g.animations&&!b&&!y&&x&&!o&&!i){se({animations:a,animationsDef:g.animations,resources:r,previousResourceId:R,currentResourceId:void 0,previousTargetId:R,currentTargetId:void 0,animationPath:`character.items[${p}].animations`,idPrefix:"character"});continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let E=kn(g,p,f),L=r.transforms[y];if(!L){console.warn("Transform not found:",y);continue}let $={type:"container",id:E,x:g.x??L.x,y:g.y??L.y,anchorX:L.anchorX,anchorY:L.anchorY,rotation:L.rotation,scaleX:L.scaleX,scaleY:L.scaleY,children:[]};for(let A of b){let k=r.images[A.resourceId];if(!k){console.warn(`Image resource not found: ${A.resourceId}`);continue}$.children.push({type:"sprite",id:`${E}-${A.id}`,src:k.fileId,width:k.width,height:k.height,x:0,y:0})}c.children.push($),g.animations&&!o&&!i&&se({animations:a,animationsDef:g.animations,resources:r,previousResourceId:R,currentResourceId:E,previousTargetId:R,currentTargetId:E,animationPath:`character.items[${p}].animations`,idPrefix:"character"})}}return e},fi=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:a,autoMode:c,skipMode:l,isChoiceVisible:u,canRollback:f,saveSlots:d=[]})=>{let{elements:p,animations:g}=e;if(t.visual&&r){let y=p.find(m=>m.id==="story");if(!y)return e;let b=t.visual.items;for(let m of b){if(m.resourceId){let{images:I={},videos:x={},spritesheets:w={}}=r,R=w[m.resourceId];if(R){let E=St(r,m),L=m.animationName;if(L){let $=R.animations?.[L];if(!$)throw new Error(`Animation '${L}' not found in spritesheet resource '${m.resourceId}'`);let A={id:`visual-${m.id}`,type:"animated-sprite",x:m.x??E.x,y:m.y??E.y,width:m.width??R.width,height:m.height??R.height,alpha:m.alpha??1,anchorX:E.anchorX,anchorY:E.anchorY,rotation:E.rotation,scaleX:E.scaleX,scaleY:E.scaleY,spritesheetSrc:R.fileId,spritesheetData:R.jsonData,animation:{frames:$.frames,animationSpeed:m.animationSpeed??$.animationSpeed??.5,loop:m.loop??$.loop??!0}};y.children.push(structuredClone(A))}}else{let E=I[m.resourceId]||x[m.resourceId];if(E){let L=x[m.resourceId]!==void 0,$=St(r,m),A={id:`visual-${m.id}`,type:L?"video":"sprite",src:E.fileId,width:E.width,height:E.height,x:$.x,y:$.y,anchorX:$.anchorX,anchorY:$.anchorY,rotation:$.rotation,scaleX:$.scaleX,scaleY:$.scaleY};L&&(A.loop=E.loop??!1,A.volume=E.volume??50),y.children.push(A)}}}if(m.resourceId){let{layouts:I={}}=r,x=I[m.resourceId];if(x){let w=St(r,m),R={id:`visual-${m.id}`,type:"container",children:structuredClone(x.elements),x:w.x,y:w.y,anchorX:w.anchorX,anchorY:w.anchorY,rotation:w.rotation,scaleX:w.scaleX,scaleY:w.scaleY},E=W(R,X({variables:s,runtime:a,saveSlots:d,isLineCompleted:o,autoMode:c,skipMode:l,isChoiceVisible:u,canRollback:f,skipTransitionsAndAnimations:i}),{functions:le});y.children.push(ce(ae(E,{isLineCompleted:o,skipMode:l,skipTransitionsAndAnimations:i}),r))}}if(m.animations&&!o&&!i){let x=(n?.visual?.items||[]).find(w=>w.id===m.id);se({animations:g,animationsDef:m.animations,resources:r,previousResourceId:x?.resourceId,currentResourceId:m.resourceId,previousTargetId:x?.resourceId?`visual-${m.id}`:void 0,currentTargetId:m.resourceId?`visual-${m.id}`:void 0,animationPath:`visual.items[${m.id}].animations`,idPrefix:m.id})}}}return e},di=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:c,skipOnlyViewedLines:l,isLineCompleted:u,skipTransitionsAndAnimations:f,variables:d,runtime:p,saveSlots:g=[]})=>{let{elements:y,animations:b}=e;if(!t.dialogue||o)return e;let m=y.find(I=>I.id==="story");if(!m)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:I={}}=r,x=I[t.dialogue.ui.resourceId];if(x){let w;t.dialogue.characterId&&(w=r.characters[t.dialogue.characterId]),t.dialogue.character&&(w={...w,name:t.dialogue.character.name});let R={elements:x.elements},E=t.dialogue?.content===void 0?[{text:""}]:Rn(t.dialogue.content,"dialogue.content"),L=(t.dialogue?.lines||[]).map((T,Y)=>({content:Rn(T.content,`dialogue.lines[${Y}].content`).map(V=>({...V,text:Cn(V.text,{variables:d})})),characterName:T.characterId&&r.characters?.[T.characterId]?.name||""})),$=X({variables:d,runtime:p,isLineCompleted:u,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:c,dialogueUIHidden:o,skipOnlyViewedLines:l,skipTransitionsAndAnimations:f}).runtime,A={variables:d,runtime:$,isChoiceVisible:a,canRollback:c,saveSlots:g,dialogueLines:L,dialogue:{character:{name:w?.name||""},content:E.map(T=>({...T,text:Cn(T.text,{variables:d})})),lines:L}},k={functions:le},B=Ue(R,A,k),S=W(B,A,k),C=ce(ae(S?.elements,{isLineCompleted:u,skipMode:s,skipTransitionsAndAnimations:f}),r);if(Array.isArray(C))for(let T of C)m.children.push(T);else C&&m.children.push(C)}}return t.dialogue.ui?.animations&&!u&&!f&&se({animations:b,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"}),e},pi=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,runtime:c,autoMode:l,skipMode:u,isChoiceVisible:f,canRollback:d,saveSlots:p=[]})=>{let{elements:g,animations:y}=e;if(t.choice&&r){let b=We(g);if(!b)return e;let m=r?.layouts[t.choice.resourceId];if(m&&m.elements){let I={elements:m.elements},x=W(I,{...X({variables:a,runtime:c,saveSlots:p,isLineCompleted:i,autoMode:l,skipMode:u,isChoiceVisible:f??!!t.choice,canRollback:d,skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:le}),w=Ot(ce(ae(x?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r));if(Array.isArray(w))for(let R of w)b.children.push(R);else w&&b.children.push(w)}t.choice.animations&&!i&&!s&&se({animations:y,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"})}return e},hi=(e,{presentationState:t,resources:n={},variables:r,runtime:o,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,canRollback:l,saveSlots:u=[],skipTransitionsAndAnimations:f})=>{if(!t.control?.resourceId)return e;let d=n.controls?.[t.control.resourceId];if(!d)return e;let p=li(d.keyboard);if(p&&Object.keys(p).length>0&&(e.global.keyboard=p),!Array.isArray(d.elements)||d.elements.length===0)return e;let g=We(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(Wn({container:y,resources:n,templateData:X({variables:r,runtime:o,saveSlots:u,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,canRollback:l,skipTransitionsAndAnimations:f}),isLineCompleted:i,skipMode:a,skipTransitionsAndAnimations:f})),e},gi=(e,{presentationState:t,resources:n,runtime:r,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&n){if(!We(i))return e;let c=n.sounds[t.bgm.resourceId];if(!c)return e;let l=X({variables:o,runtime:r}).runtime;s.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:oi(l),delay:t.bgm.delay??null})}return e},mi=(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},yi=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(!t?.voice)return e;let{fileId:o,volume:i,loop:s}=t.voice;return r.push({id:`voice-${o}`,type:"sound",src:o,volume:i??50,loop:s??!1}),e},bi=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,runtime:i,autoMode:s,skipMode:a,isChoiceVisible:c,canRollback:l,saveSlots:u=[],isLineCompleted:f,skipTransitionsAndAnimations:d})=>{let{elements:p,animations:g}=e;if(t.layout){let y=We(p);if(!y)return e;let b=r.layouts[t.layout.resourceId];if(!b)return e;Array.isArray(b.transitions)&&!f&&!d&&Pt({animations:g,transitions:b.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let m={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:b.elements||[]};y.children.push(Wn({container:m,resources:r,templateData:X({variables:o,runtime:i,saveSlots:u,isLineCompleted:f,autoMode:s,skipMode:a,isChoiceVisible:c,canRollback:l,skipTransitionsAndAnimations:d}),isLineCompleted:f,skipMode:a,skipTransitionsAndAnimations:d}))}if(t.layout?.animations&&!f&&!d){let y=n?.layout?.resourceId,b=t.layout?.resourceId;se({animations:g,animationsDef:t.layout.animations,resources:r,previousResourceId:y,currentResourceId:b,previousTargetId:y?`layout-${y}`:void 0,currentTargetId:b?`layout-${b}`:void 0,animationPath:"layout.animations",idPrefix:"layout"})}return e},Ii=(e,{resources:t={},variables:n,runtime:r,autoMode:o,skipMode:i,isChoiceVisible:s,canRollback:a,overlayStack:c=[],dialogueHistory:l=[],saveSlots:u=[],screen:f,isLineCompleted:d,skipTransitionsAndAnimations:p})=>{let{elements:g,animations:y}=e;return c&&c.length>0&&c.forEach((b,m)=>{let I=t.layouts[b.resourceId];if(!I){console.warn(`Overlay layout not found: ${b.resourceId}`);return}Array.isArray(I.transitions)&&(p||Pt({animations:y,transitions:I.transitions,defaultTargetId:`overlayStack-${m}`,idPrefix:`overlayStack-${m}`,animationPathPrefix:`overlayStack[${m}]`}));let x={id:`overlayStack-${m}`,type:"container",x:0,y:0,children:[Un({id:`overlayStack-${m}-blocker`,screen:f}),...I.elements||[]]},w=zn(l,t.characters),R=X({variables:n,runtime:r,saveSlots:u,isLineCompleted:d,autoMode:o,skipMode:i,isChoiceVisible:s,canRollback:a,historyDialogue:w,characters:t.characters||{},skipTransitionsAndAnimations:p}),E=W(x,R,{functions:le}),[L,...$]=E.children||[],A=ce(ae({...E,children:$},{isLineCompleted:d,skipMode:i,skipTransitionsAndAnimations:p}),t);g.push({...A,children:L?[L,...A.children||[]]:A.children})}),e},xi=(e,{resources:t={},variables:n,runtime:r,saveSlots:o=[],autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:c,confirmDialog:l,dialogueHistory:u=[],screen:f,isLineCompleted:d,skipTransitionsAndAnimations:p})=>{let{elements:g,animations:y}=e;if(!l?.resourceId)return e;let b=t.layouts?.[l.resourceId];if(!b)return console.warn(`ConfirmDialog layout not found: ${l.resourceId}`),e;Array.isArray(b.transitions)&&!p&&Pt({animations:y,transitions:b.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let m={id:"confirmDialog",type:"container",x:0,y:0,children:[Un({id:"confirmDialog-blocker",screen:f}),...b.elements||[]]},I=zn(u,t.characters),x=W(m,X({variables:n,runtime:r,saveSlots:o,isLineCompleted:d,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:c,confirmDialog:l,historyDialogue:I,characters:t.characters||{},skipTransitionsAndAnimations:p}),{functions:le}),[w,...R]=x.children||[],E=ce(ae({...x,children:R},{isLineCompleted:d,skipMode:s,skipTransitionsAndAnimations:p}),t);return g.push({...E,children:w?[w,...E.children||[]]:E.children}),e},Yn=e=>je(ci,[hi,ai,ui,fi,di,pi,bi,gi,mi,yi,Ii,xi])(e);var Ai=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"}}),Ye=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),Le=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Hn=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"}),Dt=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Vt=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),vi=(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]}},Mt=e=>Object.fromEntries(Object.entries(Ai).map(([t,n])=>{let r=vi(e,n.source),o=r!==void 0?r:Ye[t]??Le[t];return[t,o]})),J=(e,t)=>Mt(e)[t],Gn=(e={})=>Object.fromEntries(Dt.map(t=>[t,e[t]??Ye[t]]));var He={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Zn=1,Ke=()=>({manual:{...He.manual},auto:{...He.auto},applyMode:He.applyMode}),jt=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...Ke()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},D=e=>{let t=ee(e)?dt(e):e;return structuredClone(t)},N=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Xe=e=>String(e),Bt=()=>({sections:[],resources:[]}),Ge=()=>({sectionId:void 0,lineId:void 0}),wi=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Ei=()=>({resourceId:void 0}),_i=e=>{if(!N(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},Qn=(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}},er=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)}}},tr=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},nr=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Zn)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Li=(e,t={})=>{let n;try{n=nr(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:tr(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},Si=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Li(t,n)])),rr=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:n})=>Js(n));return t.length>0?t:void 0},Ci=e=>{!N(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!N(t))return;let n=rr(t.executedActions);if(n){t.executedActions=n;return}delete t.executedActions})},qn=(e,t,n)=>{let r=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[r]:String(e)};if(!N(e))throw new Error(`Malformed save slot viewedRegistry.${t}[${n}] entry.`);if(typeof e[r]!="string"||e[r].length===0)throw new Error(`Malformed save slot viewedRegistry.${t}[${n}] entry: missing ${r}.`);if(t==="sections"){let o={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed save slot viewedRegistry.sections[${n}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(o.lastLineId=e.lastLineId),o}return{resourceId:e.resourceId}},Ri=e=>{if(e===void 0)return Bt();if(!N(e))throw new Error("Malformed save slot viewedRegistry.");if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error("Malformed save slot viewedRegistry.sections.");if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error("Malformed save slot viewedRegistry.resources.");let t=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(t.map((r,o)=>{let i=qn(r,"sections",o);return[i.sectionId,i]}))),resources:Object.values(Object.fromEntries(n.map((r,o)=>{let i=qn(r,"resources",o);return[i.resourceId,i]})))}},Ft=(e,t,n)=>{if(!N(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}=Qn(t,r);if(!s)throw new Error(`Malformed save slot ${n}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(c=>c.id===o))throw new Error(`Malformed save slot ${n}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},$i=(e,t)=>{if(!N(e)||typeof e.sectionId!="string"||e.sectionId.length===0||typeof e.lineId!="string"||e.lineId.length===0)return Ge();try{let n=Ft(e,t,"contexts[*].pointers.history");return{sectionId:n.sectionId,lineId:n.lineId}}catch{return Ge()}},ki=(e,t,n)=>{if(!N(e)||!Array.isArray(e.timeline))return Se({pointer:t,replayStartIndex:1});let r=e.timeline.flatMap((a,c)=>{if(!N(a))return[];try{let l=Ft(a,n,`rollback.timeline[${c}]`),u=qe({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:a.rollbackPolicy}),f=rr(D(a.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(r.length===0)return Se({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(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);a>=0?o=a:(r.push(qe({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}},Oi=(e,t,n)=>{if(!N(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=zt(t),o=Ft(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!N(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);if(e.runtime!==void 0&&!N(e.runtime))throw new Error(`Malformed save slot contexts[${n}].runtime entry.`);let i=$i(e.pointers?.history,t),s=e.variables?D(e.variables):{},a=Vi({loadedContextRuntime:N(e.runtime)?D(e.runtime):{}}),c={currentPointerMode:e.currentPointerMode==="history"&&i.lineId?"history":"read",pointers:{read:o,history:i},configuration:N(e.configuration)?D(e.configuration):{},views:Array.isArray(e.views)?D(e.views):[],bgm:N(e.bgm)?D(e.bgm):{resourceId:void 0},variables:{...r,...s},rollback:ki(e.rollback,o,t)};return a&&(c.runtime=a),c},Ti=(e,t)=>{if(!N(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{viewedRegistry:Ri(e.viewedRegistry),contexts:e.contexts.map((n,r)=>Oi(n,t,r))}},Pi=(e,t)=>{if(!N(e))throw new Error("Malformed save slot.");let n=nr(e.formatVersion);return{...e,formatVersion:n,state:Ti(e.state,t)}},Kn=(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=D(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},Ni=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Kn(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Kn(e.cancelActions,"cancelActions")}},ye=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},ue=[],Xn="line",Ut="interaction",qe=({sectionId:e,lineId:t,rollbackPolicy:n})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free"}),zt=e=>{let{contextVariableDefaultValues:t}=xt(e??{});return D(t)},or=()=>({...D(Le)}),ir=({loadedRuntime:e,runtimeIds:t,defaults:n={},path:r})=>{if(e===void 0)return{runtimeState:D(n),hasLoadedValues:!1};if(!N(e))throw new Error(`Malformed ${r}.`);let o=D(n),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=lr(s,D(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Di=({loadedGlobalRuntime:e={}})=>ir({loadedRuntime:e,runtimeIds:Dt,defaults:Ye,path:"global.runtime"}).runtimeState,Vi=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:n}=ir({loadedRuntime:e,runtimeIds:Vt,defaults:or(),path:"context.runtime"});return n?t:void 0},sr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Mi=e=>e.runtime?(Vt.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=D(Le[t]))}),e.runtime):(e.runtime=or(),e.runtime),ji=e=>Gn(e.global),Bi=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:ji(e)}})},Fi=e=>Hn[e],Ui=(e,t)=>{let n=Fi(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}"`)},lr=(e,t)=>(Ui(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),cr=(e,t,n)=>{let r=lr(t,n);if(t in Le){let o=sr(e);if(!o)return r;let i=Mi(o);return i[t]=r,r}return e.global[t]=r,r},ar=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:D(e),history:Ge()},configuration:{},views:[],bgm:Ei(),variables:zt(t),rollback:Se({pointer:e})}),zi=e=>{let t=e.contexts?.[e.contexts.length-1],n=t?.pointers?.read;if(!t||!n?.sectionId||!n?.lineId)return null;let r=ar({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=r,Wi(e),r},Wi=e=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,ye(e),e.global.viewedRegistry=Bt(),e.global.nextLineConfig=Ke(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})},ur=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},Se=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[qe({sectionId:e.sectionId,lineId:e.lineId})]:[]}},de=(e,t={})=>{if(e?.rollback)return ur(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=Se({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},Wt=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=de(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(qe(t)),r.currentIndex=r.timeline.length-1},Yi=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=ue[ue.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)},Hi=({state:e},t={})=>{let n=t?.source===Xn?Xn:Ut,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?(ue.push({checkpointIndex:null,source:n}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),ue.push({checkpointIndex:o.currentIndex,source:n}),e)},Gi=({state:e})=>(ue.pop(),e),Z=(e,t,n)=>{let o=ue[ue.length-1]?.source??Ut;if(!Zs(t,o))return;let i=Yi(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:D(n)}))},Jn=(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],c=a?.scope,l=a?.type;At(c,o),vt(l,i,o),c==="context"&&(n.variables[o]=wt(n.variables[o],i,s))}},qi=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:n,payload:r})=>{Qs(e,n,r)})},Ki=(e,t)=>{let{sectionId:n,lineId:r}=t,s=j({state:e},{sectionId:n})?.lines?.find(a=>a.id===r)?.actions;s&&Object.entries(s).forEach(([a,c])=>{el(e,a,c)})},fr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=de(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Re({state:e}),e.global.skipMode&&fe({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=zt(e.projectData),delete n.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=D(He),e.global.overlayStack=[],ye(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let s=i;s<=t;s++)s>i&&jt(e),Ki(e,r.timeline[s]),qi(e,r.timeline[s]);n.pointers.read={sectionId:o.sectionId,lineId:o.lineId},n.currentPointerMode="read",n.pointers?.history&&(n.pointers.history={sectionId:null,lineId:null}),e.global.pendingEffects=e.global.pendingEffects.filter(s=>s?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},Xi=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={},runtime:i={}}=n;er(t);let s=t.story.initialSceneId,a=t.story.scenes[s],c=a.initialSectionId,l=a.sections[c],u={sceneId:s,sectionId:c,lineId:l.initialLineId??l.lines[0].id},{globalVariablesDefaultValues:f}=xt(t),d={...f,...o};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,viewedRegistry:Bt(),nextLineConfig:Ke(),saveSlots:Si(r),overlayStack:[],variables:d,...Di({loadedGlobalRuntime:i})},contexts:[ar({pointer:u,projectData:t})]}},Ji=({state:e})=>e.global.overlayStack||[],Zi=({state:e})=>e.global.pendingEffects,dr=({state:e})=>e.global.skipMode,Qi=({state:e})=>e.global.autoMode,pr=({state:e})=>e.global.dialogueUIHidden,hr=({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=j({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(l=>l.id===o);return i.lines.slice(0,s+1).filter(l=>l.actions?.dialogue).map(l=>{let u=l.actions.dialogue,f="";return u.characterId&&(f=e.projectData.resources?.characters?.[u.characterId]?.name||""),{sectionId:r,lineId:l.id,content:u.content,text:wi(u.content),characterId:u.characterId,characterName:f}})},es=({state:e})=>e.global.confirmDialog??null,Yt=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.global.viewedRegistry.sections.find(c=>c.sectionId===n);if(!o)return!1;if(o.lastLineId===void 0||r===void 0)return!0;let i=j({state:e},{sectionId:n});if(!i||!i.lines||!Array.isArray(i.lines))return o.lastLineId===r;let s=i.lines.findIndex(c=>c.id===o.lastLineId),a=i.lines.findIndex(c=>c.id===r);return s===-1||a===-1?o.lastLineId===r:a<=s},ts=({state:e},t)=>{let{resourceId:n}=t;return!!e.global.viewedRegistry.resources.find(o=>o.resourceId===n)},ns=({state:e})=>e.global.nextLineConfig,gr=({state:e,pointer:t}={})=>{let n=t??q({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=j({state:e},{sectionId:r})?.lines||[],a=s.findIndex(l=>l.id===o);if(a<0)return;let c;for(let l of s.slice(0,a+1)){let u=l?.actions;if(u?.cleanAll&&(c=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){c=void 0;continue}let f=u.choice;if(f?.resourceId){c=f.resourceId;continue}f?.animations||(c=void 0)}return c},K=({state:e})=>!!gr({state:e}),rs=({state:e})=>structuredClone(e),mr=({state:e})=>e.global.saveSlots,os=({state:e},t)=>{let n=t?.slotId,r=Xe(n);return e.global.saveSlots[r]},Ht=({state:e})=>Mt(e),is=({state:e},t)=>J(e,t?.runtimeId),yr=({state:e})=>({...e.global?.variables??{},...sr(e)?.variables??{}}),q=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(!n)return;let r=n.pointers?.[n.currentPointerMode];return{currentPointerMode:n.currentPointerMode,pointer:r}},j=({state:e},t)=>{let{sectionId:n}=t;return Qn(e.projectData,n).section},br=({state:e})=>{let t=q({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=j({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},Ir=({state:e})=>{let{sectionId:t,lineId:n}=q({state:e}).pointer,o=j({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===n),a=o.slice(0,i+1).map(l=>{let u=l.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return ve(a)},ss=({state:e})=>{let t=xr({state:e}),r=br({state:e})?.actions??{},o=ve([t??{},r]);return _t(t??{},o??{})},ls=({state:e},{sectionId:t})=>{let n=j({state:e},{sectionId:t});if(!n?.lines)return{lines:[]};let r=[],o={};for(let i of n.lines){let s=i.actions||{},a=ve([o,s]),c=_t(o,a);r.push({id:i.id,changes:c}),o=Lt(a)}return{lines:r}},xr=({state:e})=>{let{sectionId:t,lineId:n}=q({state:e}).pointer,o=j({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n);if(i<=0)return null;let a=o.slice(0,i).map(c=>{let l=c.actions||{},u={};return Object.keys(l).forEach(f=>{u[f]=l[f]}),u});return Lt(ve(a))},Gt=({state:e},{slotsPerPage:t=6}={})=>{let o=((Ht({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let a=o+s,c=e.global.saveSlots&&e.global.saveSlots[Xe(a)]||{};i.push({...c,slotId:a})}return{saveSlots:i}},cs=mr,as=Gt,us=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},fs=({state:e})=>{let t=Ir({state:e}),n=xr({state:e}),r=Ht({state:e}),o=yr({state:e}),{saveSlots:i}=Gt({state:e}),s=us(e);return Yn({presentationState:t,previousPresentationState:n,resources:e.projectData.resources,screen:e.projectData.screen,dialogueUIHidden:r.dialogueUIHidden,autoMode:r.autoMode,skipMode:r.skipMode,isChoiceVisible:K({state:e}),canRollback:Sr({state:e}),skipOnlyViewedLines:!r.skipUnseenText,isLineCompleted:r.isLineCompleted,skipTransitionsAndAnimations:!!r.skipTransitionsAndAnimations||s,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,dialogueHistory:hr({state:e}),saveSlots:i,variables:o,runtime:r})},ds=({state:e},t)=>(e.global.confirmDialog=Ni(t),e.global.pendingEffects.push({name:"render"}),e),ps=({state:e})=>(e.global.confirmDialog&&(ye(e),e.global.pendingEffects.push({name:"render"})),e),hs=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Z(e,"pushOverlay",t),e),gs=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Z(e,"popOverlay",void 0),e),ms=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),Z(e,"replaceLastOverlay",t),e),ys=({state:e})=>(e.global.overlayStack=[],ye(e),e.global.pendingEffects.push({name:"render"}),Z(e,"clearOverlays",void 0),e),bs=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"})},Je=(e,t)=>{e.global.isLineCompleted=!1;let n=!!gr({state:e,pointer:t});return n&&bs(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:n}},Ar=({state:e})=>(K({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:J(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),Re=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Is=({state:e})=>{let t=e.global.autoMode;return K({state:e})&&!t||(t?Re({state:e}):Ar({state:e})),e},vr=({state:e})=>(K({state:e})||(e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode=!0,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"startSkipNextTimer"}),e.global.pendingEffects.push({name:"render"})),e),fe=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),xs=({state:e})=>{let t=dr({state:e});return K({state:e})&&!t||(t?fe({state:e}):vr({state:e})),e},Ze=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Z(e,"showDialogueUI",void 0),e),wr=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Z(e,"hideDialogueUI",void 0),e),As=({state:e})=>(pr({state:e})?Ze({state:e}):wr({state:e}),e),pe=(e,t,n)=>(cr(e,t,n),Bi(e),e.global.pendingEffects.push({name:"render"}),e),$e=(e,t,n,r)=>{let o=cr(e,t,n);return e.global.pendingEffects.push({name:"render"}),Z(e,r,{value:o}),e},vs=({state:e},t)=>pe(e,"dialogueTextSpeed",t?.value),ws=({state:e},t)=>pe(e,"autoForwardDelay",t?.value),Es=({state:e},t)=>pe(e,"skipUnseenText",t?.value),_s=({state:e},t)=>pe(e,"skipTransitionsAndAnimations",t?.value),Ls=({state:e},t)=>pe(e,"soundVolume",t?.value),Ss=({state:e},t)=>pe(e,"musicVolume",t?.value),Cs=({state:e},t)=>pe(e,"muteAll",t?.value),Rs=({state:e},t)=>$e(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),$s=({state:e})=>{let t=J(e,"saveLoadPagination")+1;return $e(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},ks=({state:e})=>{let t=J(e,"saveLoadPagination")-1;return $e(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},Os=({state:e},t)=>$e(e,"menuPage",t?.value,"setMenuPage"),Ts=({state:e},t)=>$e(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Ps=({state:e})=>(e.global.pendingEffects=[],e),Ns=({state:e},t)=>(e.global.pendingEffects.push(t),e),Er=(e,{sectionId:t,resetStoryState:n=!1})=>{let r=j({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&&!zi(e))return e;e.global.autoMode&&Re({state:e}),e.global.skipMode&&fe({state:e});let i=e.contexts?.[e.contexts.length-1];return i&&(i.rollback||de(i,{compatibilityAnchor:!0}),i.pointers.read={sectionId:t,lineId:o.id},n?i.rollback=Se({pointer:i.pointers.read}):Wt(e,{sectionId:t,lineId:o.id})),Je(e,i?.pointers?.read),e},Ds=({state:e},t)=>Er(e,{sectionId:t?.sectionId,resetStoryState:!0}),Ce=(e,{sectionId:t,lineId:n})=>{e.global.viewedRegistry||(e.global.viewedRegistry={}),Array.isArray(e.global.viewedRegistry.sections)||(e.global.viewedRegistry.sections=[]);let r=e.global.viewedRegistry.sections.find(o=>o.sectionId===t);if(r){let o=j({state:e},{sectionId:t});if(o?.lines&&r.lastLineId!==void 0){let i=o.lines.findIndex(a=>a.id===r.lastLineId),s=o.lines.findIndex(a=>a.id===n);(i===-1||s>i)&&(r.lastLineId=n)}else r.lastLineId=n}else e.global.viewedRegistry.sections.push({sectionId:t,lastLineId:n})},Vs=({state:e},t)=>(Ce(e,t),e.global.pendingEffects.push({name:"render"}),e),Ms=({state:e},t)=>{let{resourceId:n}=t;return e.global.viewedRegistry.resources.find(o=>o.resourceId===n)||e.global.viewedRegistry.resources.push({resourceId:n}),e.global.pendingEffects.push({name:"render"}),e},_r=({state:e},t)=>{let n=_i(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 c=e.global.nextLineConfig.auto?.enabled,l=K({state:e});return!a&&!l&&c===!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&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),Z(e,"setNextLineConfig",t),e},js=({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=Xe(n),s=D(e.contexts);s?.forEach(l=>{ur(l.rollback),Ci(l.rollback)});let a={contexts:s,viewedRegistry:D(e.global.viewedRegistry)},c={formatVersion:Zn,slotId:tr(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:a};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Bs=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=Xe(n),o=e.global.saveSlots[r];if(o){let i=Pi(o,e.projectData);e.global.viewedRegistry=i.state.viewedRegistry,e.contexts=i.state.contexts,e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=Ke(),e.global.overlayStack=[],e.global.isLineCompleted=!0,ye(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},Fs=({state:e},t)=>{let{projectData:n}=t;return er(n),e.projectData=n,ye(e),e.global.pendingEffects.push({name:"render"}),e},Us=({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&&!j({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=j({state:e},{sectionId:i});return!s?.lines||!Array.isArray(s.lines)?(console.warn(`Section ${i} has no lines`),e):s.lines.find(c=>c.id===r)?(o.pointers.read={sectionId:i,lineId:r},Je(e,o.pointers.read),e):(console.warn(`Line not found: ${r} in section ${i}`),e)},zs=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return Ze({state:e}),e;if(K({state:e})&&t?._interactionSource!=="choice")return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0;let l=q({state:e})?.pointer,u=l?.sectionId,f=l?.lineId;u&&f&&Ce(e,{sectionId:u,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:J(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=q({state:e})?.pointer,r=n?.sectionId,o=j({state:e},{sectionId:r}),i=e.contexts[e.contexts.length-1],s=o?.lines||[],c=s.findIndex(l=>l.id===n?.lineId)+1;if(c<s.length){let l=s[c],u=!J(e,"skipUnseenText");if(e.global.skipMode&&u&&!Yt({state:e},{sectionId:r,lineId:l.id}))return fe({state:e}),e;if(i&&!i.rollback&&de(i,{compatibilityAnchor:!0}),i){let p=i.pointers.read.lineId;p&&r&&Ce(e,{sectionId:r,lineId:p}),i.pointers.read={sectionId:r,lineId:l.id}}Wt(e,{sectionId:r,lineId:l.id}),jt(e);let{isChoiceVisible:f}=Je(e,{sectionId:r,lineId:l.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&&Re({state:e}),e.global.skipMode&&fe({state:e});return e},Ws=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0;let t=K({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:J(e,"autoForwardDelay")}});let n=q({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&Ce(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},Ys=({state:e},t)=>{let n=t?.sectionId??q({state:e})?.pointer?.sectionId,r=j({state:e},{sectionId:n});if(!r||!r.lines||r.lines.length===0)return e;let o=r.lines,i=e.contexts[e.contexts.length-1];if(!i||!i.pointers)return e;let s=i.pointers.history||i.pointers.read;if(i.currentPointerMode!=="history"||!i.pointers.history){if(!s)return e;i.currentPointerMode="history",i.pointers.history={sectionId:n,lineId:s?.lineId};let u=o.findIndex(f=>f.id===s.lineId)-1;if(u>=0&&u<o.length){let f=o[u];i.pointers.history={sectionId:n,lineId:f.id}}return e.global.pendingEffects.push({name:"render"}),e}let c=o.findIndex(l=>l.id===i.pointers.history.lineId)-1;if(c>=0&&c<o.length){let l=o[c];i.pointers.history={sectionId:n,lineId:l.id},e.global.pendingEffects.push({name:"render"})}return e},Hs=({state:e},t)=>Er(e,{sectionId:t?.sectionId}),Gs=({state:e})=>{if(e.global.dialogueUIHidden)return Ze({state:e}),e;if(K({state:e}))return e;let t=q({state:e})?.pointer,n=t?.sectionId,r=j({state:e},{sectionId:n}),o=e.contexts[e.contexts.length-1],i=r?.lines||[],a=i.findIndex(c=>c.id===t?.lineId)+1;if(a<i.length){let c=i[a],l=!J(e,"skipUnseenText");if(e.global.skipMode&&l&&!Yt({state:e},{sectionId:n,lineId:c.id}))return fe({state:e}),e;if(o&&!o.rollback&&de(o,{compatibilityAnchor:!0}),o){let f=o.pointers.read.lineId;f&&n&&Ce(e,{sectionId:n,lineId:f}),o.pointers.read={sectionId:n,lineId:c.id}}Wt(e,{sectionId:n,lineId:c.id}),jt(e);let{isChoiceVisible:u}=Je(e,{sectionId:n,lineId:c.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},qs=({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=!1,a=!1,c=[];if(r.forEach(({variableId:l,op:u,value:f})=>{let d=e.projectData.resources?.variables?.[l],p=d?.scope,g=d?.type;At(p,l),vt(g,u,l);let y=p==="context"?o.variables:e.global.variables;p==="context"?(i=!0,c.push({variableId:l,op:u,value:f})):p==="device"?s=!0:p==="account"&&(a=!0),y[l]=wt(y[l],u,f)}),i&&Z(e,"updateVariable",{id:n,operations:c}),s){let l=Et(e.global.variables,e.projectData.resources?.variables,"device");e.global.pendingEffects.push({name:"saveGlobalDeviceVariables",payload:{globalDeviceVariables:l}})}if(a){let l=Et(e.global.variables,e.projectData.resources?.variables,"account");e.global.pendingEffects.push({name:"saveGlobalAccountVariables",payload:{globalAccountVariables:l}})}return e.global.pendingEffects.push({name:"render"}),e},Ks=e=>(t,n)=>e({state:t},n),Xs={updateVariable:{recordSources:[Ut],replayLine:Jn,replayRecorded:Jn,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Ks(_r)}},Qe=e=>Xs[e]??null,Js=e=>Qe(e)?.persistInSaveSlot===!0,Zs=(e,t)=>{let n=Qe(e)?.recordSources;return Array.isArray(n)&&n.includes(t)},Qs=(e,t,n)=>{Qe(t)?.replayRecorded?.(e,n)},el=(e,t,n)=>{Qe(t)?.replayLine?.(e,n)},Lr=({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}},Sr=({state:e})=>Lr({state:e},{offset:-1})!==null,tl=({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=de(r,{compatibilityAnchor:!r.rollback}),i=o.currentIndex+n;return i<0||i>=o.timeline.length?e:fr(e,i)},nl=({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=de(o,{compatibilityAnchor:!o.rollback}),a=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===n&&c.lineId===r);if(a===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return a===i.currentIndex?e:fr(e,a)},Cr=e=>{let t=Xi(e);return wn(t,{selectPendingEffects:Zi,selectSkipMode:dr,selectAutoMode:Qi,selectIsChoiceVisible:K,selectDialogueUIHidden:pr,selectDialogueHistory:hr,selectConfirmDialog:es,selectIsLineViewed:Yt,selectIsResourceViewed:ts,selectNextLineConfig:ns,selectSystemState:rs,selectSaveSlotMap:mr,selectSaveSlots:cs,selectSaveSlot:os,selectRuntime:Ht,selectRuntimeValue:is,selectAllVariables:yr,selectCurrentPointer:q,selectSection:j,selectCurrentLine:br,selectPresentationState:Ir,selectPresentationChanges:ss,selectSectionLineChanges:ls,selectSaveSlotPage:Gt,selectCurrentPageSlots:as,selectRenderState:fs,selectOverlayStack:Ji,selectLineIdByOffset:Lr,selectCanRollback:Sr,startAutoMode:Ar,stopAutoMode:Re,toggleAutoMode:Is,startSkipMode:vr,stopSkipMode:fe,toggleSkipMode:xs,showDialogueUI:Ze,hideDialogueUI:wr,toggleDialogueUI:As,setDialogueTextSpeed:vs,setAutoForwardDelay:ws,setSkipUnseenText:Es,setSkipTransitionsAndAnimations:_s,setSoundVolume:Ls,setMusicVolume:Ss,setMuteAll:Cs,setSaveLoadPagination:Rs,incrementSaveLoadPagination:$s,decrementSaveLoadPagination:ks,setMenuPage:Os,setMenuEntryPoint:Ts,showConfirmDialog:ds,hideConfirmDialog:ps,resetStoryAtSection:Ds,clearPendingEffects:Ps,appendPendingEffect:Ns,beginRollbackActionBatch:Hi,endRollbackActionBatch:Gi,addViewedLine:Vs,addViewedResource:Ms,setNextLineConfig:_r,saveSlot:js,loadSlot:Bs,updateProjectData:Fs,sectionTransition:Hs,jumpToLine:Us,nextLine:zs,markLineCompleted:Ws,prevLine:Ys,rollbackToLine:nl,rollbackByOffset:tl,pushOverlay:hs,popOverlay:gs,replaceLastOverlay:ms,clearOverlays:ys,updateVariable:qs,nextLineFromSystem:Gs},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var rl="route-engine",ol="projectPersistence";var Rr=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{}}),Q=e=>Object.prototype.toString.call(e)==="[object Object]",$r=(e={})=>{let t=Q(e)?e:{};return{saveSlots:Q(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:Q(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:Q(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:Q(t.globalRuntime)?t.globalRuntime:{}}},qt=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},il=e=>{let t=qt(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},sl=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},ll=({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}".`))}}),cl=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let c=r.transaction(t,"readonly").objectStore(t).get(n);c.onsuccess=()=>{o(c.result??null)},c.onerror=()=>{i(c.error??new Error(`Failed to read persisted namespace "${n}" from IndexedDB.`))}})},et=async({databasePromise:e,objectStoreName:t,namespace:n,patch:r})=>{let o=await e;return new Promise((i,s)=>{let a=o.transaction(t,"readwrite"),c=a.objectStore(t),l=c.get(n),u=!1,f=p=>{u||(u=!0,s(p))},d=()=>{u||(u=!0,i())};l.onerror=()=>{f(l.error??new Error(`Failed to read persisted namespace "${n}" before updating IndexedDB.`))},l.onsuccess=()=>{let p=$r(l.result),g={namespace:n,version:1,...Rr(),...p,...r},y=c.put(g);y.onerror=()=>{f(y.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}".`))}})},al=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let s=r.transaction(t,"readwrite"),c=s.objectStore(t).delete(n),l=!1,u=d=>{l||(l=!0,i(d))},f=()=>{l||(l=!0,o())};c.onerror=()=>{u(c.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}".`))}})},Kt=(e={})=>{let{indexedDB:t,databaseName:n=rl,objectStoreName:r=ol,namespace:o}=e,i=sl(t),s=il(o),a=ll({indexedDB:i,databaseName:n,objectStoreName:r});return{namespace:s,load:async()=>{let c=await cl({databasePromise:a,objectStoreName:r,namespace:s});return{...Rr(),...$r(c)}},clear:async()=>al({databasePromise:a,objectStoreName:r,namespace:s}),saveSlots:async c=>et({databasePromise:a,objectStoreName:r,namespace:s,patch:{saveSlots:Q(c)?c:{}}}),saveGlobalDeviceVariables:async c=>et({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:Q(c)?c:{}}}),saveGlobalAccountVariables:async c=>et({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalAccountVariables:Q(c)?c:{}}}),saveGlobalRuntime:async c=>et({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalRuntime:Q(c)?c:{}}})}},ul=Kt;function Xt(e){let t,n=0,r=null,{handlePendingEffects:o}=e,i=()=>{for(;t.selectPendingEffects().length>0;){let A=[...t.selectPendingEffects()];t.clearPendingEffects();try{o(A)}catch(k){throw t.clearPendingEffects(),A.forEach(B=>{t.appendPendingEffect(B)}),k}}},s=({initialState:A,namespace:k})=>{t=Cr(A),n=0,r=qt(k),t.appendPendingEffect({name:"handleLineActions"}),i()},a=()=>r,c=()=>t.selectPresentationState(),l=()=>t.selectPresentationChanges(),u=A=>t.selectSectionLineChanges(A),f=()=>(n+=1,{...t.selectRenderState(),id:`render-${n}`}),d=()=>t.selectSystemState(),p=()=>t.selectSaveSlotMap(),g=A=>t.selectSaveSlot(A),y=A=>t.selectSaveSlotPage(A),b=()=>t.selectSkipMode(),m=()=>t.selectAutoMode(),I=()=>t.selectRuntime(),x=()=>t.selectIsChoiceVisible(),w=(A,k)=>{t[A]&&(t[A](k),i())},R=(A,k)=>{w(A,k)},E=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:k,...B}=A,S=t.selectAllVariables?t.selectAllVariables():void 0;return{...B,_event:k,variables:S,runtime:t.selectRuntime?t.selectRuntime():{}}},L=(A,k,B={})=>{let S=E(k),C=Ln(A,S);t.beginRollbackActionBatch({source:B.rollbackSource});try{Object.entries(C).forEach(([T,Y])=>{w(T,Y)})}finally{t.endRollbackActionBatch({})}};return{init:s,handleAction:w,handleInternalAction:R,handleActions:L,selectRenderState:f,selectPresentationState:c,selectPresentationChanges:l,selectSectionLineChanges:u,selectSystemState:d,selectSaveSlotMap:p,selectSaveSlot:g,selectSaveSlotPage:y,selectSaveSlots:p,selectRuntime:I,selectIsChoiceVisible:x,handleLineActions:()=>{let A=t.selectCurrentLine();return A?.actions?(L(A.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:a}}var Jt=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},fl=80,Or=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{let o=e.selectRenderState();n?.(o),t.render(o)},dl=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&Or({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},pl=({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),tt(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},hl=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},gl=({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??fl;n.getElapsed()>=a&&(n.setElapsed(0),tt(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},ml=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},yl=({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),tt(e,"nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},bl=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Il=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveSlots(t?.saveSlots))},xl=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalDeviceVariables(t?.globalDeviceVariables))},Al=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalAccountVariables(t?.globalAccountVariables))},vl=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalRuntime(t?.globalRuntime))},kr={render:Or,saveSlots:Il,saveGlobalDeviceVariables:xl,saveGlobalAccountVariables:Al,saveGlobalRuntime:vl,handleLineActions:dl,startAutoNextTimer:pl,clearAutoNextTimer:hl,startSkipNextTimer:gl,clearSkipNextTimer:ml,nextLineConfigTimer:yl,clearNextLineConfigTimer:bl},wl=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),tt=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},El=(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(!wl.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},_l=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:a})=>{let c=Jt(),l=Jt(),u=Jt(),f=s??null,d=Promise.resolve(),p=null,g=null,y=!1,b=0,m=S=>{if(o){o(S);return}console.error("RouteEngine persistence write failed.",S)},I=()=>{if(f)return f;let S=e();return f=Kt({indexedDB:i,namespace:a??S?.getNamespace?.()}),f},x=S=>{d=d.catch(()=>{}).then(()=>{let C=I();return S(C)}).catch(C=>{m(C)})},w=S=>{let C=typeof S?.id=="string"&&S.id.length>0?S.id:null;b+=1,p=C,y=!1},R=()=>b,E=(S={})=>{if(S?.aborted===!0)return!1;let C=typeof S?.id=="string"&&S.id.length>0?S.id:null;return C?C!==p||C===g?!1:(g=C,!0):p!==null||y?!1:(y=!0,!0)},L=(S,C={})=>{if(S!=="renderComplete"||!E(C))return!1;let T=e();return tt(T,"markLineCompleted",{}),!0},$=(S={})=>{if(S?._interactionSource==="choice")return!0;let C=S?.actions;return!C||typeof C!="object"||Array.isArray(C)?!1:Object.values(C).some(T=>T?._interactionSource==="choice")},A=(S,C={})=>!C?.actions||typeof S?.selectIsChoiceVisible!="function"||!S.selectIsChoiceVisible()?!1:!$(C),k=({preprocessPayload:S,onEvent:C}={})=>async(T,Y={})=>{let H=e();if(A(H,Y))return C?.(T,Y);let V=await S?.(T,Y)??Y;if(A(H,V))return C?.(T,V);if(L(T,V),V?.actions){let Tr=V?._event?{_event:V._event}:V?.event?{_event:V.event}:void 0;H.handleActions(V.actions,Tr)}return C?.(T,V)},B=S=>{let C=e(),T=El(S);T.forEach(H=>{if(!kr[H.name]&&!r)throw new Error(`Unhandled pending effect "${H.name}".`)});let Y={engine:C,routeGraphics:t,ticker:n,autoTimer:c,skipTimer:l,nextLineConfigTimerState:u,trackRenderDispatch:w,getRenderDispatchCount:R,enqueuePersistenceWrite:x};for(let H of T){let V=kr[H.name];if(V){V(Y,H.payload);continue}r(H,Y)}};return B.handleRouteGraphicsEvent=L,B.createRouteGraphicsEventHandler=k,B},Ll=_l;var Sl=(e,t={})=>{let{resources:n={}}=t;return Nt(e,n)};var Tc=Xt;export{Ll as createEffectsHandler,ul as createIndexedDbPersistence,Tc as default,Sl as resolveLayoutReferences};
|
|
1
|
+
var Nr=Object.defineProperty;var Dr=(e,t)=>{for(var n in t)Nr(e,n,{get:t[n],enumerable:!0})};var sn=Symbol.for("immer-nothing"),en=Symbol.for("immer-draftable"),U=Symbol.for("immer-state");function G(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var he=Object.getPrototypeOf;function ee(e){return!!e&&!!e[U]}function re(e){return e?an(e)||Array.isArray(e)||!!e[en]||!!e.constructor?.[en]||De(e)||Ve(e):!1}var Vr=Object.prototype.constructor.toString();function an(e){if(!e||typeof e!="object")return!1;let t=he(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)===Vr}function Oe(e,t){Ne(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function Ne(e){let t=e[U];return t?t.type_:Array.isArray(e)?1:De(e)?2:Ve(e)?3:0}function st(e,t){return Ne(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function cn(e,t,n){let r=Ne(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Mr(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function De(e){return e instanceof Map}function Ve(e){return e instanceof Set}function ne(e){return e.copy_||e.base_}function at(e,t){if(De(e))return new Map(e);if(Ve(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[U];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let s=o[i],l=r[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(r[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(he(e),r)}else{let r=he(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function dt(e,t=!1){return Me(e)||ee(e)||!re(e)||(Ne(e)>1&&(e.set=e.add=e.clear=e.delete=jr),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>dt(r,!0))),e}function jr(){G(2)}function Me(e){return Object.isFrozen(e)}var Br={};function oe(e){let t=Br[e];return t||G(0,e),t}var Ie;function ln(){return Ie}function Fr(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function tn(e,t){t&&(oe("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function ct(e){lt(e),e.drafts_.forEach(Ur),e.drafts_=null}function lt(e){e===Ie&&(Ie=e.parent_)}function nn(e){return Ie=Fr(Ie,e)}function Ur(e){let t=e[U];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function rn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[U].modified_&&(ct(t),G(4)),re(e)&&(e=Te(t,e),t.parent_||Pe(t,e)),t.patches_&&oe("Patches").generateReplacementPatches_(n[U].base_,e,t.patches_,t.inversePatches_)):e=Te(t,n,[]),ct(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==sn?e:void 0}function Te(e,t,n){if(Me(t))return t;let r=t[U];if(!r)return Oe(t,(o,i)=>on(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Pe(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),Oe(i,(l,c)=>on(e,r,o,l,c,n,s)),Pe(e,o,!1),n&&e.patches_&&oe("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function on(e,t,n,r,o,i,s){if(ee(o)){let l=i&&t&&t.type_!==3&&!st(t.assigned_,r)?i.concat(r):void 0,c=Te(e,o,l);if(cn(n,r,c),ee(c))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(re(o)&&!Me(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Te(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&Pe(e,o)}}function Pe(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&dt(t,n)}function zr(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:ln(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=pt;n&&(o=[r],i=xe);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var pt={get(e,t){if(t===U)return e;let n=ne(e);if(!st(n,t))return Wr(e,n,t);let r=n[t];return e.finalized_||!re(r)?r:r===ot(e.base_,t)?(it(e),e.copy_[t]=ft(r,e)):r},has(e,t){return t in ne(e)},ownKeys(e){return Reflect.ownKeys(ne(e))},set(e,t,n){let r=un(ne(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=ot(ne(e),t),i=o?.[U];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Mr(n,o)&&(n!==void 0||st(e.base_,t)))return!0;it(e),ut(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 ot(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,it(e),ut(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=ne(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){G(11)},getPrototypeOf(e){return he(e.base_)},setPrototypeOf(){G(12)}},xe={};Oe(pt,(e,t)=>{xe[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});xe.deleteProperty=function(e,t){return xe.set.call(this,e,t,void 0)};xe.set=function(e,t,n){return pt.set.call(this,e[0],t,n,e[0])};function ot(e,t){let n=e[U];return(n?ne(n):e)[t]}function Wr(e,t,n){let r=un(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function un(e,t){if(!(t in e))return;let n=he(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=he(n)}}function ut(e){e.modified_||(e.modified_=!0,e.parent_&&ut(e.parent_))}function it(e){e.copy_||(e.copy_=at(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Yr=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(c=i,...a){return s.produce(c,u=>n.call(this,u,...a))}}typeof n!="function"&&G(6),r!==void 0&&typeof r!="function"&&G(7);let o;if(re(t)){let i=nn(this),s=ft(t,void 0),l=!0;try{o=n(s),l=!1}finally{l?ct(i):lt(i)}return tn(i,r),rn(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===sn&&(o=void 0),this.autoFreeze_&&dt(o,!0),r){let i=[],s=[];oe("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else G(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,c=>t(c,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){re(e)||G(8),ee(e)&&(e=ht(e));let t=nn(this),n=ft(e,void 0);return n[U].isManual_=!0,lt(t),n}finishDraft(e,t){let n=e&&e[U];(!n||!n.isManual_)&&G(9);let{scope_:r}=n;return tn(r,t),rn(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=oe("Patches").applyPatches_;return ee(e)?r(e,t):this.produce(e,o=>r(o,t))}};function ft(e,t){let n=De(e)?oe("MapSet").proxyMap_(e,t):Ve(e)?oe("MapSet").proxySet_(e,t):zr(e,t);return(t?t.scope_:ln()).drafts_.push(n),n}function ht(e){return ee(e)||G(10,e),fn(e)}function fn(e){if(!re(e)||Me(e))return e;let t=e[U],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=at(e,t.scope_.immer_.useStrictShallowCopy_)}else n=at(e,!0);return Oe(n,(r,o)=>{cn(n,r,fn(o))}),t&&(t.finalized_=!1),n}var z=new Yr,gt=z.produce,Oa=z.produceWithPatches.bind(z),Ta=z.setAutoFreeze.bind(z),Pa=z.setUseStrictShallowCopy.bind(z),Na=z.applyPatches.bind(z),Da=z.createDraft.bind(z),Va=z.finishDraft.bind(z);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},Ae={NOT:0};var v=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},F=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var mt=e=>{if(!e||e.trim()==="")throw new v("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new v(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${n}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let n of t)if(e.trim().endsWith(n))throw new v(`Incomplete comparison expression - missing right operand (got: '${e}')`)},dn=e=>{if(e.trim().endsWith(" in"))throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new v(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);let r=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of r){if(!o)throw new v(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new v(`Invalid loop syntax (got: '$for ${e}')`)}};var pn=(e,t,n=!1)=>{if(t===null)return new F(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new F(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new F(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new F(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},hn=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new F(`Unknown function '${e}' (${n})`)};var Hr=(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=_(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},_=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return P(e.var,n,r);if(e.type===h.LITERAL)return e.value;if(e.type===h.VARIABLE)return P(e.path,n,r);if(e.type===h.INTERPOLATION)return qr(e.parts,t,n,r);switch(e.type){case h.FUNCTION:return mn(e,t,n,r);case h.BINARY:return yn(e,t,n,r);case h.UNARY:return bn(e,t,n,r);case h.CONDITIONAL:return Xr(e,t,n,r);case h.LOOP:return to(e,t,n,r);case h.OBJECT:return ro(e,t,n,r);case h.ARRAY:return oo(e,t,n,r);case h.PARTIAL:return io(e,t,n,r);case h.PATH_REFERENCE:return so(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},gn=new Map,Gr=e=>{let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(i==="]"){if(r&&n){let s=n.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let l=s.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:s});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},P=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=gn.get(e);if(!r){let i=[],s="",l=0;for(let c=0;c<e.length;c++){let a=e[c];a==="["?(l++,s+=a):a==="]"?(l--,s+=a):a==="."&&l===0?s&&(i.push(s),s=""):s+=a}s&&i.push(s),r=[];for(let c of i){let a=Gr(c.trim());r.push(...a)}gn.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},qr=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=_(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},mn=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw hn(e.name,o);let s=e.args.map(l=>_(l,t,n,r));return i(...s)},ge=(e,t,n,r)=>{if(e.var&&!e.type)return P(e.var,n,r);switch(e.type){case h.VARIABLE:return P(e.path,n,r);case h.LITERAL:return e.value;case h.BINARY:return yn(e,t,n,r);case h.UNARY:return bn(e,t,n,r);case h.FUNCTION:return mn(e,t,n,r);default:return _(e,t,n,r)}},yn=(e,t,n,r)=>{if(e.op===T.AND||e.op===T.OR){let s=ge(e.left,t,n,r),l=ge(e.right,t,n,r);switch(e.op){case T.AND:return s&&l;case T.OR:return s||l}}let o=_(e.left,t,n,r),i=_(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 F(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case T.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new F(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},bn=(e,t,n,r)=>{let o=e.op===Ae.NOT?ge(e.operand,t,n,r):_(e.operand,t,n,r);if(e.op===Ae.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Kr=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===h.VARIABLE)if(P(o.path,n,r)){let s=e.bodies[0];if(s.type===h.OBJECT&&s.properties.length<=5){let l={};for(let c of s.properties){let a=c.parsedKey?_(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===h.LITERAL)l[a]=u.value;else if(u.type===h.VARIABLE)l[a]=P(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=P(d.path,n,r);f.push(p!=null?String(p):"")}else{let p=_(d,t,n,r);f.push(p!=null?String(p):"")}l[a]=f.join("")}else l[a]=_(u,t,n,r)}return l}}else{let s=e.bodies[1];if(s.type===h.OBJECT&&s.properties.length<=5){let l={};for(let c of s.properties){let a=c.parsedKey?_(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===h.LITERAL)l[a]=u.value;else if(u.type===h.VARIABLE)l[a]=P(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=P(d.path,n,r);f.push(p!=null?String(p):"")}else{let p=_(d,t,n,r);f.push(p!=null?String(p):"")}l[a]=f.join("")}else l[a]=_(u,t,n,r)}return l}}}return null},Xr=(e,t,n,r)=>{let o=Kr(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||ge(s,t,n,r))return _(e.bodies[i],t,n,r)}return In},Jr=(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 c of i.properties)if(c.parsedKey)return null;let l=[];for(let c=0;c<t.length;c++){let a=t[c];if(a[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]=a;else if(g.startsWith(r+".")){let y=g.substring(r.length+1);u[d]=a[y]}else return null}else if(p.type===h.INTERPOLATION){let g=[],y=!0;for(let b of p.parts)if(typeof b=="string")g.push(b);else if(b.type===h.VARIABLE){let m=b.path;if(m===r)g.push(a!=null?String(a):"");else if(m.startsWith(r+".")){let I=m.substring(r.length+1),x=a[I];g.push(x!=null?String(x):"")}else{y=!1;break}}else{y=!1;break}if(!y)return null;u[d]=g.join("")}else return null}l.push(u)}}return l}}}return null},Zr=(e,t)=>{let n=e.body,r=e.itemVar,o=Jr(e,t);if(o!==null)return o;if(n.type===h.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let l of n.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of n.properties){let c=l.key,a=l.value;if(a.type===h.LITERAL)i.push({key:c,type:"literal",value:a.value});else if(a.type===h.VARIABLE){let u=a.path;if(u===r)i.push({key:c,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(a.type===h.INTERPOLATION&&a.parts.length===1){let u=a.parts[0];if(u.type===h.VARIABLE){let f=u.path;if(f===r)i.push({key:c,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let l=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let a=t[c];l[c]={id:a.id,title:a.title!=null?String(a.title):"",completed:a.completed}}else for(let c=0;c<t.length;c++){let a=t[c],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=a;else if(f.type==="prop")u[f.key]=a[f.prop];else if(f.type==="item_string")u[f.key]=a!=null?String(a):"";else if(f.type==="prop_string"){let d=a[f.prop];u[f.key]=d!=null?String(d):""}l[c]=u}return l}}return null},Qr=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===h.OBJECT&&s.fast!==!1){let l=e.itemVar,c=e.indexVar;for(let a=0;a<o.length;a++){let u=o[a],f={},d={...r,[l]:u,...c&&{[c]:a}};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__,[l]:`${p}[${a}]`,...c&&{[c]:a}};for(let g of s.properties){let y=g.parsedKey?_(g.parsedKey,t,n,d):g.key,b=g.value;if(b.type===h.LITERAL)f[y]=b.value;else if(b.type===h.VARIABLE){let m=b.path;if(m===l)f[y]=u;else if(m===c)f[y]=a;else if(m.startsWith(l+".")){let I=m.substring(l.length+1);!I.includes(".")&&!I.includes("[")?f[y]=u[I]:f[y]=P(m,n,{...r,[l]:u,...c&&{[c]:a}})}else f[y]=P(m,n,{...r,[l]:u,...c&&{[c]:a}})}else if(b.type===h.INTERPOLATION){let m=[];for(let I of b.parts)if(typeof I=="string")m.push(I);else if(I.type===h.VARIABLE){let x=I.path,w;if(x===l)w=u;else if(x===c)w=a;else if(x.startsWith(l+".")){let R=x.substring(l.length+1);!R.includes(".")&&!R.includes("[")?w=u[R]:w=P(x,n,{...r,[l]:u,...c&&{[c]:a}})}else w=P(x,n,{...r,[l]:u,...c&&{[c]:a}});m.push(w!=null?String(w):"")}else{let x={...r,[l]:u,...c&&{[c]:a}},w=_(I,t,n,x);m.push(w!=null?String(w):"")}f[y]=m.join("")}else{let m={...r,[l]:u,...c&&{[c]:a}};f[y]=_(b,t,n,m)}}i.push(f)}return i}return null},eo=(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 l=s.properties[0],c=s.properties[1];if(l.key==="id"&&l.value.type===h.VARIABLE&&l.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===h.CONDITIONAL){let a=[];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),a.push(d)}}return a}}}}return null},to=(e,t,n,r)=>{let o=_(e.iterable,t,n,r);if(!Array.isArray(o)){let a,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(", ");a=`${e.iterable.name}(${d})`}else a=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${a}`;throw pn(f,o,u)}if(!e.indexVar){let a=eo(e,o,e.itemVar);if(a!==null)return a}if(!e.indexVar){let a=Zr(e,o);if(a!==null)return a}let i=Qr(e,t,n,r,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(r&&r.__paths__&&l){let a=l.split("."),u=a[0];u in r.__paths__&&(l=r.__paths__[u],a.length>1&&(l+="."+a.slice(1).join(".")))}let c=!1;e.body.type===h.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(a=>a.type===h.OBJECT&&a.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let a=0;a<o.length;a++){let u=e.indexVar?{...r,[e.itemVar]:o[a],[e.indexVar]:a}:{...r,[e.itemVar]:o[a]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${a}]`},e.indexVar&&(u.__paths__[e.indexVar]=a);let f=_(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!c){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},no=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?_(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===h.OBJECT&&s.properties.length<=10&&!s.whenCondition){let l={},c={},a=!0;for(let u of s.properties){let f=u.parsedKey?_(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]=P(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=P(g.path,n,r);p.push(y!=null?String(y):"")}else{a=!1;break}if(!a)break;c[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,b=g.value;if(b.type===h.LITERAL)p[y]=b.value;else if(b.type===h.VARIABLE)p[y]=P(b.path,n,r);else if(b.type===h.INTERPOLATION){let m=[];for(let I of b.parts)if(typeof I=="string")m.push(I);else if(I.type===h.VARIABLE){let x=P(I.path,n,r);m.push(x!=null?String(x):"")}else{a=!1;break}if(!a)break;p[y]=m.join("")}else{a=!1;break}}if(!a)break;c[f]=p}else{a=!1;break}}if(a)return l[i]=c,l}}return null},ro=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!ge(e.whenCondition,o,n,r))return;let i=no(e,t,n,r);if(i!==null)return i;if(e.fast){let a={};for(let u of e.properties){let f=u.parsedKey?_(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===h.LITERAL)a[f]=d.value;else if(d.type===h.VARIABLE)a[f]=P(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=P(g.path,n,r);p.push(y!=null?String(y):"")}else{let y=_(g,t,n,r);p.push(y!=null?String(y):"")}a[f]=p.join("")}else a[f]=_(d,t,n,r)}return a}let s={},l=null,c=!1;for(let a of e.properties)if(!a.key.startsWith("$if ")&&!a.key.match(/^\$if\s+\w+.*:?$/)&&!a.key.startsWith("$elif")&&!a.key.startsWith("$else")&&!a.key.startsWith("$for ")){c=!0;break}for(let a of e.properties)if(a.key.startsWith("$if ")||a.key.match(/^\$if\s+\w+.*:?$/)){let u=_(a.value,t,n,r);if(!c&&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(a.key.startsWith("$for ")){if(e.properties.length===1)return _(a.value,t,n,r)}else{let u=a.value;if(u&&u.type===h.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=_(f.value,t,n,r);d!==void 0&&(s[a.key]=d)}else{let d=_(a.value,t,n,r);d!==void 0&&(s[a.key]=d)}}else{let f=a.parsedKey?_(a.parsedKey,t,n,r):a.key,d=_(a.value,t,n,r);d!==void 0&&(s[f]=d)}}return s},In={},oo=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===h.LOOP){let s=_(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=_(i,t,n,r);s!==In&&s!==void 0&&o.push(s)}return o},io=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},c=t.functions||t;if(s&&!ge(s,c,n,r))return;if(!l[o])throw new F(`Partial '${o}' is not defined`);let a=r._partialStack||[];if(a.includes(o))throw new F(`Circular partial reference detected: ${o}`);let u=l[o],f=n,d={...r,_partialStack:[...a,o]};if(r){f={...n};for(let p of Object.keys(r))p.startsWith("_")||(f[p]=r[p])}if(i){let p=_(i,t,n,r);f={...f,...p}}return _(u,t,f,d)},so=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),s=i[0],l=i.slice(1);if(!r||!(s in r))throw new F(`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 F(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=r.__paths__[s];if(typeof c=="number"){if(l.length>0)throw new F(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return l.length>0&&(c+="."+l.join(".")),c},yt=Hr;var ao=/\$\{([^}]*)\}/g,co=/#\{([^}]*)\}/g,An=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=lo(o,t);return{isFunction:!0,type:h.FUNCTION,name:r,args:i}},lo=(e,t={})=>e.trim()?uo(e).map(r=>fo(r.trim(),t)):[],uo=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],c=s>0?e[s-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,n+=l):o&&l===i&&c!=="\\"?(o=!1,i="",n+=l):!o&&l==="("?(r++,n+=l):!o&&l===")"?(r--,n+=l):!o&&l===","&&r===0?(t.push(n),n=""):n+=l}return n&&t.push(n),t},fo=(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=An(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:l,type:c}of o){let a=0;for(;a<r.length;){let u=ie(r.substring(a),l);if(u===-1)break;let f=a+u;f>i&&(i=f,s={op:l,type:c}),a=f+l.length}}if(i!==-1)try{return M(r,t)}catch{return{type:h.VARIABLE,path:r}}return{type:h.VARIABLE,path:r}},vn=/^\w+\(.*\)$/,po=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,ho=e=>{if(!(!e||e.trim()===""||vn.test(e))&&po.test(e))throw e.includes("?")&&e.includes(":")?new v(`Complex expressions not supported in variable replacements - consider calculating the value in your data instead. Offending expression: "${e}"`):e.includes("||")||e.includes("&&")||e.includes("??")?new v(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new v(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},xn=e=>{let t=e.trim();if(vn.test(t))throw new v(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new v(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new v(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new v(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("?")&&t.includes(":"))throw new v(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:h.PATH_REFERENCE,path:t}},ve=(e,t={})=>{let n=e.trim();ho(n);let r=An(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}},bt=(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,(a,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\(#\{[^}]*\})/g,(a,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(ao)],i=[...n.matchAll(co)],s=[...o.map(a=>({match:a,type:"variable"})),...i.map(a=>({match:a,type:"pathref"}))].sort((a,u)=>a.match.index-u.match.index);if(s.length===0){let a=n;for(let u=0;u<r.length;u++)a=a.replace(`__ESCAPED_${u}__`,r[u]);return{type:h.LITERAL,value:a}}if(s.length===1&&s[0].match[0]===n&&r.length===0){let{match:a,type:u}=s[0];try{return u==="variable"?ve(a[1],t):xn(a[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:h.LITERAL,value:n};throw f}}let l=[],c=0;for(let{match:a,type:u}of s){let[f,d]=a,p=a.index;if(p>c){let g=n.substring(c,p);for(let y=0;y<r.length;y++)g=g.replace(`__ESCAPED_${y}__`,r[y]);g&&l.push(g)}try{let g;u==="variable"?g=ve(d.trim(),t):g=xn(d.trim()),l.push(g)}catch(g){if(g.message==="Invalid array index syntax")l.push(f);else throw g}c=p+f.length}if(c<n.length){let a=n.substring(c);for(let u=0;u<r.length;u++)a=a.replace(`__ESCAPED_${u}__`,r[u]);a&&l.push(a)}return{type:h.INTERPOLATION,parts:l}};var te=(e,t)=>typeof e=="string"?bt(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?mo(e,t):yo(e,t):{type:h.LITERAL,value:e},go=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new v("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new v("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new v("Empty $each body not allowed");if(n.$partial!==void 0)throw new v("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},mo=(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 c=go(i),a=Object.keys(c);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let u=wn(a[0],c[a[0]],t,!0);n.push(u),r=!0;continue}}catch(c){throw c instanceof v?c:new v(c.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let c=wn(l[0],i[l[0]],t);n.push(c),r=!0;continue}}let s=te(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}},yo=(e,t)=>{let n=[],r=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new v("$partial value must be a string");if(e.$partial.trim()==="")throw new v("$partial value cannot be an empty string");let c=["$if","$elif","$else","$for"],a=[];for(let[m]of i)for(let I of c)if(m===I||m.startsWith(I+" ")||m.startsWith(I+"#")){a.push(I);break}if(a.length>0)throw new v(`Cannot use $partial with ${a.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[m,I]of Object.entries(d)){let x=m;(m.startsWith("\\$")||m.startsWith("$$"))&&(x=m.slice(1)),p[x]=I,g=!0}let y=null;if(g&&(y=te(p,t),y.type===h.OBJECT)){let m=!1;for(let I of y.properties)if(I.value.type===h.VARIABLE||I.value.type===h.INTERPOLATION||I.value.type===h.FUNCTION||I.value.type===h.CONDITIONAL||I.value.type===h.OBJECT&&!I.value.fast||I.value.type===h.ARRAY&&!I.value.fast){m=!0;break}m&&(y.fast=!1)}let b={type:h.PARTIAL,name:u,data:y};if(f!==void 0){let m;if(typeof f=="string"){if(f.trim()==="")throw new v("Empty condition expression after '$when'");m=M(f,t)}else m={type:h.LITERAL,value:f};b.whenCondition=m}return b}for(let[c,a]of i)if(c==="$when"){if(o!==null)throw new v("Multiple '$when' directives on the same object are not allowed");if(a==null)throw new v("Missing condition expression after '$when'");let u=typeof a=="string"?a:JSON.stringify(a);if(u.trim()==="")throw new v("Empty condition expression after '$when'");o=M(u,t),r=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new v("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[c,a]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new v("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=bo(i,s,t);n.push({key:c,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(c)){let u=c.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new v(`$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(c.startsWith("$elif ")||c.startsWith("$else"))throw new v(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new v("Missing condition expression after '$if'");{let u=te(a,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=bt(c,t),d={key:c,value:u};(f.type!==h.LITERAL||f.value!==c)&&(d.parsedKey=f),n.push(d),s++}}}let l={type:h.OBJECT,properties:n,fast:!r};return o&&(l.whenCondition=o),l},bo=(e,t,n={})=>{let r=[],o=[],i=t,[s,l]=e[i],c=null,a;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=f[1],a=f[2];else throw new v(`Invalid conditional syntax: ${s}`)}else a=s.substring(4),a.endsWith(":")&&(a=a.slice(0,-1).trim());mt(a);let u=M(a,n);for(r.push(u),o.push(te(l,n)),i++;i<e.length;){let[f,d]=e[i],p=!1,g;if(c?f.startsWith(`$elif#${c} `)?(g=f.substring(`$elif#${c} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),p=!0):(f===`$else#${c}`||f===`$else#${c}:`)&&(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{mt(g);let y=M(g,n);r.push(y)}if(o.push(te(d,n)),i++,g===null)break}else break}return{node:{type:h.CONDITIONAL,conditions:r,bodies:o,id:c},nextIndex:i}},M=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let a=e.slice(1,-1),u=0,f=!0;for(let d=0;d<a.length;d++)if(a[d]==="("?u++:a[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return M(a,t)}let n=ie(e,"||");if(n!==-1)return{type:h.BINARY,op:T.OR,left:M(e.substring(0,n).trim(),t),right:M(e.substring(n+2).trim(),t)};let r=ie(e,"&&");if(r!==-1)return{type:h.BINARY,op:T.AND,left:M(e.substring(0,r).trim(),t),right:M(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:a,type:u}of o){let f=ie(e,a);if(f!==-1)return{type:h.BINARY,op:u,left:M(e.substring(0,f).trim(),t),right:M(e.substring(f+a.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:T.ADD},{op:" - ",type:T.SUBTRACT}];for(let{op:a,type:u}of l){let f=0;for(;f<e.length;){let d=ie(e.substring(f),a);if(d===-1)break;let p=f+d;p>i&&(i=p,s={op:a,type:u}),f=p+a.length}}if(i!==-1&&s)return{type:h.BINARY,op:s.type,left:M(e.substring(0,i).trim(),t),right:M(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let a of c)if(ie(e,a)!==-1)throw new v(`Arithmetic operations are not allowed in conditionals: "${a}"`);return e.startsWith("!")?{type:h.UNARY,op:Ae.NOT,operand:M(e.substring(1).trim(),t)}:En(e,t)},ie=(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},Io=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}},En=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return ve(n,t);let o=Io(n);if(o.type===h.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:h.VARIABLE,path:n};try{return ve(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},xo=(e,t=!1)=>{let n=t?"$each":"$for";try{dn(e)}catch(r){if(r instanceof v&&t){let o=r.message.replace(/\$for/g,"$each");throw new v(o.replace("Parse Error: ",""))}throw r}},wn=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let b=r?"$each":"$for";throw new v(`Invalid loop syntax (got: '${e.replace("$for",b)}')`)}let s=i[1],l=i[2].trim();xo(l,r);let c=l.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let b=r?"$each":"$for";throw new v(`Invalid loop syntax - missing 'in' keyword (got: '${b} ${l}')`)}let a=c[1].trim(),u=c[2].trim(),f,d=null;if(a.includes(",")){let b=a.split(",").map(m=>m.trim());if(b.length!==2)throw new v(`Invalid loop variables: ${a}. Expected format: "item" or "item, index"`);f=b[0],d=b[1]}else f=a;let p=["this","undefined","null","true","false"];if(p.includes(f))throw new v(`Reserved variable name: ${f}`);if(d&&p.includes(d))throw new v(`Reserved variable name: ${d}`);let g=En(u,n),y=te(t,n);return{type:h.LOOP,itemVar:f,indexVar:d,iterable:g,body:y,flatten:s!=="nested"}};var Ao=(e,t={})=>{let{functions:n={}}=t;return te(e,n)},je=Ao;var It={};Dr(It,{now:()=>vo});var vo=()=>Date.now();var wo=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...It,...r},s=je(e,{functions:i}),l={};for(let[c,a]of Object.entries(o))l[c]=je(a,{functions:i});return yt(s,t,{functions:i,partials:l})},W=wo;var _n=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:l=c=>c}=n;for(let[c,a]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>a(s(r),...u):i[c]=(...u)=>{r=gt(r,d=>a(l(d),...u))});return{...o,...i}},Be=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return gt(r,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var Eo=(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{}}},vt=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{let i=Eo(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},wt=(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(", ")}`)},Et=(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(", ")}`)},_t=(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}`)}},Lt=(e,t,n)=>Object.fromEntries(Object.entries(e).filter(([r])=>t?.[r]?.scope===n)),Ln=(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()))},_o=(e,t)=>{let n=e?.ui,r=t?.ui;return JSON.stringify(n)===JSON.stringify(r)?null:n&&!r?{changeType:"delete",data:e}:r&&!e?{changeType:"add",data:t}:r&&e?{changeType:"update",data:t}:null},Ct=(e={},t={})=>{let n={},r=["sfx","voice"],o=s=>{let l=e[s],c=t[s];c&&!l?n[s]={changeType:"add",data:c}:l&&!c?r.includes(s)||(n[s]={changeType:"delete",data:l}):l&&c&&JSON.stringify(l)!==JSON.stringify(c)&&(n[s]={changeType:"update",data:c})};o("background"),o("bgm"),o("voice");let i=_o(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},St=(e={})=>{let t=structuredClone(e);t.background&&(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);let r=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(l=>{let c={...l};return delete c.animations,i(c)?c: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},Lo=(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},Co=(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=Lo(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},So={updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"])},Cn=(e,t)=>{let n=e[e.length-1];return n?So[n]?.has(t)===!0:!1},xt=(e,t,n=[])=>Array.isArray(e)?e.map(r=>xt(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Cn(n,r)?o:xt(o,t,[...n,r])])):Co(e,t),At=(e,t,n=[])=>Array.isArray(e)?e.map(r=>At(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Cn(n,r)?o:At(o,t,[...n,r])])):typeof e=="string"?W(e,t):e,Sn=(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=xt(e,t._event);return At(n,t)};var Ue=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:structuredClone(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Rn=(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}},Fe=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ro=e=>{if(e){if(e.character&&Fe(e.character,"name"))return e.character.name;if(Fe(e,"characterName"))return e.characterName}},$o=()=>({}),ko=(e,t)=>{if(t.background){let{animationsOnly:n,state:r}=Ue(t.background,o=>!!o.resourceId);if(n){e.background=e.background?.resourceId?{...structuredClone(e.background),...r}:r;return}if(!t.background.resourceId){delete e.background;return}e.background=structuredClone(t.background)}else e.background?.animations&&(e.background.animations={})},Oo=(e,t)=>{if(!t.dialogue){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:s,state:l}=Ue(t.dialogue.ui,c=>!!c.resourceId);s?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=Fe(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;n?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let r=Fe(t.dialogue,"characterId"),o=Ro(t.dialogue),i=o!==void 0;if(r?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:n||delete e.dialogue.characterId,i?e.dialogue.character={name:o}:(r||!n)&&delete e.dialogue.character,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 s={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(s.character={...e.dialogue.character}),e.dialogue.lines.push(s)}},To=(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},Po=(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}}},No=(e,t)=>{if(t.visual){let{hasValidItems:n,processedItems:r}=Rn(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))},Do=(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}=Rn(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);n?e.character={items:r}:delete e.character},Vo=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Mo=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=Ue(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},jo=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=Ue(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},Bo=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},Fo=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},Uo=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},me=e=>Be($o,[Uo,ko,To,Po,No,Oo,Do,Vo,Mo,jo,Bo,Fo])(e);var ae={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:Ln},zo=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,Wo=(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},We=(e,t,n)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),l=zo.exec(s);if(l){let[,c,a,u]=l,f=Wo(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((p,g)=>{let y={...t,[c]:p};a&&(y[a]=g),d.forEach(b=>{let m=We(b,y,n),I=W(m,y,n);Array.isArray(I)?o.push(...I):o.push(I)})});continue}}o.push(We(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=We(i,t,n)}),r},Nt=({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".`)},Yo=({id:e,targetId:t,animation:n,animationPath:r="animation"})=>{let o=structuredClone(n);return Nt({animationType:o.type,animationId:e,animationPath:r}),delete o.name,o.id=e,o.targetId=t,o},Ho=(e,{animationId:t="animation",animationPath:n="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Nt({animationType:e.type,animationId:t,animationPath:n}),e.type},Go=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},qo=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Ko=(e,t)=>{if(qo(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},we=({animations:e,resources:t,animationId:n,instanceId:r,targetId:o,animationPath:i="animation"})=>{if(!n||!o)return!1;let s=t?.animations?.[n];return s?(e.push(Yo({id:r,targetId:o,animation:s,animationPath:i})),!0):!1},Xo=({hasPrevious:e,hasCurrent:t,previousResourceId:n,currentResourceId:r,sharedTarget:o})=>!e&&t?"enter":e&&!t?"exit":e&&t?n===r&&o?"update":"replace":"none",Jo=({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.`)},Zo=(e,{defaultTargetId:t,defaultId:n,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Nt({animationType:o.type,animationId:o.id??n,animationPath:r}),o.id??=n,o.targetId??=t,o},Dt=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r,animationPathPrefix:o=r})=>{t.forEach((i,s)=>{e.push(Zo(i,{defaultTargetId:n,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},$n=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=W(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},On=(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))},Tn=(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("-")}`},Rt=(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},Qo=(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},Pn=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},ze=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},ei=(e={})=>e.textStyles||{},ti=(e={})=>e.images||{},ni=(e={})=>e.colors||{},ri=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Ee=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,ye=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},Nn=(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},Bn=(e,t)=>{if(typeof e!="string"||!ri.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},Dn=(e,t,n)=>{let r=Bn(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})`},oi=(e={},t)=>{let n=ei(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=Nn(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:Dn(o.hex,i,`Color "${n.colorId}" for text style "${t}"`)};if(n.align!==void 0&&(s.align=n.align),n.wordWrap!==void 0&&(s.wordWrap=n.wordWrap),n.breakWords!==void 0&&(s.breakWords=n.breakWords),n.wordWrapWidth!==void 0&&(s.wordWrapWidth=n.wordWrapWidth),n.strokeColorId){let l=e.colors?.[n.strokeColorId];if(!l)throw new Error(`Stroke color "${n.strokeColorId}" not found for text style "${t}"`);let c=Nn(n.strokeAlpha,"strokeAlpha",t);s.strokeColor=Dn(l.hex,c,`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},Ot=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Ot(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]=Ot(i,t,Ee(n,o)));return e.textStyleId!==void 0&&(ye(e.textStyleId,n,"textStyleId"),r.textStyle=oi(t,e.textStyleId)),r},Fn=(e={},t)=>{let n=ni(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return Bn(n.hex,`Color "${t}"`)},Un=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",$t=(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 ${Un(`${t}.fill`)} instead`)},ii=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>_e(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]=_e(i,t,Ee(n,o)));return e.colorId!==void 0&&(ye(e.colorId,n,"colorId"),r.fill=Fn(t,e.colorId)),r},_e=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>_e(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 ${Un("fill")} instead`);$t(e,"hover",n),$t(e,"click",n),$t(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]=ii(i,t,Ee(n,o));continue}r[o]=_e(i,t,Ee(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(ye(e.colorId,n,"colorId"),r.fill=Fn(t,e.colorId)),r},kt=(e={},t)=>{let n=ti(e)?.[t];return n||null},zn=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",Vn=(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 ${zn(`${t}.${r}`)} instead`)},Mn=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},Tt=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Tt(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 ${zn(o)} instead`);Vn(e,"hover",n,"src"),Vn(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]=Tt(i,t,Ee(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){ye(e.imageId,n,"imageId");let o=kt(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&&(ye(e.hoverImageId,n,"hoverImageId"),Mn(r,"hover",kt(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(ye(e.clickImageId,n,"clickImageId"),Mn(r,"click",kt(t,e.clickImageId)?.fileId??e.clickImageId)),r},Vt=(e,t={},n="root")=>Tt(_e(Ot(e,t,n),t,n),t,n),ce=Vt,He=(e=[])=>e.find(t=>t.id==="story");var si=(e={})=>e?.muteAll?0:e?.musicVolume??50,X=({variables:e,runtime:t,saveSlots:n=[],isLineCompleted:r,autoMode:o,skipMode:i,isChoiceVisible:s,canRollback:l,confirmDialog:c,historyDialogue:a=[],characters:u={},dialogueUIHidden:f,skipOnlyViewedLines:d,skipTransitionsAndAnimations:p}={})=>{let g={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??o??!1,skipMode:t?.skipMode??i??!1,dialogueUIHidden:t?.dialogueUIHidden??f??!1,isLineCompleted:t?.isLineCompleted??r??!1};return{variables:e,runtime:g,saveSlots:n,isChoiceVisible:s,canRollback:l,confirmDialog:c,historyDialogue:a,characters:u}},jn=100,Ye=(e,t)=>{if(Array.isArray(e))return e.map(r=>Ye(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=Ye(n[r],t)}),n.type==="text-revealing"?t(n):n},ai=e=>Ye(e,t=>({...t,revealEffect:"none"})),ci=e=>Ye(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,jn):jn;return{...t,speed:r,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:r}:{}}}),le=(e,{isLineCompleted:t=!1,skipMode:n=!1,skipTransitionsAndAnimations:r=!1}={})=>t||r?ai(e):n?ci(e):e,Wn=({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:{}}}}),Pt=e=>{if(Array.isArray(e))return e.map(Pt);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Pt(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}}:{}}}}},Yn=(e=[],t={})=>e.map(n=>{let r=t?.[n.characterId],o=n.character?.name!==void 0?n.character.name:n.characterName!==void 0?n.characterName:r?.name||"",i=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(s=>s?.text??"").join(""):"";return{...n,text:i,character:{...n.character||{},name:o},characterName:o}}),Hn=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=W(e,n,{functions:ae});return ce(le(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},li=(e={})=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{payload:{actions:structuredClone(n?.actions||{})}}]))},se=({animations:e,animationsDef:t,resources:n,previousResourceId:r,currentResourceId:o,previousTargetId:i,currentTargetId:s,animationPath:l,idPrefix:c,allowIncomingUpdateFallback:a=!1})=>{if(!t)return;let u=r!=null&&r!==!1,f=o!=null&&o!==!1,d=i&&s&&i===s,p=Xo({hasPrevious:u,hasCurrent:f,previousResourceId:r,currentResourceId:o,sharedTarget:d});Ko(t,l);let g=Go(t),y=n?.animations?.[g],b=Ho(y,{animationId:g,animationPath:l}),m=a&&b==="update"&&p!=="update"&&f&&s;if(m||Jo({animationType:b,animationId:g,animationPath:l,lifecycle:p}),b==="update"){u&&f&&r===o&&d?we({animations:e,resources:n,animationId:g,instanceId:`${c}-animation-update`,targetId:s,animationPath:l}):m&&we({animations:e,resources:n,animationId:g,instanceId:`${c}-animation-update`,targetId:s,animationPath:l});return}if(b==="transition"){if(u&&f&&d){we({animations:e,resources:n,animationId:g,instanceId:`${c}-animation-transition`,targetId:s,animationPath:l});return}u&&we({animations:e,resources:n,animationId:g,instanceId:`${c}-animation-out`,targetId:i,animationPath:l}),f&&we({animations:e,resources:n,animationId:g,instanceId:`${c}-animation-in`,targetId:s,animationPath:l})}},ui=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),fi=(e,{presentationState:t,previousPresentationState:n,resources:r={},screen:o={width:1920,height:1080},isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:c,autoMode:a,skipMode:u,isChoiceVisible:f,canRollback:d,saveSlots:p=[]})=>{let{elements:g,animations:y}=e;if(t.background){let b=g.find(E=>E.id==="story");if(!b)return e;let m=Qo(r,t.background),I=n?.background?.resourceId,x=t.background.resourceId??(t.background.animations?I:void 0),w=Pn(r,I),R=Pn(r,x);if(x){let{images:E={},videos:L={}}=r,$=E[x]||L[x];if($){let A=L[x]!==void 0,k={x:(o?.width??1920)/2,y:(o?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...m},B={id:ze({resourceId:x,kind:A?"video":"sprite"}),type:A?"video":"sprite",x:k.x,y:k.y,src:$.fileId,width:$.width,height:$.height,alpha:1,anchorX:k.anchorX,anchorY:k.anchorY,rotation:k.rotation,scaleX:k.scaleX,scaleY:k.scaleY};A&&(B.loop=t.background.loop??!1,B.volume=$.volume??50),b.children.push(B)}}if(x){let{layouts:E={}}=r,L=E[x];if(L){let $={id:ze({resourceId:x,kind:"container"}),type:"container",children:L.elements};m&&Object.assign($,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...m});let A=W($,X({variables:l,runtime:c,saveSlots:p,isLineCompleted:i,autoMode:a,skipMode:u,isChoiceVisible:f,canRollback:d,skipTransitionsAndAnimations:s}),{functions:ae});b.children.push(ce(le(A,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r))}}t.background.animations&&!i&&!s&&se({animations:y,animationsDef:t.background.animations,resources:r,previousResourceId:I,currentResourceId:x,previousTargetId:ze({resourceId:I,kind:w}),currentTargetId:ze({resourceId:x,kind:R}),animationPath:"background.animations",idPrefix:"bg-cg",allowIncomingUpdateFallback:!0})}return e},di=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i})=>{let{elements:s,animations:l}=e;if(t.character&&r){let c=s.find(p=>p.id==="story");if(!c)return e;let a=t.character.items||[],u=n?.character?.items||[],f=On(a),d=On(u);for(let p=0;p<a.length;p++){let g=a[p],{transformId:y,sprites:b}=g,m=u.find(A=>A.id===g.id),I=u.findIndex(A=>A.id===g.id),x=m?.sprites&&m.sprites.length>0,w=b&&b.length>0,R=I>=0?Tn(m,I,d):void 0;if(g.animations&&!b&&!y&&x&&!o&&!i){se({animations:l,animationsDef:g.animations,resources:r,previousResourceId:R,currentResourceId:void 0,previousTargetId:R,currentTargetId:void 0,animationPath:`character.items[${p}].animations`,idPrefix:"character"});continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let E=Tn(g,p,f),L=r.transforms[y];if(!L){console.warn("Transform not found:",y);continue}let $={type:"container",id:E,x:g.x??L.x,y:g.y??L.y,anchorX:L.anchorX,anchorY:L.anchorY,rotation:L.rotation,scaleX:L.scaleX,scaleY:L.scaleY,children:[]};for(let A of b){let k=r.images[A.resourceId];if(!k){console.warn(`Image resource not found: ${A.resourceId}`);continue}$.children.push({type:"sprite",id:`${E}-${A.id}`,src:k.fileId,width:k.width,height:k.height,x:0,y:0})}c.children.push($),g.animations&&!o&&!i&&se({animations:l,animationsDef:g.animations,resources:r,previousResourceId:R,currentResourceId:E,previousTargetId:R,currentTargetId:E,animationPath:`character.items[${p}].animations`,idPrefix:"character"})}}return e},pi=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:l,autoMode:c,skipMode:a,isChoiceVisible:u,canRollback:f,saveSlots:d=[]})=>{let{elements:p,animations:g}=e;if(t.visual&&r){let y=p.find(m=>m.id==="story");if(!y)return e;let b=t.visual.items;for(let m of b){if(m.resourceId){let{images:I={},videos:x={},spritesheets:w={}}=r,R=w[m.resourceId];if(R){let E=Rt(r,m),L=m.animationName;if(L){let $=R.animations?.[L];if(!$)throw new Error(`Animation '${L}' not found in spritesheet resource '${m.resourceId}'`);let A={id:`visual-${m.id}`,type:"animated-sprite",x:m.x??E.x,y:m.y??E.y,width:m.width??R.width,height:m.height??R.height,alpha:m.alpha??1,anchorX:E.anchorX,anchorY:E.anchorY,rotation:E.rotation,scaleX:E.scaleX,scaleY:E.scaleY,spritesheetSrc:R.fileId,spritesheetData:R.jsonData,animation:{frames:$.frames,animationSpeed:m.animationSpeed??$.animationSpeed??.5,loop:m.loop??$.loop??!0}};y.children.push(structuredClone(A))}}else{let E=I[m.resourceId]||x[m.resourceId];if(E){let L=x[m.resourceId]!==void 0,$=Rt(r,m),A={id:`visual-${m.id}`,type:L?"video":"sprite",src:E.fileId,width:E.width,height:E.height,x:$.x,y:$.y,anchorX:$.anchorX,anchorY:$.anchorY,rotation:$.rotation,scaleX:$.scaleX,scaleY:$.scaleY};L&&(A.loop=E.loop??!1,A.volume=E.volume??50),y.children.push(A)}}}if(m.resourceId){let{layouts:I={}}=r,x=I[m.resourceId];if(x){let w=Rt(r,m),R={id:`visual-${m.id}`,type:"container",children:structuredClone(x.elements),x:w.x,y:w.y,anchorX:w.anchorX,anchorY:w.anchorY,rotation:w.rotation,scaleX:w.scaleX,scaleY:w.scaleY},E=W(R,X({variables:s,runtime:l,saveSlots:d,isLineCompleted:o,autoMode:c,skipMode:a,isChoiceVisible:u,canRollback:f,skipTransitionsAndAnimations:i}),{functions:ae});y.children.push(ce(le(E,{isLineCompleted:o,skipMode:a,skipTransitionsAndAnimations:i}),r))}}if(m.animations&&!o&&!i){let x=(n?.visual?.items||[]).find(w=>w.id===m.id);se({animations:g,animationsDef:m.animations,resources:r,previousResourceId:x?.resourceId,currentResourceId:m.resourceId,previousTargetId:x?.resourceId?`visual-${m.id}`:void 0,currentTargetId:m.resourceId?`visual-${m.id}`:void 0,animationPath:`visual.items[${m.id}].animations`,idPrefix:m.id})}}}return e},hi=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,canRollback:c,skipOnlyViewedLines:a,isLineCompleted:u,skipTransitionsAndAnimations:f,variables:d,runtime:p,saveSlots:g=[]})=>{let{elements:y,animations:b}=e;if(!t.dialogue||o)return e;let m=y.find(I=>I.id==="story");if(!m)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:I={}}=r,x=I[t.dialogue.ui.resourceId];if(x){let w;t.dialogue.characterId&&(w=r.characters[t.dialogue.characterId]),t.dialogue.character&&(w={...w,name:t.dialogue.character.name});let R={elements:x.elements},E=t.dialogue?.content===void 0?[{text:""}]:kn(t.dialogue.content,"dialogue.content"),L=(t.dialogue?.lines||[]).map((O,H)=>{let Y=kn(O.content,`dialogue.lines[${H}].content`),V=O.character?.name!==void 0?O.character.name:O.characterName!==void 0?O.characterName:O.characterId&&r.characters?.[O.characterId]?.name||"";return{...O,content:Y.map(ke=>({...ke,text:$n(ke.text,{variables:d})})),character:{...O.character||{},name:V},characterName:V}}),$=X({variables:d,runtime:p,isLineCompleted:u,autoMode:i,skipMode:s,isChoiceVisible:l,canRollback:c,dialogueUIHidden:o,skipOnlyViewedLines:a,skipTransitionsAndAnimations:f}).runtime,A={variables:d,runtime:$,isChoiceVisible:l,canRollback:c,saveSlots:g,dialogueLines:L,dialogue:{characterId:t.dialogue.characterId,persistCharacter:t.dialogue.persistCharacter,character:{...t.dialogue.character||{},name:w?.name||""},content:E.map(O=>({...O,text:$n(O.text,{variables:d})})),lines:L}},k={functions:ae},B=We(R,A,k),C=W(B,A,k),S=ce(le(C?.elements,{isLineCompleted:u,skipMode:s,skipTransitionsAndAnimations:f}),r);if(Array.isArray(S))for(let O of S)m.children.push(O);else S&&m.children.push(S)}}return t.dialogue.ui?.animations&&!u&&!f&&se({animations:b,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"}),e},gi=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:c,autoMode:a,skipMode:u,isChoiceVisible:f,canRollback:d,saveSlots:p=[]})=>{let{elements:g,animations:y}=e;if(t.choice&&r){let b=He(g);if(!b)return e;let m=r?.layouts[t.choice.resourceId];if(m&&m.elements){let I={elements:m.elements},x=W(I,{...X({variables:l,runtime:c,saveSlots:p,isLineCompleted:i,autoMode:a,skipMode:u,isChoiceVisible:f??!!t.choice,canRollback:d,skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:ae}),w=Pt(ce(le(x?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r));if(Array.isArray(w))for(let R of w)b.children.push(R);else w&&b.children.push(w)}t.choice.animations&&!i&&!s&&se({animations:y,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"})}return e},mi=(e,{presentationState:t,resources:n={},variables:r,runtime:o,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,saveSlots:u=[],skipTransitionsAndAnimations:f})=>{if(!t.control?.resourceId)return e;let d=n.controls?.[t.control.resourceId];if(!d)return e;let p=li(d.keyboard);if(p&&Object.keys(p).length>0&&(e.global.keyboard=p),!Array.isArray(d.elements)||d.elements.length===0)return e;let g=He(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(Hn({container:y,resources:n,templateData:X({variables:r,runtime:o,saveSlots:u,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,skipTransitionsAndAnimations:f}),isLineCompleted:i,skipMode:l,skipTransitionsAndAnimations:f})),e},yi=(e,{presentationState:t,resources:n,runtime:r,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&n){if(!He(i))return e;let c=n.sounds[t.bgm.resourceId];if(!c)return e;let a=X({variables:o,runtime:r}).runtime;s.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:si(a),delay:t.bgm.delay??null})}return e},bi=(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},Ii=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(!t?.voice)return e;let{fileId:o,volume:i,loop:s}=t.voice;return r.push({id:`voice-${o}`,type:"sound",src:o,volume:i??50,loop:s??!1}),e},xi=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,saveSlots:u=[],isLineCompleted:f,skipTransitionsAndAnimations:d})=>{let{elements:p,animations:g}=e;if(t.layout){let y=He(p);if(!y)return e;let b=r.layouts[t.layout.resourceId];if(!b)return e;Array.isArray(b.transitions)&&!f&&!d&&Dt({animations:g,transitions:b.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let m={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:b.elements||[]};y.children.push(Hn({container:m,resources:r,templateData:X({variables:o,runtime:i,saveSlots:u,isLineCompleted:f,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,skipTransitionsAndAnimations:d}),isLineCompleted:f,skipMode:l,skipTransitionsAndAnimations:d}))}if(t.layout?.animations&&!f&&!d){let y=n?.layout?.resourceId,b=t.layout?.resourceId;se({animations:g,animationsDef:t.layout.animations,resources:r,previousResourceId:y,currentResourceId:b,previousTargetId:y?`layout-${y}`:void 0,currentTargetId:b?`layout-${b}`:void 0,animationPath:"layout.animations",idPrefix:"layout"})}return e},Ai=(e,{resources:t={},variables:n,runtime:r,autoMode:o,skipMode:i,isChoiceVisible:s,canRollback:l,overlayStack:c=[],dialogueHistory:a=[],saveSlots:u=[],screen:f,isLineCompleted:d,skipTransitionsAndAnimations:p})=>{let{elements:g,animations:y}=e;return c&&c.length>0&&c.forEach((b,m)=>{let I=t.layouts[b.resourceId];if(!I){console.warn(`Overlay layout not found: ${b.resourceId}`);return}Array.isArray(I.transitions)&&(p||Dt({animations:y,transitions:I.transitions,defaultTargetId:`overlayStack-${m}`,idPrefix:`overlayStack-${m}`,animationPathPrefix:`overlayStack[${m}]`}));let x={id:`overlayStack-${m}`,type:"container",x:0,y:0,children:[Wn({id:`overlayStack-${m}-blocker`,screen:f}),...I.elements||[]]},w=Yn(a,t.characters),R=X({variables:n,runtime:r,saveSlots:u,isLineCompleted:d,autoMode:o,skipMode:i,isChoiceVisible:s,canRollback:l,historyDialogue:w,characters:t.characters||{},skipTransitionsAndAnimations:p}),E=W(x,R,{functions:ae}),[L,...$]=E.children||[],A=ce(le({...E,children:$},{isLineCompleted:d,skipMode:i,skipTransitionsAndAnimations:p}),t);g.push({...A,children:L?[L,...A.children||[]]:A.children})}),e},vi=(e,{resources:t={},variables:n,runtime:r,saveSlots:o=[],autoMode:i,skipMode:s,isChoiceVisible:l,canRollback:c,confirmDialog:a,dialogueHistory:u=[],screen:f,isLineCompleted:d,skipTransitionsAndAnimations:p})=>{let{elements:g,animations:y}=e;if(!a?.resourceId)return e;let b=t.layouts?.[a.resourceId];if(!b)return console.warn(`ConfirmDialog layout not found: ${a.resourceId}`),e;Array.isArray(b.transitions)&&!p&&Dt({animations:y,transitions:b.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let m={id:"confirmDialog",type:"container",x:0,y:0,children:[Wn({id:"confirmDialog-blocker",screen:f}),...b.elements||[]]},I=Yn(u,t.characters),x=W(m,X({variables:n,runtime:r,saveSlots:o,isLineCompleted:d,autoMode:i,skipMode:s,isChoiceVisible:l,canRollback:c,confirmDialog:a,historyDialogue:I,characters:t.characters||{},skipTransitionsAndAnimations:p}),{functions:ae}),[w,...R]=x.children||[],E=ce(le({...x,children:R},{isLineCompleted:d,skipMode:s,skipTransitionsAndAnimations:p}),t);return g.push({...E,children:w?[w,...E.children||[]]:E.children}),e},Gn=e=>Be(ui,[mi,fi,di,pi,hi,gi,xi,yi,bi,Ii,Ai,vi])(e);var wi=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"}}),Ge=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),Le=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),qn=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"}),Mt=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),jt=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Ei=(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]}},Bt=e=>Object.fromEntries(Object.entries(wi).map(([t,n])=>{let r=Ei(e,n.source),o=r!==void 0?r:Ge[t]??Le[t];return[t,o]})),J=(e,t)=>Bt(e)[t],Kn=(e={})=>Object.fromEntries(Mt.map(t=>[t,e[t]??Ge[t]]));var qe={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},er=1,Je=()=>({manual:{...qe.manual},auto:{...qe.auto},applyMode:qe.applyMode}),Ft=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...Je()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},D=e=>{let t=ee(e)?ht(e):e;return structuredClone(t)},N=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ze=e=>String(e),Ut=()=>({sections:[],resources:[]}),Ke=()=>({sectionId:void 0,lineId:void 0}),_i=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Li=()=>({resourceId:void 0}),Ci=e=>{if(!N(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},tr=(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}},nr=e=>{let t=e?.story?.scenes??{},n=new Map;for(let[r,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let l=n.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${r}". Section IDs must be globally unique.`);n.set(s,r)}}},rr=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},or=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==er)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Si=(e,t={})=>{let n;try{n=or(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:rr(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},Ri=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Si(t,n)])),ir=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:n})=>ea(n));return t.length>0?t:void 0},$i=e=>{!N(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!N(t))return;let n=ir(t.executedActions);if(n){t.executedActions=n;return}delete t.executedActions})},Xn=(e,t,n)=>{let r=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[r]:String(e)};if(!N(e))throw new Error(`Malformed save slot viewedRegistry.${t}[${n}] entry.`);if(typeof e[r]!="string"||e[r].length===0)throw new Error(`Malformed save slot viewedRegistry.${t}[${n}] entry: missing ${r}.`);if(t==="sections"){let o={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed save slot viewedRegistry.sections[${n}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(o.lastLineId=e.lastLineId),o}return{resourceId:e.resourceId}},ki=e=>{if(e===void 0)return Ut();if(!N(e))throw new Error("Malformed save slot viewedRegistry.");if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error("Malformed save slot viewedRegistry.sections.");if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error("Malformed save slot viewedRegistry.resources.");let t=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(t.map((r,o)=>{let i=Xn(r,"sections",o);return[i.sectionId,i]}))),resources:Object.values(Object.fromEntries(n.map((r,o)=>{let i=Xn(r,"resources",o);return[i.resourceId,i]})))}},zt=(e,t,n)=>{if(!N(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}=tr(t,r);if(!s)throw new Error(`Malformed save slot ${n}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(c=>c.id===o))throw new Error(`Malformed save slot ${n}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},Oi=(e,t)=>{if(!N(e)||typeof e.sectionId!="string"||e.sectionId.length===0||typeof e.lineId!="string"||e.lineId.length===0)return Ke();try{let n=zt(e,t,"contexts[*].pointers.history");return{sectionId:n.sectionId,lineId:n.lineId}}catch{return Ke()}},Ti=(e,t,n)=>{if(!N(e)||!Array.isArray(e.timeline))return Ce({pointer:t,replayStartIndex:1});let r=e.timeline.flatMap((l,c)=>{if(!N(l))return[];try{let a=zt(l,n,`rollback.timeline[${c}]`),u=Xe({sectionId:a.sectionId,lineId:a.lineId,rollbackPolicy:l.rollbackPolicy}),f=ir(D(l.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(r.length===0)return Ce({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 l=r.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);l>=0?o=l:(r.push(Xe({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}},Pi=(e,t,n)=>{if(!N(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=Yt(t),o=zt(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!N(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);if(e.runtime!==void 0&&!N(e.runtime))throw new Error(`Malformed save slot contexts[${n}].runtime entry.`);let i=Oi(e.pointers?.history,t),s=e.variables?D(e.variables):{},l=ji({loadedContextRuntime:N(e.runtime)?D(e.runtime):{}}),c={currentPointerMode:e.currentPointerMode==="history"&&i.lineId?"history":"read",pointers:{read:o,history:i},configuration:N(e.configuration)?D(e.configuration):{},views:Array.isArray(e.views)?D(e.views):[],bgm:N(e.bgm)?D(e.bgm):{resourceId:void 0},variables:{...r,...s},rollback:Ti(e.rollback,o,t)};return l&&(c.runtime=l),c},Ni=(e,t)=>{if(!N(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{viewedRegistry:ki(e.viewedRegistry),contexts:e.contexts.map((n,r)=>Pi(n,t,r))}},Di=(e,t)=>{if(!N(e))throw new Error("Malformed save slot.");let n=or(e.formatVersion);return{...e,formatVersion:n,state:Ni(e.state,t)}},Jn=(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=D(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},Vi=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Jn(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Jn(e.cancelActions,"cancelActions")}},be=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},ue=[],Zn="line",Wt="interaction",Xe=({sectionId:e,lineId:t,rollbackPolicy:n})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free"}),Yt=e=>{let{contextVariableDefaultValues:t}=vt(e??{});return D(t)},sr=()=>({...D(Le)}),ar=({loadedRuntime:e,runtimeIds:t,defaults:n={},path:r})=>{if(e===void 0)return{runtimeState:D(n),hasLoadedValues:!1};if(!N(e))throw new Error(`Malformed ${r}.`);let o=D(n),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=lr(s,D(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Mi=({loadedGlobalRuntime:e={}})=>ar({loadedRuntime:e,runtimeIds:Mt,defaults:Ge,path:"global.runtime"}).runtimeState,ji=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:n}=ar({loadedRuntime:e,runtimeIds:jt,defaults:sr(),path:"context.runtime"});return n?t:void 0},cr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Bi=e=>e.runtime?(jt.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=D(Le[t]))}),e.runtime):(e.runtime=sr(),e.runtime),Fi=e=>Kn(e.global),Ui=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Fi(e)}})},zi=e=>qn[e],Wi=(e,t)=>{let n=zi(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}"`)},lr=(e,t)=>(Wi(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),ur=(e,t,n)=>{let r=lr(t,n);if(t in Le){let o=cr(e);if(!o)return r;let i=Bi(o);return i[t]=r,r}return e.global[t]=r,r},fr=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:D(e),history:Ke()},configuration:{},views:[],bgm:Li(),variables:Yt(t),rollback:Ce({pointer:e})}),Yi=e=>{let t=e.contexts?.[e.contexts.length-1],n=t?.pointers?.read;if(!t||!n?.sectionId||!n?.lineId)return null;let r=fr({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=r,Hi(e),r},Hi=e=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,be(e),e.global.viewedRegistry=Ut(),e.global.nextLineConfig=Je(),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},Ce=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[Xe({sectionId:e.sectionId,lineId:e.lineId})]:[]}},de=(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=Ce({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},Ht=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=de(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(Xe(t)),r.currentIndex=r.timeline.length-1},Gi=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=ue[ue.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)},qi=({state:e},t={})=>{let n=t?.source===Zn?Zn:Wt,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?(ue.push({checkpointIndex:null,source:n}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),ue.push({checkpointIndex:o.currentIndex,source:n}),e)},Ki=({state:e})=>(ue.pop(),e),Z=(e,t,n)=>{let o=ue[ue.length-1]?.source??Wt;if(!ta(t,o))return;let i=Gi(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:D(n)}))},Qn=(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 l=e.projectData.resources?.variables?.[o],c=l?.scope,a=l?.type;wt(c,o),Et(a,i,o),c==="context"&&(n.variables[o]=_t(n.variables[o],i,s))}},Xi=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:n,payload:r})=>{na(e,n,r)})},Ji=(e,t)=>{let{sectionId:n,lineId:r}=t,s=j({state:e},{sectionId:n})?.lines?.find(l=>l.id===r)?.actions;s&&Object.entries(s).forEach(([l,c])=>{ra(e,l,c)})},pr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=de(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Re({state:e}),e.global.skipMode&&fe({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=Yt(e.projectData),delete n.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=D(qe),e.global.overlayStack=[],be(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let s=i;s<=t;s++)s>i&&Ft(e),Ji(e,r.timeline[s]),Xi(e,r.timeline[s]);n.pointers.read={sectionId:o.sectionId,lineId:o.lineId},n.currentPointerMode="read",n.pointers?.history&&(n.pointers.history={sectionId:null,lineId:null}),e.global.pendingEffects=e.global.pendingEffects.filter(s=>s?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},Zi=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={},runtime:i={}}=n;nr(t);let s=t.story.initialSceneId,l=t.story.scenes[s],c=l.initialSectionId,a=l.sections[c],u={sceneId:s,sectionId:c,lineId:a.initialLineId??a.lines[0].id},{globalVariablesDefaultValues:f}=vt(t),d={...f,...o};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,viewedRegistry:Ut(),nextLineConfig:Je(),saveSlots:Ri(r),overlayStack:[],variables:d,...Mi({loadedGlobalRuntime:i})},contexts:[fr({pointer:u,projectData:t})]}},Qi=({state:e})=>e.global.overlayStack||[],es=({state:e})=>e.global.pendingEffects,hr=({state:e})=>e.global.skipMode,ts=({state:e})=>e.global.autoMode,gr=({state:e})=>e.global.dialogueUIHidden,mr=({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=j({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),l=i.lines.slice(0,s+1),c=[],a={};for(let u of l){let f=u.actions||{};if(a=me([a,f]),!f.dialogue)continue;let d=a.dialogue||{},p="";d.character?.name!==void 0?p=d.character.name:d.characterId&&(p=e.projectData.resources?.characters?.[d.characterId]?.name||""),c.push({sectionId:r,lineId:u.id,content:f.dialogue.content,text:_i(f.dialogue.content),characterId:d.characterId,character:{name:p},characterName:p})}return c},ns=({state:e})=>e.global.confirmDialog??null,Gt=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.global.viewedRegistry.sections.find(c=>c.sectionId===n);if(!o)return!1;if(o.lastLineId===void 0||r===void 0)return!0;let i=j({state:e},{sectionId:n});if(!i||!i.lines||!Array.isArray(i.lines))return o.lastLineId===r;let s=i.lines.findIndex(c=>c.id===o.lastLineId),l=i.lines.findIndex(c=>c.id===r);return s===-1||l===-1?o.lastLineId===r:l<=s},rs=({state:e},t)=>{let{resourceId:n}=t;return!!e.global.viewedRegistry.resources.find(o=>o.resourceId===n)},os=({state:e})=>e.global.nextLineConfig,yr=({state:e,pointer:t}={})=>{let n=t??q({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=j({state:e},{sectionId:r})?.lines||[],l=s.findIndex(a=>a.id===o);if(l<0)return;let c;for(let a of s.slice(0,l+1)){let u=a?.actions;if(u?.cleanAll&&(c=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){c=void 0;continue}let f=u.choice;if(f?.resourceId){c=f.resourceId;continue}f?.animations||(c=void 0)}return c},K=({state:e})=>!!yr({state:e}),is=({state:e})=>structuredClone(e),br=({state:e})=>e.global.saveSlots,ss=({state:e},t)=>{let n=t?.slotId,r=Ze(n);return e.global.saveSlots[r]},qt=({state:e})=>Bt(e),as=({state:e},t)=>J(e,t?.runtimeId),Ir=({state:e})=>({...e.global?.variables??{},...cr(e)?.variables??{}}),q=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(!n)return;let r=n.pointers?.[n.currentPointerMode];return{currentPointerMode:n.currentPointerMode,pointer:r}},j=({state:e},t)=>{let{sectionId:n}=t;return tr(e.projectData,n).section},xr=({state:e})=>{let t=q({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=j({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},Ar=({state:e})=>{let{sectionId:t,lineId:n}=q({state:e}).pointer,o=j({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===n),l=o.slice(0,i+1).map(a=>{let u=a.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return me(l)},cs=({state:e})=>{let t=vr({state:e}),r=xr({state:e})?.actions??{},o=me([t??{},r]);return Ct(t??{},o??{})},ls=({state:e},{sectionId:t})=>{let n=j({state:e},{sectionId:t});if(!n?.lines)return[];let r=[],o={};for(let i of n.lines){let s=i.actions||{},l=me([o,s]),c=Ct(o,l);r.push({id:i.id,changes:c,presentationState:l}),o=St(l)}return r},us=({state:e},{sectionId:t,includePresentationState:n=!1})=>{let r=ls({state:e},{sectionId:t});return n?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},vr=({state:e})=>{let{sectionId:t,lineId:n}=q({state:e}).pointer,o=j({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n);if(i<=0)return null;let l=o.slice(0,i).map(c=>{let a=c.actions||{},u={};return Object.keys(a).forEach(f=>{u[f]=a[f]}),u});return St(me(l))},Kt=({state:e},{slotsPerPage:t=6}={})=>{let o=((qt({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let l=o+s,c=e.global.saveSlots&&e.global.saveSlots[Ze(l)]||{};i.push({...c,slotId:l})}return{saveSlots:i}},fs=br,ds=Kt,ps=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},hs=({state:e})=>{let t=Ar({state:e}),n=vr({state:e}),r=qt({state:e}),o=Ir({state:e}),{saveSlots:i}=Kt({state:e}),s=ps(e);return Gn({presentationState:t,previousPresentationState:n,resources:e.projectData.resources,screen:e.projectData.screen,dialogueUIHidden:r.dialogueUIHidden,autoMode:r.autoMode,skipMode:r.skipMode,isChoiceVisible:K({state:e}),canRollback:Rr({state:e}),skipOnlyViewedLines:!r.skipUnseenText,isLineCompleted:r.isLineCompleted,skipTransitionsAndAnimations:!!r.skipTransitionsAndAnimations||s,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,dialogueHistory:mr({state:e}),saveSlots:i,variables:o,runtime:r})},gs=({state:e},t)=>(e.global.confirmDialog=Vi(t),e.global.pendingEffects.push({name:"render"}),e),ms=({state:e})=>(e.global.confirmDialog&&(be(e),e.global.pendingEffects.push({name:"render"})),e),ys=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Z(e,"pushOverlay",t),e),bs=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Z(e,"popOverlay",void 0),e),Is=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),Z(e,"replaceLastOverlay",t),e),xs=({state:e})=>(e.global.overlayStack=[],be(e),e.global.pendingEffects.push({name:"render"}),Z(e,"clearOverlays",void 0),e),As=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"})},Qe=(e,t)=>{e.global.isLineCompleted=!1;let n=!!yr({state:e,pointer:t});return n&&As(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:n}},wr=({state:e})=>(K({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:J(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),Re=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),vs=({state:e})=>{let t=e.global.autoMode;return K({state:e})&&!t||(t?Re({state:e}):wr({state:e})),e},Er=({state:e})=>(K({state:e})||(e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode=!0,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"startSkipNextTimer"}),e.global.pendingEffects.push({name:"render"})),e),fe=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),ws=({state:e})=>{let t=hr({state:e});return K({state:e})&&!t||(t?fe({state:e}):Er({state:e})),e},et=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Z(e,"showDialogueUI",void 0),e),_r=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Z(e,"hideDialogueUI",void 0),e),Es=({state:e})=>(gr({state:e})?et({state:e}):_r({state:e}),e),pe=(e,t,n)=>(ur(e,t,n),Ui(e),e.global.pendingEffects.push({name:"render"}),e),$e=(e,t,n,r)=>{let o=ur(e,t,n);return e.global.pendingEffects.push({name:"render"}),Z(e,r,{value:o}),e},_s=({state:e},t)=>pe(e,"dialogueTextSpeed",t?.value),Ls=({state:e},t)=>pe(e,"autoForwardDelay",t?.value),Cs=({state:e},t)=>pe(e,"skipUnseenText",t?.value),Ss=({state:e},t)=>pe(e,"skipTransitionsAndAnimations",t?.value),Rs=({state:e},t)=>pe(e,"soundVolume",t?.value),$s=({state:e},t)=>pe(e,"musicVolume",t?.value),ks=({state:e},t)=>pe(e,"muteAll",t?.value),Os=({state:e},t)=>$e(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),Ts=({state:e})=>{let t=J(e,"saveLoadPagination")+1;return $e(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},Ps=({state:e})=>{let t=J(e,"saveLoadPagination")-1;return $e(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},Ns=({state:e},t)=>$e(e,"menuPage",t?.value,"setMenuPage"),Ds=({state:e},t)=>$e(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Vs=({state:e})=>(e.global.pendingEffects=[],e),Ms=({state:e},t)=>(e.global.pendingEffects.push(t),e),Lr=(e,{sectionId:t,resetStoryState:n=!1})=>{let r=j({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&&!Yi(e))return e;e.global.autoMode&&Re({state:e}),e.global.skipMode&&fe({state:e});let i=e.contexts?.[e.contexts.length-1];return i&&(i.rollback||de(i,{compatibilityAnchor:!0}),i.pointers.read={sectionId:t,lineId:o.id},n?i.rollback=Ce({pointer:i.pointers.read}):Ht(e,{sectionId:t,lineId:o.id})),Qe(e,i?.pointers?.read),e},js=({state:e},t)=>Lr(e,{sectionId:t?.sectionId,resetStoryState:!0}),Se=(e,{sectionId:t,lineId:n})=>{e.global.viewedRegistry||(e.global.viewedRegistry={}),Array.isArray(e.global.viewedRegistry.sections)||(e.global.viewedRegistry.sections=[]);let r=e.global.viewedRegistry.sections.find(o=>o.sectionId===t);if(r){let o=j({state:e},{sectionId:t});if(o?.lines&&r.lastLineId!==void 0){let i=o.lines.findIndex(l=>l.id===r.lastLineId),s=o.lines.findIndex(l=>l.id===n);(i===-1||s>i)&&(r.lastLineId=n)}else r.lastLineId=n}else e.global.viewedRegistry.sections.push({sectionId:t,lastLineId:n})},Bs=({state:e},t)=>(Se(e,t),e.global.pendingEffects.push({name:"render"}),e),Fs=({state:e},t)=>{let{resourceId:n}=t;return e.global.viewedRegistry.resources.find(o=>o.resourceId===n)||e.global.viewedRegistry.resources.push({resourceId:n}),e.global.pendingEffects.push({name:"render"}),e},Cr=({state:e},t)=>{let n=Ci(t.manual),{auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;n&&r?(e.global.nextLineConfig={manual:n,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let c=e.global.nextLineConfig.auto?.enabled,a=K({state:e});return!l&&!a&&c===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!l&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),Z(e,"setNextLineConfig",t),e},Us=({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=Ze(n),s=D(e.contexts);s?.forEach(a=>{dr(a.rollback),$i(a.rollback)});let l={contexts:s,viewedRegistry:D(e.global.viewedRegistry)},c={formatVersion:er,slotId:rr(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:l};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},zs=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=Ze(n),o=e.global.saveSlots[r];if(o){let i=Di(o,e.projectData);e.global.viewedRegistry=i.state.viewedRegistry,e.contexts=i.state.contexts,e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=Je(),e.global.overlayStack=[],e.global.isLineCompleted=!0,be(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},Ws=({state:e},t)=>{let{projectData:n}=t;return nr(n),e.projectData=n,be(e),e.global.pendingEffects.push({name:"render"}),e},Ys=({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&&!j({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=j({state:e},{sectionId:i});return!s?.lines||!Array.isArray(s.lines)?(console.warn(`Section ${i} has no lines`),e):s.lines.find(c=>c.id===r)?(o.pointers.read={sectionId:i,lineId:r},Qe(e,o.pointers.read),e):(console.warn(`Line not found: ${r} in section ${i}`),e)},Hs=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return et({state:e}),e;if(K({state:e})&&t?._interactionSource!=="choice")return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0;let a=q({state:e})?.pointer,u=a?.sectionId,f=a?.lineId;u&&f&&Se(e,{sectionId:u,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:J(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=q({state:e})?.pointer,r=n?.sectionId,o=j({state:e},{sectionId:r}),i=e.contexts[e.contexts.length-1],s=o?.lines||[],c=s.findIndex(a=>a.id===n?.lineId)+1;if(c<s.length){let a=s[c],u=!J(e,"skipUnseenText");if(e.global.skipMode&&u&&!Gt({state:e},{sectionId:r,lineId:a.id}))return fe({state:e}),e;if(i&&!i.rollback&&de(i,{compatibilityAnchor:!0}),i){let p=i.pointers.read.lineId;p&&r&&Se(e,{sectionId:r,lineId:p}),i.pointers.read={sectionId:r,lineId:a.id}}Ht(e,{sectionId:r,lineId:a.id}),Ft(e);let{isChoiceVisible:f}=Qe(e,{sectionId:r,lineId:a.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&&Re({state:e}),e.global.skipMode&&fe({state:e});return e},Gs=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0;let t=K({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:J(e,"autoForwardDelay")}});let n=q({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&Se(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},qs=({state:e},t)=>{let n=t?.sectionId??q({state:e})?.pointer?.sectionId,r=j({state:e},{sectionId:n});if(!r||!r.lines||r.lines.length===0)return e;let o=r.lines,i=e.contexts[e.contexts.length-1];if(!i||!i.pointers)return e;let s=i.pointers.history||i.pointers.read;if(i.currentPointerMode!=="history"||!i.pointers.history){if(!s)return e;i.currentPointerMode="history",i.pointers.history={sectionId:n,lineId:s?.lineId};let u=o.findIndex(f=>f.id===s.lineId)-1;if(u>=0&&u<o.length){let f=o[u];i.pointers.history={sectionId:n,lineId:f.id}}return e.global.pendingEffects.push({name:"render"}),e}let c=o.findIndex(a=>a.id===i.pointers.history.lineId)-1;if(c>=0&&c<o.length){let a=o[c];i.pointers.history={sectionId:n,lineId:a.id},e.global.pendingEffects.push({name:"render"})}return e},Ks=({state:e},t)=>Lr(e,{sectionId:t?.sectionId}),Xs=({state:e})=>{if(e.global.dialogueUIHidden)return et({state:e}),e;if(K({state:e}))return e;let t=q({state:e})?.pointer,n=t?.sectionId,r=j({state:e},{sectionId:n}),o=e.contexts[e.contexts.length-1],i=r?.lines||[],l=i.findIndex(c=>c.id===t?.lineId)+1;if(l<i.length){let c=i[l],a=!J(e,"skipUnseenText");if(e.global.skipMode&&a&&!Gt({state:e},{sectionId:n,lineId:c.id}))return fe({state:e}),e;if(o&&!o.rollback&&de(o,{compatibilityAnchor:!0}),o){let f=o.pointers.read.lineId;f&&n&&Se(e,{sectionId:n,lineId:f}),o.pointers.read={sectionId:n,lineId:c.id}}Ht(e,{sectionId:n,lineId:c.id}),Ft(e);let{isChoiceVisible:u}=Qe(e,{sectionId:n,lineId:c.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},Js=({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=!1,l=!1,c=[];if(r.forEach(({variableId:a,op:u,value:f})=>{let d=e.projectData.resources?.variables?.[a],p=d?.scope,g=d?.type;wt(p,a),Et(g,u,a);let y=p==="context"?o.variables:e.global.variables;p==="context"?(i=!0,c.push({variableId:a,op:u,value:f})):p==="device"?s=!0:p==="account"&&(l=!0),y[a]=_t(y[a],u,f)}),i&&Z(e,"updateVariable",{id:n,operations:c}),s){let a=Lt(e.global.variables,e.projectData.resources?.variables,"device");e.global.pendingEffects.push({name:"saveGlobalDeviceVariables",payload:{globalDeviceVariables:a}})}if(l){let a=Lt(e.global.variables,e.projectData.resources?.variables,"account");e.global.pendingEffects.push({name:"saveGlobalAccountVariables",payload:{globalAccountVariables:a}})}return e.global.pendingEffects.push({name:"render"}),e},Zs=e=>(t,n)=>e({state:t},n),Qs={updateVariable:{recordSources:[Wt],replayLine:Qn,replayRecorded:Qn,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Zs(Cr)}},tt=e=>Qs[e]??null,ea=e=>tt(e)?.persistInSaveSlot===!0,ta=(e,t)=>{let n=tt(e)?.recordSources;return Array.isArray(n)&&n.includes(t)},na=(e,t,n)=>{tt(t)?.replayRecorded?.(e,n)},ra=(e,t,n)=>{tt(t)?.replayLine?.(e,n)},Sr=({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}},Rr=({state:e})=>Sr({state:e},{offset:-1})!==null,oa=({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=de(r,{compatibilityAnchor:!r.rollback}),i=o.currentIndex+n;return i<0||i>=o.timeline.length?e:pr(e,i)},ia=({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=de(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===n&&c.lineId===r);if(l===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return l===i.currentIndex?e:pr(e,l)},$r=e=>{let t=Zi(e);return _n(t,{selectPendingEffects:es,selectSkipMode:hr,selectAutoMode:ts,selectIsChoiceVisible:K,selectDialogueUIHidden:gr,selectDialogueHistory:mr,selectConfirmDialog:ns,selectIsLineViewed:Gt,selectIsResourceViewed:rs,selectNextLineConfig:os,selectSystemState:is,selectSaveSlotMap:br,selectSaveSlots:fs,selectSaveSlot:ss,selectRuntime:qt,selectRuntimeValue:as,selectAllVariables:Ir,selectCurrentPointer:q,selectSection:j,selectCurrentLine:xr,selectPresentationState:Ar,selectPresentationChanges:cs,selectSectionLineChanges:us,selectSaveSlotPage:Kt,selectCurrentPageSlots:ds,selectRenderState:hs,selectOverlayStack:Qi,selectLineIdByOffset:Sr,selectCanRollback:Rr,startAutoMode:wr,stopAutoMode:Re,toggleAutoMode:vs,startSkipMode:Er,stopSkipMode:fe,toggleSkipMode:ws,showDialogueUI:et,hideDialogueUI:_r,toggleDialogueUI:Es,setDialogueTextSpeed:_s,setAutoForwardDelay:Ls,setSkipUnseenText:Cs,setSkipTransitionsAndAnimations:Ss,setSoundVolume:Rs,setMusicVolume:$s,setMuteAll:ks,setSaveLoadPagination:Os,incrementSaveLoadPagination:Ts,decrementSaveLoadPagination:Ps,setMenuPage:Ns,setMenuEntryPoint:Ds,showConfirmDialog:gs,hideConfirmDialog:ms,resetStoryAtSection:js,clearPendingEffects:Vs,appendPendingEffect:Ms,beginRollbackActionBatch:qi,endRollbackActionBatch:Ki,addViewedLine:Bs,addViewedResource:Fs,setNextLineConfig:Cr,saveSlot:Us,loadSlot:zs,updateProjectData:Ws,sectionTransition:Ks,jumpToLine:Ys,nextLine:Hs,markLineCompleted:Gs,prevLine:qs,rollbackToLine:ia,rollbackByOffset:oa,pushOverlay:ys,popOverlay:bs,replaceLastOverlay:Is,clearOverlays:xs,updateVariable:Js,nextLineFromSystem:Xs},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var sa="route-engine",aa="projectPersistence";var kr=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{}}),Q=e=>Object.prototype.toString.call(e)==="[object Object]",Or=(e={})=>{let t=Q(e)?e:{};return{saveSlots:Q(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:Q(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:Q(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:Q(t.globalRuntime)?t.globalRuntime:{}}},Xt=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},ca=e=>{let t=Xt(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},la=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},ua=({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}".`))}}),fa=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let c=r.transaction(t,"readonly").objectStore(t).get(n);c.onsuccess=()=>{o(c.result??null)},c.onerror=()=>{i(c.error??new Error(`Failed to read persisted namespace "${n}" from IndexedDB.`))}})},nt=async({databasePromise:e,objectStoreName:t,namespace:n,patch:r})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),c=l.objectStore(t),a=c.get(n),u=!1,f=p=>{u||(u=!0,s(p))},d=()=>{u||(u=!0,i())};a.onerror=()=>{f(a.error??new Error(`Failed to read persisted namespace "${n}" before updating IndexedDB.`))},a.onsuccess=()=>{let p=Or(a.result),g={namespace:n,version:1,...kr(),...p,...r},y=c.put(g);y.onerror=()=>{f(y.error??new Error(`Failed to persist namespace "${n}" to IndexedDB.`))}},l.oncomplete=()=>{d()},l.onerror=()=>{f(l.error??new Error(`IndexedDB transaction failed while updating namespace "${n}".`))},l.onabort=()=>{f(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${n}".`))}})},da=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let s=r.transaction(t,"readwrite"),c=s.objectStore(t).delete(n),a=!1,u=d=>{a||(a=!0,i(d))},f=()=>{a||(a=!0,o())};c.onerror=()=>{u(c.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}".`))}})},Jt=(e={})=>{let{indexedDB:t,databaseName:n=sa,objectStoreName:r=aa,namespace:o}=e,i=la(t),s=ca(o),l=ua({indexedDB:i,databaseName:n,objectStoreName:r});return{namespace:s,load:async()=>{let c=await fa({databasePromise:l,objectStoreName:r,namespace:s});return{...kr(),...Or(c)}},clear:async()=>da({databasePromise:l,objectStoreName:r,namespace:s}),saveSlots:async c=>nt({databasePromise:l,objectStoreName:r,namespace:s,patch:{saveSlots:Q(c)?c:{}}}),saveGlobalDeviceVariables:async c=>nt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:Q(c)?c:{}}}),saveGlobalAccountVariables:async c=>nt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalAccountVariables:Q(c)?c:{}}}),saveGlobalRuntime:async c=>nt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalRuntime:Q(c)?c:{}}})}},pa=Jt;function Zt(e){let t,n=0,r=null,{handlePendingEffects:o}=e,i=()=>{for(;t.selectPendingEffects().length>0;){let A=[...t.selectPendingEffects()];t.clearPendingEffects();try{o(A)}catch(k){throw t.clearPendingEffects(),A.forEach(B=>{t.appendPendingEffect(B)}),k}}},s=({initialState:A,namespace:k})=>{t=$r(A),n=0,r=Xt(k),t.appendPendingEffect({name:"handleLineActions"}),i()},l=()=>r,c=()=>t.selectPresentationState(),a=()=>t.selectPresentationChanges(),u=A=>t.selectSectionLineChanges(A),f=()=>(n+=1,{...t.selectRenderState(),id:`render-${n}`}),d=()=>t.selectSystemState(),p=()=>t.selectSaveSlotMap(),g=A=>t.selectSaveSlot(A),y=A=>t.selectSaveSlotPage(A),b=()=>t.selectSkipMode(),m=()=>t.selectAutoMode(),I=()=>t.selectRuntime(),x=()=>t.selectIsChoiceVisible(),w=(A,k)=>{t[A]&&(t[A](k),i())},R=(A,k)=>{w(A,k)},E=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:k,...B}=A,C=t.selectAllVariables?t.selectAllVariables():void 0;return{...B,_event:k,variables:C,runtime:t.selectRuntime?t.selectRuntime():{}}},L=(A,k,B={})=>{let C=E(k),S=Sn(A,C);t.beginRollbackActionBatch({source:B.rollbackSource});try{Object.entries(S).forEach(([O,H])=>{w(O,H)})}finally{t.endRollbackActionBatch({})}};return{init:s,handleAction:w,handleInternalAction:R,handleActions:L,selectRenderState:f,selectPresentationState:c,selectPresentationChanges:a,selectSectionLineChanges:u,selectSystemState:d,selectSaveSlotMap:p,selectSaveSlot:g,selectSaveSlotPage:y,selectSaveSlots:p,selectRuntime:I,selectIsChoiceVisible:x,handleLineActions:()=>{let A=t.selectCurrentLine();return A?.actions?(L(A.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:l}}var Qt=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},ha=80,Pr=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{let o=e.selectRenderState();n?.(o),t.render(o)},ga=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&Pr({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},ma=({engine:e,ticker:t,autoTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(t.remove(i),n.setCallback(null),n.setElapsed(0),rt(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},ya=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},ba=({engine:e,ticker:t,skipTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r?.delay??ha;n.getElapsed()>=l&&(n.setElapsed(0),rt(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Ia=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},xa=({engine:e,ticker:t,nextLineConfigTimerState:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(n.setElapsed(0),rt(e,"nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},Aa=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},va=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveSlots(t?.saveSlots))},wa=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalDeviceVariables(t?.globalDeviceVariables))},Ea=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalAccountVariables(t?.globalAccountVariables))},_a=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalRuntime(t?.globalRuntime))},Tr={render:Pr,saveSlots:va,saveGlobalDeviceVariables:wa,saveGlobalAccountVariables:Ea,saveGlobalRuntime:_a,handleLineActions:ga,startAutoNextTimer:ma,clearAutoNextTimer:ya,startSkipNextTimer:ba,clearSkipNextTimer:Ia,nextLineConfigTimer:xa,clearNextLineConfigTimer:Aa},La=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),rt=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},Ca=(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(!La.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},Sa=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let c=Qt(),a=Qt(),u=Qt(),f=s??null,d=Promise.resolve(),p=null,g=null,y=!1,b=0,m=C=>{if(o){o(C);return}console.error("RouteEngine persistence write failed.",C)},I=()=>{if(f)return f;let C=e();return f=Jt({indexedDB:i,namespace:l??C?.getNamespace?.()}),f},x=C=>{d=d.catch(()=>{}).then(()=>{let S=I();return C(S)}).catch(S=>{m(S)})},w=C=>{let S=typeof C?.id=="string"&&C.id.length>0?C.id:null;b+=1,p=S,y=!1},R=()=>b,E=(C={})=>{if(C?.aborted===!0)return!1;let S=typeof C?.id=="string"&&C.id.length>0?C.id:null;return S?S!==p||S===g?!1:(g=S,!0):p!==null||y?!1:(y=!0,!0)},L=(C,S={})=>{if(C!=="renderComplete"||!E(S))return!1;let O=e();return rt(O,"markLineCompleted",{}),!0},$=(C={})=>{if(C?._interactionSource==="choice")return!0;let S=C?.actions;return!S||typeof S!="object"||Array.isArray(S)?!1:Object.values(S).some(O=>O?._interactionSource==="choice")},A=(C,S={})=>!S?.actions||typeof C?.selectIsChoiceVisible!="function"||!C.selectIsChoiceVisible()?!1:!$(S),k=({preprocessPayload:C,onEvent:S}={})=>async(O,H={})=>{let Y=e();if(A(Y,H))return S?.(O,H);let V=await C?.(O,H)??H;if(A(Y,V))return S?.(O,V);if(L(O,V),V?.actions){let ke=V?._event?{_event:V._event}:V?.event?{_event:V.event}:void 0;Y.handleActions(V.actions,ke)}return S?.(O,V)},B=C=>{let S=e(),O=Ca(C);O.forEach(Y=>{if(!Tr[Y.name]&&!r)throw new Error(`Unhandled pending effect "${Y.name}".`)});let H={engine:S,routeGraphics:t,ticker:n,autoTimer:c,skipTimer:a,nextLineConfigTimerState:u,trackRenderDispatch:w,getRenderDispatchCount:R,enqueuePersistenceWrite:x};for(let Y of O){let V=Tr[Y.name];if(V){V(H,Y.payload);continue}r(Y,H)}};return B.handleRouteGraphicsEvent=L,B.createRouteGraphicsEventHandler=k,B},Ra=Sa;var $a=(e,t={})=>{let{resources:n={}}=t;return Vt(e,n)};var Dc=Zt;export{Ra as createEffectsHandler,pa as createIndexedDbPersistence,Dc as default,$a as resolveLayoutReferences};
|
package/package.json
CHANGED