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