route-engine-js 1.15.0 → 1.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/RouteEngine.js +1 -1
- package/package.json +1 -1
package/dist/RouteEngine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var mi=Object.defineProperty;var gi=(e,t)=>{for(var r in t)mi(e,r,{get:t[r],enumerable:!0})};var gn=Symbol.for("immer-nothing"),fn=Symbol.for("immer-draftable"),te=Symbol.for("immer-state");function se(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Fe=Object.getPrototypeOf;function re(e){return!!e&&!!e[te]}function Oe(e){return e?yn(e)||Array.isArray(e)||!!e[fn]||!!e.constructor?.[fn]||bt(e)||It(e):!1}var yi=Object.prototype.constructor.toString();function yn(e){if(!e||typeof e!="object")return!1;let t=Fe(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===yi}function ht(e,t){yt(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function yt(e){let t=e[te];return t?t.type_:Array.isArray(e)?1:bt(e)?2:It(e)?3:0}function Ht(e,t){return yt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function bn(e,t,r){let n=yt(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function bi(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function bt(e){return e instanceof Map}function It(e){return e instanceof Set}function Re(e){return e.copy_||e.base_}function Jt(e,t){if(bt(e))return new Map(e);if(It(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=yn(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[te];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],a=n[s];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(n[s]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[s]})}return Object.create(Fe(e),n)}else{let n=Fe(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function er(e,t=!1){return At(e)||re(e)||!Oe(e)||(yt(e)>1&&(e.set=e.add=e.clear=e.delete=Ii),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>er(n,!0))),e}function Ii(){se(2)}function At(e){return Object.isFrozen(e)}var Ai={};function $e(e){let t=Ai[e];return t||se(0,e),t}var Xe;function In(){return Xe}function wi(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function dn(e,t){t&&($e("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Gt(e){Xt(e),e.drafts_.forEach(vi),e.drafts_=null}function Xt(e){e===Xe&&(Xe=e.parent_)}function pn(e){return Xe=wi(Xe,e)}function vi(e){let t=e[te];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function hn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[te].modified_&&(Gt(t),se(4)),Oe(e)&&(e=mt(t,e),t.parent_||gt(t,e)),t.patches_&&$e("Patches").generateReplacementPatches_(r[te].base_,e,t.patches_,t.inversePatches_)):e=mt(t,r,[]),Gt(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==gn?e:void 0}function mt(e,t,r){if(At(t))return t;let n=t[te];if(!n)return ht(t,(o,i)=>mn(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return gt(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let o=n.copy_,i=o,s=!1;n.type_===3&&(i=new Set(o),o.clear(),s=!0),ht(i,(a,c)=>mn(e,n,o,a,c,r,s)),gt(e,o,!1),r&&e.patches_&&$e("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function mn(e,t,r,n,o,i,s){if(re(o)){let a=i&&t&&t.type_!==3&&!Ht(t.assigned_,n)?i.concat(n):void 0,c=mt(e,o,a);if(bn(r,n,c),re(c))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(Oe(o)&&!At(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;mt(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&>(e,o)}}function gt(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&er(t,r)}function Ei(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:In(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=tr;r&&(o=[n],i=Qe);let{revoke:s,proxy:a}=Proxy.revocable(o,i);return n.draft_=a,n.revoke_=s,a}var tr={get(e,t){if(t===te)return e;let r=Re(e);if(!Ht(r,t))return xi(e,r,t);let n=r[t];return e.finalized_||!Oe(n)?n:n===Yt(e.base_,t)?(Kt(e),e.copy_[t]=Zt(n,e)):n},has(e,t){return t in Re(e)},ownKeys(e){return Reflect.ownKeys(Re(e))},set(e,t,r){let n=An(Re(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=Yt(Re(e),t),i=o?.[te];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(bi(r,o)&&(r!==void 0||Ht(e.base_,t)))return!0;Kt(e),Qt(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return Yt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Kt(e),Qt(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Re(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){se(11)},getPrototypeOf(e){return Fe(e.base_)},setPrototypeOf(){se(12)}},Qe={};ht(tr,(e,t)=>{Qe[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Qe.deleteProperty=function(e,t){return Qe.set.call(this,e,t,void 0)};Qe.set=function(e,t,r){return tr.set.call(this,e[0],t,r,e[0])};function Yt(e,t){let r=e[te];return(r?Re(r):e)[t]}function xi(e,t,r){let n=An(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function An(e,t){if(!(t in e))return;let r=Fe(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=Fe(r)}}function Qt(e){e.modified_||(e.modified_=!0,e.parent_&&Qt(e.parent_))}function Kt(e){e.copy_||(e.copy_=Jt(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Ci=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,n)=>{if(typeof t=="function"&&typeof r!="function"){let i=r;r=t;let s=this;return function(c=i,...l){return s.produce(c,u=>r.call(this,u,...l))}}typeof r!="function"&&se(6),n!==void 0&&typeof n!="function"&&se(7);let o;if(Oe(t)){let i=pn(this),s=Zt(t,void 0),a=!0;try{o=r(s),a=!1}finally{a?Gt(i):Xt(i)}return dn(i,n),hn(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===gn&&(o=void 0),this.autoFreeze_&&er(o,!0),n){let i=[],s=[];$e("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else se(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...a)=>this.produceWithPatches(s,c=>t(c,...a));let n,o;return[this.produce(t,r,(s,a)=>{n=s,o=a}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Oe(e)||se(8),re(e)&&(e=Le(e));let t=pn(this),r=Zt(e,void 0);return r[te].isManual_=!0,Xt(t),r}finishDraft(e,t){let r=e&&e[te];(!r||!r.isManual_)&&se(9);let{scope_:n}=r;return dn(n,t),hn(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let o=t[r];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}r>-1&&(t=t.slice(r+1));let n=$e("Patches").applyPatches_;return re(e)?n(e,t):this.produce(e,o=>n(o,t))}};function Zt(e,t){let r=bt(e)?$e("MapSet").proxyMap_(e,t):It(e)?$e("MapSet").proxySet_(e,t):Ei(e,t);return(t?t.scope_:In()).drafts_.push(r),r}function Le(e){return re(e)||se(10,e),wn(e)}function wn(e){if(!Oe(e)||At(e))return e;let t=e[te],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=Jt(e,t.scope_.immer_.useStrictShallowCopy_)}else r=Jt(e,!0);return ht(r,(n,o)=>{bn(r,n,wn(o))}),t&&(t.finalized_=!1),r}var ne=new Ci,rr=ne.produce,_u=ne.produceWithPatches.bind(ne),Ru=ne.setAutoFreeze.bind(ne),Ou=ne.setUseStrictShallowCopy.bind(ne),$u=ne.applyPatches.bind(ne),Lu=ne.createDraft.bind(ne),ku=ne.finishDraft.bind(ne);var m={LITERAL:0,VARIABLE:1,INTERPOLATION:2,FUNCTION:3,BINARY:4,UNARY:5,CONDITIONAL:6,LOOP:7,OBJECT:8,ARRAY:9,PARTIAL:10,PATH_REFERENCE:11},R={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},Be={NOT:0};var v=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},Q=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var nr=e=>{if(!e||e.trim()==="")throw new v("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new v(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${r}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let r of t)if(e.trim().endsWith(r))throw new v(`Incomplete comparison expression - missing right operand (got: '${e}')`)},vn=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,r]=e.split(" in ");if(!r||r.trim()==="")throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);let n=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of n){if(!o)throw new 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 En=(e,t,r=!1)=>{if(t===null)return new Q(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new Q(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new Q(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new Q(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},xn=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new Q(`Unknown function '${e}' (${r})`)};var Si=(e,t,r={})=>{let n={},o={};r&&typeof r=="object"&&(r.functions!==void 0||r.partials!==void 0?(n=r.functions||{},o=r.partials||{}):typeof r=="object"&&(n=r));let s=$(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},$=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return Y(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return Y(e.path,r,n);if(e.type===m.INTERPOLATION)return Ri(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return Sn(e,t,r,n);case m.BINARY:return _n(e,t,r,n);case m.UNARY:return Rn(e,t,r,n);case m.CONDITIONAL:return $i(e,t,r,n);case m.LOOP:return Di(e,t,r,n);case m.OBJECT:return Vi(e,t,r,n);case m.ARRAY:return ji(e,t,r,n);case m.PARTIAL:return Mi(e,t,r,n);case m.PATH_REFERENCE:return Fi(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Cn=new Map,_i=e=>{let t=[],r="",n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")r&&(t.push({type:"property",value:r}),r=""),n=!0;else if(i==="]"){if(n&&r){let s=r.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let a=s.slice(1,-1);t.push({type:"property",value:a})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},Y=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=Cn.get(e);if(!n){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),n=[];for(let c of i){let l=_i(c.trim());n.push(...l)}Cn.set(e,n)}let o=t;for(let i=0;i<n.length;i++){let s=n[i];if(s.type==="property"&&s.value in r){o=r[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},Ri=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=$(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},Sn=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw xn(e.name,o);let s=e.args.map(a=>$(a,t,r,n));return i(...s)},we=(e,t,r,n)=>{if(e.var&&!e.type)return Y(e.var,r,n);switch(e.type){case m.VARIABLE:return Y(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return _n(e,t,r,n);case m.UNARY:return Rn(e,t,r,n);case m.FUNCTION:return Sn(e,t,r,n);default:return $(e,t,r,n)}},_n=(e,t,r,n)=>{if(e.op===R.AND||e.op===R.OR){let s=we(e.left,t,r,n),a=we(e.right,t,r,n);switch(e.op){case R.AND:return s&&a;case R.OR:return s||a}}let o=$(e.left,t,r,n),i=$(e.right,t,r,n);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 Q(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case R.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new Q(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Rn=(e,t,r,n)=>{let o=e.op===Be.NOT?we(e.operand,t,r,n):$(e.operand,t,r,n);if(e.op===Be.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Oi=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(Y(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?$(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)a[l]=u.value;else if(u.type===m.VARIABLE)a[l]=Y(u.path,r,n);else if(u.type===m.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===m.VARIABLE){let p=Y(d.path,r,n);f.push(p!=null?String(p):"")}else{let p=$(d,t,r,n);f.push(p!=null?String(p):"")}a[l]=f.join("")}else a[l]=$(u,t,r,n)}return a}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?$(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)a[l]=u.value;else if(u.type===m.VARIABLE)a[l]=Y(u.path,r,n);else if(u.type===m.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===m.VARIABLE){let p=Y(d.path,r,n);f.push(p!=null?String(p):"")}else{let p=$(d,t,r,n);f.push(p!=null?String(p):"")}a[l]=f.join("")}else a[l]=$(u,t,r,n)}return a}}}return null},$i=(e,t,r,n)=>{let o=Oi(e,t,r,n);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||we(s,t,r,n))return $(e.bodies[i],t,r,n)}return On},Li=(e,t)=>{let r=e.body,n=e.itemVar;if(r.type===m.CONDITIONAL&&r.conditions.length===1&&r.conditions[0].type===m.VARIABLE){let o=r.conditions[0].path,i=r.bodies[0];if(o.startsWith(n+".")){let s=o.substring(n.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let 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===m.LITERAL)u[d]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)u[d]=l;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);u[d]=l[g]}else return null}else if(p.type===m.INTERPOLATION){let h=[],g=!0;for(let y of p.parts)if(typeof y=="string")h.push(y);else if(y.type===m.VARIABLE){let b=y.path;if(b===n)h.push(l!=null?String(l):"");else if(b.startsWith(n+".")){let w=b.substring(n.length+1),E=l[w];h.push(E!=null?String(E):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[d]=h.join("")}else return null}a.push(u)}}return a}}}return null},ki=(e,t)=>{let r=e.body,n=e.itemVar,o=Li(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let a of r.properties)if(a.parsedKey)return null;let i=[],s=!0;for(let a of r.properties){let c=a.key,l=a.value;if(l.type===m.LITERAL)i.push({key:c,type:"literal",value:l.value});else if(l.type===m.VARIABLE){let u=l.path;if(u===n)i.push({key:c,type:"item"});else if(u.startsWith(n+".")){let f=u.substring(n.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===m.INTERPOLATION&&l.parts.length===1){let u=l.parts[0];if(u.type===m.VARIABLE){let f=u.path;if(f===n)i.push({key:c,type:"item_string"});else if(f.startsWith(n+".")){let d=f.substring(n.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},Pi=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.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={...n,[a]:u,...c&&{[c]:l}};d.__paths__||(d.__paths__=n.__paths__||{});let p=e.iterable.path||"";if(n&&n.__paths__&&p){let h=p.split("."),g=h[0];g in n.__paths__&&(p=n.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}d.__paths__={...d.__paths__,[a]:`${p}[${l}]`,...c&&{[c]:l}};for(let h of s.properties){let g=h.parsedKey?$(h.parsedKey,t,r,d):h.key,y=h.value;if(y.type===m.LITERAL)f[g]=y.value;else if(y.type===m.VARIABLE){let b=y.path;if(b===a)f[g]=u;else if(b===c)f[g]=l;else if(b.startsWith(a+".")){let w=b.substring(a.length+1);!w.includes(".")&&!w.includes("[")?f[g]=u[w]:f[g]=Y(b,r,{...n,[a]:u,...c&&{[c]:l}})}else f[g]=Y(b,r,{...n,[a]:u,...c&&{[c]:l}})}else if(y.type===m.INTERPOLATION){let b=[];for(let w of y.parts)if(typeof w=="string")b.push(w);else if(w.type===m.VARIABLE){let E=w.path,I;if(E===a)I=u;else if(E===c)I=l;else if(E.startsWith(a+".")){let N=E.substring(a.length+1);!N.includes(".")&&!N.includes("[")?I=u[N]:I=Y(E,r,{...n,[a]:u,...c&&{[c]:l}})}else I=Y(E,r,{...n,[a]:u,...c&&{[c]:l}});b.push(I!=null?String(I):"")}else{let E={...n,[a]:u,...c&&{[c]:l}},I=$(w,t,r,E);b.push(I!=null?String(I):"")}f[g]=b.join("")}else{let b={...n,[a]:u,...c&&{[c]:l}};f[g]=$(y,t,r,b)}}i.push(f)}return i}return null},Ti=(e,t,r)=>{let n=e.body;if(n.type===m.OBJECT&&n.properties.length===1&&n.properties[0].key==="$if item.visible"){let i=n.properties[0].value;if(i.type===m.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===m.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===m.OBJECT&&s.properties.length===2){let a=s.properties[0],c=s.properties[1];if(a.key==="id"&&a.value.type===m.VARIABLE&&a.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===m.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},Di=(e,t,r,n)=>{let o=$(e.iterable,t,r,n);if(!Array.isArray(o)){let l,u=!1;if(e.iterable.type===m.FUNCTION){u=!0;let d=e.iterable.args.map(p=>p.type===m.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===m.VARIABLE?p.path:p.type===m.FUNCTION?`${p.name}(...)`:"?").join(", ");l=`${e.iterable.name}(${d})`}else l=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw En(f,o,u)}if(!e.indexVar){let l=Ti(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=ki(e,o);if(l!==null)return l}let i=Pi(e,t,r,n,o);if(i!==null)return i;let s=[],a=e.iterable.path||"";if(n&&n.__paths__&&a){let l=a.split("."),u=l[0];u in n.__paths__&&(a=n.__paths__[u],l.length>1&&(a+="."+l.slice(1).join(".")))}let c=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(l=>l.type===m.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?{...n,[e.itemVar]:o[l],[e.indexVar]:l}:{...n,[e.itemVar]:o[l]};u.__paths__||(u.__paths__=n.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${a}[${l}]`},e.indexVar&&(u.__paths__[e.indexVar]=l);let f=$(e.body,t,r,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},Ni=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?$(o.parsedKey,t,r,n):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let a={},c={},l=!0;for(let u of s.properties){let f=u.parsedKey?$(u.parsedKey,t,r,n):u.key,d=u.value;if(d.type===m.LITERAL)c[f]=d.value;else if(d.type===m.VARIABLE)c[f]=Y(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=Y(h.path,r,n);p.push(g!=null?String(g):"")}else{l=!1;break}if(!l)break;c[f]=p.join("")}else if(d.type===m.OBJECT&&d.properties.length<=5){let p={};for(let h of d.properties){let g=h.key,y=h.value;if(y.type===m.LITERAL)p[g]=y.value;else if(y.type===m.VARIABLE)p[g]=Y(y.path,r,n);else if(y.type===m.INTERPOLATION){let b=[];for(let w of y.parts)if(typeof w=="string")b.push(w);else if(w.type===m.VARIABLE){let E=Y(w.path,r,n);b.push(E!=null?String(E):"")}else{l=!1;break}if(!l)break;p[g]=b.join("")}else{l=!1;break}}if(!l)break;c[f]=p}else{l=!1;break}}if(l)return a[i]=c,a}}return null},Vi=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!we(e.whenCondition,o,r,n))return;let i=Ni(e,t,r,n);if(i!==null)return i;if(e.fast){let l={};for(let u of e.properties){let f=u.parsedKey?$(u.parsedKey,t,r,n):u.key,d=u.value;if(d.type===m.LITERAL)l[f]=d.value;else if(d.type===m.VARIABLE)l[f]=Y(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=Y(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=$(h,t,r,n);p.push(g!=null?String(g):"")}l[f]=p.join("")}else l[f]=$(d,t,r,n)}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,r,n);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,r,n)}else{let u=l.value;if(u&&u.type===m.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=$(f.value,t,r,n);d!==void 0&&(s[l.key]=d)}else{let d=$(l.value,t,r,n);d!==void 0&&(s[l.key]=d)}}else{let f=l.parsedKey?$(l.parsedKey,t,r,n):l.key,d=$(l.value,t,r,n);d!==void 0&&(s[f]=d)}}return s},On={},ji=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=$(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=$(i,t,r,n);s!==On&&s!==void 0&&o.push(s)}return o},Mi=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,a=t.partials||{},c=t.functions||t;if(s&&!we(s,c,r,n))return;if(!a[o])throw new Q(`Partial '${o}' is not defined`);let l=n._partialStack||[];if(l.includes(o))throw new Q(`Circular partial reference detected: ${o}`);let u=a[o],f=r,d={...n,_partialStack:[...l,o]};if(n){f={...r};for(let p of Object.keys(n))p.startsWith("_")||(f[p]=n[p])}if(i){let p=$(i,t,r,n);f={...f,...p}}return $(u,t,f,d)},Fi=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],a=i.slice(1);if(!n||!(s in n))throw new Q(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(n.__paths__||(n.__paths__={}),!(s in n.__paths__))throw new Q(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=n.__paths__[s];if(typeof c=="number"){if(a.length>0)throw new Q(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return a.length>0&&(c+="."+a.join(".")),c};var or=Si;var Bi=/\$\{([^}]*)\}/g,Ui=/#\{([^}]*)\}/g,Ln=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=zi(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},zi=(e,t={})=>e.trim()?Wi(e).map(n=>qi(n.trim(),t)):[],Wi=e=>{let t=[],r="",n=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,r+=a):o&&a===i&&c!=="\\"?(o=!1,i="",r+=a):!o&&a==="("?(n++,r+=a):!o&&a===")"?(n--,r+=a):!o&&a===","&&n===0?(t.push(r),r=""):r+=a}return r&&t.push(r),t},qi=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:m.LITERAL,value:parseFloat(e)};if(e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};let r=Ln(e,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};let n=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:a,type:c}of o){let l=0;for(;l<n.length;){let u=ke(n.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 H(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},kn=/^\w+\(.*\)$/,Yi=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Ki=e=>{if(!(!e||e.trim()===""||kn.test(e))&&Yi.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}"`)},$n=e=>{let t=e.trim();if(kn.test(t))throw new v(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new v(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new v(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new v(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("?")&&t.includes(":"))throw new v(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:m.PATH_REFERENCE,path:t}},Ze=(e,t={})=>{let r=e.trim();Ki(r);let n=Ln(r,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};if(r.includes("[")&&!/[\s+\-*/%|&?:]/.test(r)){let o=0;for(let i of r)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:r}},ir=(e,t={})=>{let r=e,n=[];(e.includes("\\${")||e.includes("\\#{"))&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),r=r.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\(#\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(Bi)],i=[...r.matchAll(Ui)],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=r;for(let u=0;u<n.length;u++)l=l.replace(`__ESCAPED_${u}__`,n[u]);return{type:m.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:l,type:u}=s[0];try{return u==="variable"?Ze(l[1],t):$n(l[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};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 h=r.substring(c,p);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&a.push(h)}try{let h;u==="variable"?h=Ze(d.trim(),t):h=$n(d.trim()),a.push(h)}catch(h){if(h.message==="Invalid array index syntax")a.push(f);else throw h}c=p+f.length}if(c<r.length){let l=r.substring(c);for(let u=0;u<n.length;u++)l=l.replace(`__ESCAPED_${u}__`,n[u]);l&&a.push(l)}return{type:m.INTERPOLATION,parts:a}};var cr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Dn=e=>Object.keys(e),G=e=>e.join("."),ve=(e,t,r)=>{let n=Dn(e).filter(o=>!t.has(o));if(n.length>0)throw new v(`Unexpected key '${n[0]}' in condition JSON at '${G(r)}'`)},Ee=(e,t)=>typeof e=="string"?ir(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Ji(e,t):Gi(e,t):{type:m.LITERAL,value:e},Hi=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new v("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new v("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new v("Empty $each body not allowed");if(r.$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 ${n}`]:r}},Ji=(e,t)=>{let r=[],n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let c=Hi(i),l=Object.keys(c);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let u=Tn(l[0],c[l[0]],t,!0);r.push(u),n=!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=Tn(a[0],i[a[0]],t);r.push(c),n=!0;continue}}let s=Ee(i,t);r.push(s),(s.type===m.FUNCTION||s.type===m.CONDITIONAL||s.type===m.LOOP||s.type===m.PARTIAL||s.type===m.OBJECT&&!s.fast||s.type===m.ARRAY&&!s.fast)&&(n=!0)}return{type:m.ARRAY,items:r,fast:!n}},Gi=(e,t)=>{let r=[],n=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new 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[b]of i)for(let w of c)if(b===w||b.startsWith(w+" ")||b.startsWith(w+"#")){l.push(w);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={},h=!1;for(let[b,w]of Object.entries(d)){let E=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(E=b.slice(1)),p[E]=w,h=!0}let g=null;if(h&&(g=Ee(p,t),g.type===m.OBJECT)){let b=!1;for(let w of g.properties)if(w.value.type===m.VARIABLE||w.value.type===m.INTERPOLATION||w.value.type===m.FUNCTION||w.value.type===m.CONDITIONAL||w.value.type===m.OBJECT&&!w.value.fast||w.value.type===m.ARRAY&&!w.value.fast){b=!0;break}b&&(g.fast=!1)}let y={type:m.PARTIAL,name:u,data:g};return f!==void 0&&(y.whenCondition=Pn(f,t)),y}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'");o=Pn(l,t),n=!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=Xi(i,s,t);r.push({key:c,value:u.node}),n=!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=Ee(l,t);(u.type===m.FUNCTION||u.type===m.CONDITIONAL||u.type===m.PARTIAL||u.type===m.OBJECT&&!u.fast||u.type===m.ARRAY&&!u.fast)&&(n=!0);let f=ir(c,t),d={key:c,value:u};(f.type!==m.LITERAL||f.value!==c)&&(d.parsedKey=f),r.push(d),s++}}}let a={type:m.OBJECT,properties:r,fast:!n};return o&&(a.whenCondition=o),a},Xi=(e,t,r={})=>{let n=[],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());nr(l);let u=H(l,r);for(n.push(u),o.push(Ee(a,r)),i++;i<e.length;){let[f,d]=e[i],p=!1,h;if(c?f.startsWith(`$elif#${c} `)?(h=f.substring(`$elif#${c} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f===`$else#${c}`||f===`$else#${c}:`)&&(p=!0,h=null):f.startsWith("$elif ")?(h=f.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f==="$else"||f==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{nr(h);let g=H(h,r);n.push(g)}if(o.push(Ee(d,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:c},nextIndex:i}},sr={eq:R.EQ,neq:R.NEQ,gt:R.GT,gte:R.GTE,lt:R.LT,lte:R.LTE,in:R.IN,add:R.ADD,sub:R.SUBTRACT},ar={all:R.AND,any:R.OR},Qi=new Set(["var","literal","call","not",...Object.keys(sr),...Object.keys(ar)]),Zi=(e,t,r)=>{if(!Array.isArray(e))throw new v(`Condition JSON operator '${t}' at '${G(r)}' requires an array`);if(e.length!==2)throw new v(`Condition JSON operator '${t}' at '${G(r)}' requires exactly 2 operands`);return e},es=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new v(`Condition JSON operator '${t}' at '${G(o)}' requires an array`);if(e.length===0)throw new v(`Condition JSON operator '${t}' at '${G(o)}' requires at least 1 condition`);return e.map((s,a)=>me(s,n,[...o,a])).reduce((s,a)=>({type:m.BINARY,op:r,left:s,right:a}))},ts=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],ve(e,new Set(["call","args"]),r);else if(cr(e.call))n=e.call.name,o=e.call.args??[],ve(e,new Set(["call"]),r),ve(e.call,new Set(["name","args"]),[...r,"call"]);else throw new v(`Condition JSON call at '${G(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new v(`Condition JSON call at '${G(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new v(`Invalid condition JSON function name '${n}' at '${G(r)}'`);if(!Array.isArray(o))throw new v(`Condition JSON call '${n}' at '${G(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>me(i,t,[...r,"args",s]))}},me=(e,t={},r=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:m.LITERAL,value:e};if(Array.isArray(e))throw new v(`Condition JSON array at '${G(r)}' must be wrapped in an operator or { literal: [...] }`);if(!cr(e))throw new v(`Invalid condition JSON value at '${G(r)}'`);let n=Dn(e);if(n.length===0)throw new v(`Condition JSON object at '${G(r)}' must contain an operator`);let o=n.filter(s=>Qi.has(s));if(o.length===0)throw new v(`Unknown condition JSON operator '${n[0]}' at '${G(r)}'`);if(o.length>1)throw new v(`Condition JSON at '${G(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(ve(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new v(`Condition JSON var at '${G(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return ve(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return ts(e,t,r);if(i==="not")return ve(e,new Set(["not"]),r),{type:m.UNARY,op:Be.NOT,operand:me(e.not,t,[...r,"not"])};if(i in ar)return ve(e,new Set([i]),r),es(e[i],i,ar[i],t,[...r,i]);if(i in sr){ve(e,new Set([i]),r);let s=Zi(e[i],i,[...r,i]);return{type:m.BINARY,op:sr[i],left:me(s[0],t,[...r,i,0]),right:me(s[1],t,[...r,i,1])}}throw new v(`Unknown condition JSON operator '${i}' at '${G(r)}'`)},Pn=(e,t={})=>{if(e==null)throw new v("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new v("Empty condition expression after '$when'");return H(e,t)}return cr(e)||Array.isArray(e)?me(e,t):{type:m.LITERAL,value:e}},H=(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 H(l,t)}let r=ke(e,"||");if(r!==-1)return{type:m.BINARY,op:R.OR,left:H(e.substring(0,r).trim(),t),right:H(e.substring(r+2).trim(),t)};let n=ke(e,"&&");if(n!==-1)return{type:m.BINARY,op:R.AND,left:H(e.substring(0,n).trim(),t),right:H(e.substring(n+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=ke(e,l);if(f!==-1)return{type:m.BINARY,op:u,left:H(e.substring(0,f).trim(),t),right:H(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=ke(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:m.BINARY,op:s.type,left:H(e.substring(0,i).trim(),t),right:H(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let l of c)if(ke(e,l)!==-1)throw new v(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:m.UNARY,op:Be.NOT,operand:H(e.substring(1).trim(),t)}:Nn(e,t)},ke=(e,t)=>{let r=0,n=0;for(;n<=e.length-t.length;){if(e[n]==="(")r++;else if(e[n]===")")r--;else if(r===0&&e.substring(n,n+t.length)===t)return n;n++}return-1},rs=e=>{if(e=e.trim(),e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:m.LITERAL,value:""};if(e==="{}")return{type:m.LITERAL,value:{}};if(e==="[]")return{type:m.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:m.LITERAL,value:t}:{type:m.VARIABLE,path:e}},Nn=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return Ze(r,t);let o=rs(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return Ze(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},ns=(e,t=!1)=>{let r=t?"$each":"$for";try{vn(e)}catch(n){if(n instanceof v&&t){let o=n.message.replace(/\$for/g,"$each");throw new v(o.replace("Parse Error: ",""))}throw n}},Tn=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new v(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],a=i[2].trim();ns(a,n);let c=a.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let y=n?"$each":"$for";throw new v(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${a}')`)}let l=c[1].trim(),u=c[2].trim(),f,d=null;if(l.includes(",")){let y=l.split(",").map(b=>b.trim());if(y.length!==2)throw new v(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);f=y[0],d=y[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 h=Nn(u,r),g=Ee(t,r);return{type:m.LOOP,itemVar:f,indexVar:d,iterable:h,body:g,flatten:s!=="nested"}};var os=(e,t={})=>{let{functions:r={}}=t;return Ee(e,r)},wt=os;var et={};gi(et,{now:()=>is});var is=()=>Date.now();var ss=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...et,...n},s=wt(e,{functions:i}),a={};for(let[c,l]of Object.entries(o))a[c]=wt(l,{functions:i});return or(s,t,{functions:i,partials:a})},ee=ss;var as=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",cs=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,ls=(e,t)=>{if(as(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new v("Empty condition expression");return H(e,t)}return me(e,t)},us=(e,t={},r={})=>{let n=cs(r),o={...et,...n},i=ls(e,o);return!!we(i,{functions:o,partials:{}},t,{})},lr=us;var rt=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return lr(e,t)},Mn=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:a=c=>c}=r;for(let[c,l]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>l(s(n),...u):i[c]=(...u)=>{let f;return n=rr(n,p=>{let h=l(a(p),...u);f=h!==void 0&&!re(h)?h:void 0}),f});return{...o,...i}},xt=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return rr(n,i=>{o.forEach(s=>{t.forEach(a=>{a(i,s)})})})};var fs=(e,t)=>{if(e.default!==void 0)return e.default;let r=["number","boolean","string","object"];if(!r.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${r.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},ce=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),tt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Fn=e=>{let t=re(e)?Le(e):e;return structuredClone(t)},xe=e=>ce(e,"computed"),Ue=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!xe(t[r]))),ds=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),ur=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},ps=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=ds(e),[n,o,...i]=r;if(n==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return ur(s,i)}return n==="runtime"?ur(t.runtime,r.slice(1)):ur(t,r)},hs=(e,t,r)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(r!==void 0&&t.length!==r)throw new Error(`Computed expression operator "${e}" requires ${r} operand(s)`)},Vn=(e,t)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(t.length===0)throw new Error(`Computed expression operator "${e}" requires at least one operand`)},ms=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},ae=(e,t,r,n)=>(hs(e,t,n),t.map(o=>Et(o,r))),ie=(e,t,r,n)=>{let o=ae(e,t,r,n);return o.forEach(i=>ms(e,i)),o},gs=(e,t,r)=>{switch(e){case"var":return ps(t,r);case"add":{let[n,o]=ie(e,t,r,2);return n+o}case"sub":{let[n,o]=ie(e,t,r,2);return n-o}case"mul":{let[n,o]=ie(e,t,r,2);return n*o}case"div":{let[n,o]=ie(e,t,r,2);return n/o}case"mod":{let[n,o]=ie(e,t,r,2);return n%o}case"neg":{let[n]=ie(e,t,r,1);return-n}case"round":{let[n]=ie(e,t,r,1);return Math.round(n)}case"floor":{let[n]=ie(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=ie(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=ie(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=ie(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=ie(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=ae(e,t,r,2);return n==o}case"neq":{let[n,o]=ae(e,t,r,2);return n!=o}case"gt":{let[n,o]=ae(e,t,r,2);return n>o}case"gte":{let[n,o]=ae(e,t,r,2);return n>=o}case"lt":{let[n,o]=ae(e,t,r,2);return n<o}case"lte":{let[n,o]=ae(e,t,r,2);return n<=o}case"in":{let[n,o]=ae(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return Vn(e,t),t.every(n=>!!Et(n,r));case"or":case"any":return Vn(e,t),t.some(n=>!!Et(n,r));case"not":{let[n]=ae(e,t,r,1);return!n}case"length":{let[n]=ae(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:tt(n)?Object.keys(n).length:0}case"includes":{let[n,o]=ae(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return Fn(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},Et=(e,t={})=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let r=Object.entries(e);if(r.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[n,o]]=r;return gs(n,o,t)},ys=(e,t={})=>rt(e,{variables:t.variables,runtime:t.runtime}),bs=(e,t)=>{if(!tt(e))throw new Error(`${t} must be an object`);let r=ce(e,"expr"),n=ce(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},fr=(e,t,r)=>(bs(e,t),ce(e,"value")?Fn(e.value):Et(e.expr,r)),Is=(e,t={},r="unknown")=>{if(!tt(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=ce(e,"expr"),o=ce(e,"value");if(ce(e,"branches")){if(n||o)throw new Error(`Computed variable "${r}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${r}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${r}" branches must not be empty`);if(!tt(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let a=e.branches[s];if(!tt(a))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!ce(a,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(ys(a.when,t))return fr(a,`Computed variable "${r}" branch ${s}`,t)}return fr(e.default,`Computed variable "${r}" default`,t)}if(n===o)throw new Error(`Computed variable "${r}" must contain exactly one of expr, value, or branches`);return fr(e,`Computed variable "${r}"`,t)},As=(e,t,r)=>{switch(t){case"number":if(typeof r!="number"||!Number.isFinite(r))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(r)?"array":typeof r}`);return;case"boolean":if(typeof r!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(r)?"array":typeof r}`);return;case"string":if(typeof r!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(r)?"array":typeof r}`);return;case"object":if(r===null||typeof r!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof r}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},Ct=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=Ue(e,r),i=Object.entries(r).filter(([,f])=>xe(f)).map(([f])=>f),s={},a=[],c=f=>{if(ce(s,f))return s[f];let d=r[f];if(!xe(d))return o[f];let p=a.indexOf(f);if(p>=0){let h=[...a.slice(p),f].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}a.push(f);try{let h=Is(d.computed,u,f);return As(f,d.type,h),s[f]=h,h}finally{a.pop()}},l=new Proxy({},{get:(f,d)=>{if(typeof d=="string")return c(d)},has:(f,d)=>typeof d=="string"&&(ce(o,d)||i.includes(d)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(f,d)=>{if(!(typeof d!="string"||!ce(o,d)&&!i.includes(d)))return{enumerable:!0,configurable:!0}}}),u={variables:l,runtime:t,resolveVariable:c};return n?(i.forEach(f=>{c(f)}),{...o,...s}):l},ws=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>Ct({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),hr=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(xe(o))return;let i=fs(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},St=(e,t)=>{let r=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!r.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${r.join(", ")}`)},_t=(e,t,r)=>{let n={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=n[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${r}`);if(!Object.values(n).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${r}" of type "${e}". Valid operations: ${o.join(", ")}`)},vs=2,jn=12,Bn=(e=vs)=>{if(!Number.isInteger(e)||e<0||e>jn)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${jn}.`);return e},Es=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},vt=e=>typeof e=="number"&&Number.isFinite(e),mr=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!vt(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!vt(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!vt(r))throw new Error(`Operation "divide" requires value to be a number for variable "${n}".`);if(t==="divide"){if(r===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${n}".`);Bn(o.roundTo)}}},Rt=(e,t,r,n={})=>{let o=(s,a,c)=>{let l=s??a;if(!vt(l))throw new Error(`Operation "${t}" requires ${c} to be a number.`);return l},i=s=>{let a=o(s,void 0,"value");if(a===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return a};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return Es(o(e,0,"current value")/i(r),Bn(n.roundTo));case"increment":return o(e,0,"current value")+o(r,1,"value");case"decrement":return o(e,0,"current value")-o(r,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var Un=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let r=new Date(e),n=o=>String(o).padStart(2,"0");return t.replace("DD",n(r.getDate())).replace("MM",n(r.getMonth()+1)).replace("YYYY",r.getFullYear()).replace("YY",String(r.getFullYear()).slice(-2)).replace("HH",n(r.getHours())).replace("mm",n(r.getMinutes())).replace("ss",n(r.getSeconds()))},xs=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let a=i.character?.sprite;return a&&Object.keys(a).length>0&&(s.sprite=a),Object.keys(s).length>0?s:void 0},n=r(e),o=r(t);return JSON.stringify(n)===JSON.stringify(o)?null:n&&!o?{changeType:"delete",data:e}:o&&!n?{changeType:"add",data:t}:o&&n?{changeType:"update",data:t}:null},gr=(e={},t={})=>{let r={},n=["sfx","voice"],o=s=>{let a=e[s],c=t[s];c&&!a?r[s]={changeType:"add",data:c}:a&&!c?n.includes(s)||(r[s]={changeType:"delete",data:a}):a&&c&&JSON.stringify(a)!==JSON.stringify(c)&&(r[s]={changeType:"update",data:c})};o("background"),o("bgm"),o("voice");let i=xs(e.dialogue,t.dialogue);return i&&(r.dialogue=i),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),r},yr=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,!t.background.resourceId&&!t.background.colorId&&delete t.background);let r=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};r("layout"),r("choice"),r("form"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let n=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(a=>{let c={...a};return delete c.animations,i(c)?c:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return n("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),n("visual",o=>o.resourceId||o.transformId),t},Cs=(e,t)=>{if(!e||!t)return;let r=e;for(let n of t.split(".")){if(r==null||!(n in Object(r)))return;r=r[n]}return r},Ss=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let r=e.slice(7),n=Cs(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},_s={conditional:new Set(["branches"]),updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"]),form:new Set(["submitActions","cancelActions"]),submitForm:new Set(["actions"]),cancelForm:new Set(["actions"])},zn=(e,t)=>{let r=e[e.length-1];return r?_s[r]?.has(t)===!0:!1},dr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>dr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,zn(r,n)?o:dr(o,t,[...r,n])])):Ss(e,t),pr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>pr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,zn(r,n)?o:pr(o,t,[...r,n])])):typeof e=="string"?ee(e,t):e,br=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let r=dr(e,t._event);return pr(r,t)};var ge=e=>structuredClone(re(e)?Le(e):e),nt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:ge(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Yn=(e,t)=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let r=e.map(n=>ge(n)).filter(n=>t(n)||n.animations);return{hasValidItems:r.length>0,processedItems:r}},le=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wn=e=>e?.animations?.playback?.continuity==="persistent",Ot=(e,t)=>le(e??{},t)&&e[t]!==void 0,Rs=e=>{if(e){if(e.character&&le(e.character,"name"))return e.character.name;if(le(e,"characterName"))return e.characterName}},Kn=e=>!!e?.character&&le(e.character,"sprite"),Os=e=>{let t={},r=!1,n=Rs(e);return n!==void 0&&(t.name=n,r=!0),Kn(e)&&(t.sprite=ge(e.character.sprite),r=!0),r?t:void 0},qn=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},$s=({dialogueState:e,content:t,append:r=!1})=>{if(!r||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let n=Array.isArray(e.content)?e.content:[];n.length>0?e.initialRevealedContent=n.map(o=>ge(o)):delete e.initialRevealedContent,e.content=[...n,...t]},Ls=()=>({}),ks=(e,t)=>{if(t.background){let r=Ot(t.background,"resourceId"),n=Ot(t.background,"colorId"),{animationsOnly:o,state:i}=nt(t.background,c=>Ot(c,"resourceId")||Ot(c,"colorId"));if(o){e.background=e.background?{...ge(e.background),...i}:i;return}if(!r&&!n){delete e.background;return}let s=e.background,a=ge(t.background);if(!r&&s?.resourceId&&(a.resourceId=s.resourceId,!le(a,"transformId")&&s.transformId&&(a.transformId=s.transformId)),!n&&s?.colorId&&(a.colorId=s.colorId),le(a,"resourceId")&&a.resourceId===void 0&&delete a.resourceId,le(a,"colorId")&&a.colorId===void 0&&delete a.colorId,le(a,"animations")&&a.animations===void 0&&delete a.animations,!a.resourceId&&!a.colorId){delete e.background;return}s?.resourceId===a.resourceId&&s?.transformId===a.transformId&&!le(a,"animations")&&Wn(s)&&(a.animations=ge(s.animations)),e.background=a}else e.background?.animations&&!Wn(e.background)&&(e.background.animations={})},Ps=(e,t)=>{if(!t.dialogue){e.dialogue&&(qn(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let r=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:l,state:u}=nt(t.dialogue.ui,f=>!!f.resourceId);l?e.dialogue.ui={...e.dialogue.ui,...u}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let n=t.dialogue.append===!0&&r!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&$s({dialogueState:e.dialogue,content:t.dialogue.content,append:n});let o=le(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=le(t.dialogue,"characterId"),s=Os(t.dialogue),a=s!==void 0,c=Kn(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,a?e.dialogue.character=!i&&o&&e.dialogue.character?{...ge(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,c||qn(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let l={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(l.character=ge(e.dialogue.character)),e.dialogue.lines.push(l)}},Ts=(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},Ds=(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}}},Ns=(e,t)=>{if(t.visual){let{hasValidItems:r,processedItems:n}=Yn(t.visual.items,o=>!!o.resourceId);r?e.visual={items:n}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(r=>r.animations?{...r,animations:{}}:r))},Vs=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:r,processedItems:n}=Yn(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);r?e.character={items:n}:delete e.character},js=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Ms=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=nt(t.layout,o=>!!o.resourceId);if(r){e.layout=n;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},Fs=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=nt(t.choice,o=>!!o.resourceId);if(r){e.choice={...e.choice,...n};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},Bs=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=nt(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=ge(t.form)}else e.form&&delete e.form},Us=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},zs=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},Ws=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},Pe=e=>xt(Ls,[Ws,ks,Ts,Ds,Ns,Ps,Vs,js,Ms,Fs,Bs,Us,zs])(e);var qs=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"}}),Te=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),ot=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Hn=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",skipUnseenText:"boolean",skipTransitionsAndAnimations:"boolean",soundVolume:"number",musicVolume:"number",muteAll:"boolean",saveLoadPagination:"number",menuPage:"string",menuEntryPoint:"string",autoMode:"boolean",skipMode:"boolean",dialogueUIHidden:"boolean",isLineCompleted:"boolean"}),Ir=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Ar=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Ys=(e,t)=>{if(t.startsWith("global.")){let r=t.slice(7);return e?.global?.[r]}if(t.startsWith("context.runtime.")){let r=t.slice(16),n=Array.isArray(e?.contexts)?e.contexts:[];return n[n.length-1]?.runtime?.[r]}},ze=e=>Object.fromEntries(Object.entries(qs).map(([t,r])=>{let n=Ys(e,r.source),o=n!==void 0?n:Te[t]??ot[t];return[t,o]})),Ie=(e,t)=>ze(e)[t],Jn=(e={})=>Object.fromEntries(Ir.map(t=>[t,e[t]??Te[t]]));var Ce={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:Un},Ks=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,Hs=(e,t)=>{let r=String(t||"").trim();if(!r)return;let n=r.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of n){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},Lt=(e,t,r)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),a=Ks.exec(s);if(a){let[,c,l,u]=a,f=Hs(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((p,h)=>{let g={...t,[c]:p};l&&(g[l]=h),d.forEach(y=>{let b=Lt(y,g,r),w=ee(b,g,r);Array.isArray(w)?o.push(...w):o.push(w)})});continue}}o.push(Lt(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=Lt(i,t,r)}),n},Vr=({animationType:e,animationId:t,animationPath:r})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${r}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},Js=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);return Vr({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n&&(i.playback=structuredClone(n)),i},Gs=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Vr({animationType:e.type,animationId:t,animationPath:r}),e.type},Xs=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Qs=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Zs=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),ao=e=>e?.playback?.continuity==="persistent",Sr=e=>Array.isArray(e)?e.map(Sr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=Sr(e[r]),t),{}),kt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify(Sr(t))},co=(e=[])=>e.filter(t=>ao(t)).map(t=>structuredClone(t)),lo=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,r)=>{let n=typeof r?.duration=="number"&&Number.isFinite(r.duration)?r.duration:0;return t+n},0):0,wr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,lo(r)),0),uo=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(wr(e.tween),wr(e.prev?.tween),wr(e.next?.tween),lo(e.mask?.progress)),Gn=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let r=new Set(t.map(kt).filter(Boolean));return e.some(n=>{if(!ao(n))return!1;let o=kt(n);return o?r.has(o):!1})},ue=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||Gn({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:Gn({animationInstances:e,activePersistentAnimations:o}),ea=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),ta=(e,t)=>{if(ea(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},ra=({resources:e,animationId:t,playback:r,instanceId:n,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?Js({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},na=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Vr({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},jr=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(na(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},_r=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=ee(e,t);return r&&typeof r=="object"?e:r},Rr=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(r=>r===null||typeof r!="object"||Array.isArray(r)))throw new Error(`${t} must be an array of objects`);return e},oa=({content:e,path:t,variables:r})=>Rr(e,t).reduce((n,o)=>{let i=_r(o.text,{variables:r});return n+`${i??""}`.length},0),Xn=(e=[])=>{let t=new Map;for(let r of e)r?.id&&t.set(r.id,(t.get(r.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,r])=>r>1).map(([r])=>r))},$t=(e,t=0,r=new Set)=>{if(!r.has(e?.id))return`character-container-${e.id}`;let n=e?.sprites?.map(({resourceId:o})=>o)||[];return n.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${n.join("-")}`},vr=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return r},ia=(e,t={})=>{if(!t?.transformId)return;let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for background`);return r},sa=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},Or=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},aa=(e={})=>e.textStyles||{},ca=(e={})=>e.images||{},la=(e={})=>e.colors||{},ua=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,it=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,qe=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},Qn=(e,t,r)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);return e},Mr=(e,t)=>{if(typeof e!="string"||!ua.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(r=>r.repeat(2)).join("")}`:e},Zn=(e,t,r)=>{let n=Mr(e,r);if(t===1)return n;let o=Number.parseInt(n.slice(1,3),16),i=Number.parseInt(n.slice(3,5),16),s=Number.parseInt(n.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},fa=(e={},t)=>{let r=aa(e)?.[t];if(!r)throw new Error(`Text style "${t}" not found`);let n=e.fonts?.[r.fontId];if(!n)throw new Error(`Font "${r.fontId}" not found for text style "${t}"`);let o=e.colors?.[r.colorId];if(!o)throw new Error(`Color "${r.colorId}" not found for text style "${t}"`);let i=Qn(r.colorAlpha,"colorAlpha",t),s={fontFamily:n.fileId,fontSize:r.fontSize??16,fontWeight:r.fontWeight??"400",fontStyle:r.fontStyle??"normal",lineHeight:r.lineHeight??1.2,fill:Zn(o.hex,i,`Color "${r.colorId}" for text style "${t}"`)};if(r.align!==void 0&&(s.align=r.align),r.wordWrap!==void 0&&(s.wordWrap=r.wordWrap),r.breakWords!==void 0&&(s.breakWords=r.breakWords),r.wordWrapWidth!==void 0&&(s.wordWrapWidth=r.wordWrapWidth),r.strokeColorId){let a=e.colors?.[r.strokeColorId];if(!a)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let c=Qn(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=Zn(a.hex,c,`Stroke color "${r.strokeColorId}" for text style "${t}"`)}else if(r.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return r.strokeWidth!==void 0&&(s.strokeWidth=r.strokeWidth),s},$r=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>$r(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${r}". Use textStyleId instead`);let n={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(n[o]=$r(i,t,it(r,o)));return e.textStyleId!==void 0&&(qe(e.textStyleId,r,"textStyleId"),n.textStyle=fa(t,e.textStyleId)),n},Fr=(e={},t)=>{let r=la(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return Mr(r.hex,`Color "${t}"`)},fo=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Er=(e,t,r)=>{let n=e?.[t];if(!(!n||typeof n!="object"||Array.isArray(n))&&Object.prototype.hasOwnProperty.call(n,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${r}". Use ${fo(`${t}.fill`)} instead`)},da=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>st(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;let n={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(n[o]=st(i,t,it(r,o)));return e.colorId!==void 0&&(qe(e.colorId,r,"colorId"),n.fill=Fr(t,e.colorId)),n},st=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>st(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${r}". Use ${fo("fill")} instead`);Er(e,"hover",r),Er(e,"click",r),Er(e,"rightClick",r)}let n={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){n[o]=da(i,t,it(r,o));continue}n[o]=st(i,t,it(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(qe(e.colorId,r,"colorId"),n.fill=Fr(t,e.colorId)),n},xr=(e={},t)=>{let r=ca(e)?.[t];return r||null},po=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",eo=(e,t,r,n)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,n))throw new Error(`Inline ${t}.${n} is not allowed in sprite layout elements at "${r}". Use ${po(`${t}.${n}`)} instead`)},to=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},Lr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Lr(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${r}". Use ${po(o)} instead`);eo(e,"hover",r,"src"),eo(e,"click",r,"src")}let n={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(n[o]=Lr(i,t,it(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){qe(e.imageId,r,"imageId");let o=xr(t,e.imageId),i=o?.fileId??e.imageId;n.src=i,n.width===void 0&&o?.width!==void 0&&(n.width=o.width),n.height===void 0&&o?.height!==void 0&&(n.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(qe(e.hoverImageId,r,"hoverImageId"),to(n,"hover",xr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(qe(e.clickImageId,r,"clickImageId"),to(n,"click",xr(t,e.clickImageId)?.fileId??e.clickImageId)),n},Br=(e,t={},r="root")=>Lr(st($r(e,t,r),t,r),t,r),Se=Br,Ye=(e=[])=>e.find(t=>t.id==="story"),pa="#000000",kr="bg-cg-background-color",ha=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?Mr(r?.backgroundColor??pa,"screen.backgroundColor"):Fr(e,t.colorId),ma=({resources:e,background:t,screen:r={width:1920,height:1080}})=>({id:kr,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:ha({resources:e,background:t,screen:r})}),ga=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.layouts?.[t]):!1,ro=({resources:e={},resourceId:t,colorId:r})=>{let n=sa(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:Or({resourceId:t,kind:n})}:r!==void 0?{resourceId:kr,targetId:kr}:{resourceId:void 0,targetId:void 0}},ho=100,Tt=ho,mo=(e,t)=>e*t/ho,ya=(e={},t=Tt)=>e?.muteAll?0:mo(t,e?.soundVolume??Te.soundVolume),ba=(e={},t=Tt)=>e?.muteAll?0:mo(t,e?.musicVolume??Te.musicVolume),Ia=({item:e,index:t}={})=>`sfx:${t}:${e?.resourceId}`,fe=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,confirmDialog:f,form:d,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:b}={})=>{let w={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??a??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},E=xa({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e}),I={variables:e,runtime:w,saveSlots:r,isChoiceVisible:c,isFormVisible:l,canRollback:u,confirmDialog:f,form:d,historyDialogue:p,characters:h};return E&&(I.dialogue=E,I.dialogueLines=E.lines),I},no=100,Pt=(e,t)=>{if(Array.isArray(e))return e.map(n=>Pt(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=Pt(r[n],t)}),r.type==="text-revealing"?t(r):r},Aa=e=>Pt(e,t=>({...t,revealEffect:"none"})),wa=e=>Pt(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,no):no;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),_e=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?Aa(e):r?wa(e):e,go=({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:{}}}}),Pr=e=>{if(Array.isArray(e))return e.map(Pr);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Pr(s);let r=t.click?.payload;if(!r||typeof r!="object"||Array.isArray(r))return t;let n=r.actions,o=n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"nextLine")?{...n.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...r,bypassChoice:!0,...o?{actions:{...n,nextLine:o}}:{}}}}},va=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),oo=(e,t)=>{let r=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},n=r.actions&&typeof r.actions=="object"?r.actions:{};return{...e||{},payload:{...r,actions:{...n,...t}}}},Tr=(e,t)=>{if(Array.isArray(e))return e.map(i=>Tr(i,t));if(!e||typeof e!="object")return e;let r={};for(let[i,s]of Object.entries(e))r[i]=Tr(s,t);if(r.type!=="input"||typeof r.field!="string")return r;let n=t?.fields?.[r.field];if(!n)return r;let o={updateFormField:{formId:t.id,formKey:t.key,field:n.id,value:"_event.value",_interactionSource:"form"}};return{...r,value:n.value,placeholder:r.placeholder===void 0?n.placeholder:r.placeholder,multiline:r.multiline===void 0?n.multiline:r.multiline,...r.maxLength===void 0&&n.maxLength!==void 0?{maxLength:n.maxLength}:{},change:oo(r.change,o),submit:oo(r.submit,t.submitActions)}},Dr=(e,t)=>{if(Array.isArray(e))return e.map(n=>Dr(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Dr(o,t);for(let n of va){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form",_formId:t.id,_formKey:t.key}})}return r},Nr=({characterId:e,character:t,characterName:r,characters:n={}}={})=>{let o=e?n?.[e]:void 0,i=t?.name!==void 0?t.name:r!==void 0?r:o?.name||"";return{...o||{},...t||{},name:i}},yo=(e=[],t={})=>e.map(r=>{let n=Nr({characterId:r.characterId,character:r.character,characterName:r.characterName,characters:t}),o=typeof r.text=="string"?r.text:Array.isArray(r.content)?r.content.map(i=>i?.text??"").join(""):"";return{...r,text:o,character:n,characterName:n.name}}),Ea=e=>!(!e||e.mode==="adv"&&e.content===void 0),xa=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n}={})=>{if(!t&&!Ea(e))return;let o=e.content===void 0?[{text:""}]:Rr(e.content,"dialogue.content"),i=e.content===void 0?0:oa({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),s=(e.lines||[]).map((c,l)=>{let u=Rr(c.content,`dialogue.lines[${l}].content`),f=Nr({characterId:c.characterId,character:c.character,characterName:c.characterName,characters:r});return{...c,content:u.map(d=>({...d,text:_r(d.text,{variables:n})})),character:f,characterName:f.name}}),a=Nr({characterId:e.characterId,character:e.character,characters:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:a,content:o.map(c=>({...c,text:_r(c.text,{variables:n})})),initialRevealedCharacters:i,lines:s}},bo=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=ee(e,r,{functions:Ce});return Se(_e(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},Cr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),io=({renderStateKeyboard:e,keyboard:t,phase:r})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([n,o])=>{let i=e[n]??{},s=r==="keydown"?o?.keydown:o?.keyup;if(r==="keydown"&&s&&typeof s=="object"){e[n]={...i,keydown:{payload:Cr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:Cr(o.keyup)});return}e[n]={...i,[r]:{payload:Cr(o)}}})},Ca=(e={},t={})=>{let r={};return io({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),io({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},Ae=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:a})=>{if(!e)return[];let c=[],l=({instanceId:b,targetId:w})=>{let E=ra({resources:t,animationId:p,playback:h,instanceId:b,targetId:w,animationPath:s});E&&c.push(E)},u=r!=null&&r!==!1,f=n!=null&&n!==!1,d=o&&i&&o===i;ta(e,s);let p=Xs(e),h=Qs(e),g=t?.animations?.[p],y=Gs(g,{animationId:p,animationPath:s});if(y==="update")return f&&i?l({instanceId:`${a}-animation-update`,targetId:i}):u&&o&&l({instanceId:`${a}-animation-update`,targetId:o}),c;if(y==="transition"){let b=`${a}-animation-transition`,w=h?.continuity==="persistent"?b:`${a}-animation-in`;if(u&&f&&d)return l({instanceId:b,targetId:i}),c;u&&l({instanceId:`${a}-animation-out`,targetId:o}),f&&l({instanceId:w,targetId:i})}return c},Sa=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),_a=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:a,variables:c,runtime:l,activePersistentAnimations:u,restoredPersistentAnimations:f,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,saveSlots:w=[]})=>{let{elements:E,animations:I}=e;if(t.background){let N=n===void 0?!0:Zs(n?.background??{},"animations"),L=E.find(K=>K.id==="story");if(!L)return e;let V=ia(o,t.background),M=r?.background?.resourceId,O=r?.background?.colorId,D=t.background.resourceId??(t.background.animations?M:void 0),F=t.background.colorId??(t.background.animations?O:void 0),k=ga(o,D),W={...t.background,colorId:F};if((F!==void 0||k)&&L.children.push(ma({resources:o,background:W,screen:i})),D){let{images:K={},videos:q={}}=o,j=K[D]||q[D];if(j){let pe=q[D]!==void 0,Z={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...V},Me={id:Or({resourceId:D,kind:pe?"video":"sprite"}),type:pe?"video":"sprite",x:Z.x,y:Z.y,src:j.fileId,width:j.width,height:j.height,alpha:1,anchorX:Z.anchorX,anchorY:Z.anchorY,rotation:Z.rotation,scaleX:Z.scaleX,scaleY:Z.scaleY};pe&&(Me.loop=t.background.loop??!1,Me.volume=j.volume??50),L.children.push(Me)}}if(D){let{layouts:K={}}=o,q=K[D];if(q){let j={id:Or({resourceId:D,kind:"container"}),type:"container",children:q.elements};V&&Object.assign(j,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...V});let pe=ee(j,fe({variables:c,runtime:l,saveSlots:w,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,characters:o.characters||{},skipTransitionsAndAnimations:a}),{functions:Ce});L.children.push(Se(_e(pe,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:a}),o))}}let x=ro({resources:o,resourceId:M,colorId:O}),S=ro({resources:o,resourceId:D,colorId:F}),B=Ae({animationsDef:t.background.animations,resources:o,previousResourceId:x.resourceId,currentResourceId:S.resourceId,previousTargetId:x.targetId,currentTargetId:S.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});ue({animationInstances:B,isLineCompleted:s,skipTransitionsAndAnimations:a,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:N})&&I.push(...B)}return e},Ra=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:a,animations:c}=e;if(t.character&&n){let l=a.find(h=>h.id==="story");if(!l)return e;let u=t.character.items||[],f=r?.character?.items||[],d=Xn(u),p=Xn(f);for(let h=0;h<u.length;h++){let g=u[h],{transformId:y,sprites:b}=g,w=f.find(F=>F.id===g.id),E=f.findIndex(F=>F.id===g.id),I=w?.sprites&&w.sprites.length>0,N=b&&b.length>0,L=E>=0?$t(w,E,p):void 0,V=Ae({animationsDef:g.animations,resources:n,previousResourceId:L,currentResourceId:N?$t(g,h,d):void 0,previousTargetId:L,currentTargetId:N?$t(g,h,d):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&I&&ue({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){c.push(...V);continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let M=$t(g,h,d),O=n.transforms[y];if(!O){console.warn("Transform not found:",y);continue}let D={type:"container",id:M,x:g.x??O.x,y:g.y??O.y,anchorX:O.anchorX,anchorY:O.anchorY,rotation:O.rotation,scaleX:O.scaleX,scaleY:O.scaleY,children:[]};for(let F of b){let k=n.images[F.resourceId];if(!k){console.warn(`Image resource not found: ${F.resourceId}`);continue}D.children.push({type:"sprite",id:`${M}-${F.id}`,src:k.fileId,width:k.width,height:k.height,x:0,y:0})}l.children.push(D),ue({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...V)}}return e},Oa=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:a,activePersistentAnimations:c,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,saveSlots:g=[]})=>{let{elements:y,animations:b}=e;if(t.visual&&n){let w=y.find(I=>I.id==="story");if(!w)return e;let E=t.visual.items;for(let I of E){if(I.resourceId){let{images:M={},videos:O={},spritesheets:D={}}=n,F=D[I.resourceId];if(F){let k=vr(n,I),W=I.animationName;if(W){let x=F.animations?.[W];if(!x)throw new Error(`Animation '${W}' not found in spritesheet resource '${I.resourceId}'`);let S={id:`visual-${I.id}`,type:"animated-sprite",x:I.x??k.x,y:I.y??k.y,width:I.width??F.width,height:I.height??F.height,alpha:I.alpha??1,anchorX:k.anchorX,anchorY:k.anchorY,rotation:k.rotation,scaleX:k.scaleX,scaleY:k.scaleY,spritesheetSrc:F.fileId,spritesheetData:F.jsonData,animation:{frames:x.frames,animationSpeed:I.animationSpeed??x.animationSpeed??.5,loop:I.loop??x.loop??!0}};w.children.push(structuredClone(S))}}else{let k=M[I.resourceId]||O[I.resourceId];if(k){let W=O[I.resourceId]!==void 0,x=vr(n,I),S={id:`visual-${I.id}`,type:W?"video":"sprite",src:k.fileId,width:k.width,height:k.height,x:x.x,y:x.y,anchorX:x.anchorX,anchorY:x.anchorY,rotation:x.rotation,scaleX:x.scaleX,scaleY:x.scaleY};W&&(S.loop=k.loop??!1,S.volume=k.volume??50),w.children.push(S)}}}if(I.resourceId){let{layouts:M={}}=n,O=M[I.resourceId];if(O){let D=vr(n,I),F={id:`visual-${I.id}`,type:"container",children:structuredClone(O.elements),x:D.x,y:D.y,anchorX:D.anchorX,anchorY:D.anchorY,rotation:D.rotation,scaleX:D.scaleX,scaleY:D.scaleY},k=ee(F,fe({variables:s,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i}),{functions:Ce});w.children.push(Se(_e(k,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),n))}}let L=(r?.visual?.items||[]).find(M=>M.id===I.id),V=Ae({animationsDef:I.animations,resources:n,previousResourceId:L?.resourceId,currentResourceId:I.resourceId,previousTargetId:L?.resourceId?`visual-${I.id}`:void 0,currentTargetId:I.resourceId?`visual-${I.id}`:void 0,animationPath:`visual.items[${I.id}].animations`,idPrefix:I.id});ue({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:c})&&b.push(...V)}}return e},We="dialogue-character-sprite",so=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,$a=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:a}=e,c=Ye(e.elements);if(!c)return e;let l=t.dialogue?.character?.sprite,u=r?.dialogue?.character?.sprite,f=so(l),d=so(u),p=Ae({animationsDef:l?.animations,resources:n,previousResourceId:d?We:void 0,currentResourceId:f?We:void 0,previousTargetId:d?We:void 0,currentTargetId:f?We:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!f)return l?.animations&&d&&ue({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...p),e;let h=n.transforms?.[l.transformId];if(!h)return console.warn("Transform not found:",l.transformId),e;let g={type:"container",id:We,x:h.x,y:h.y,anchorX:h.anchorX,anchorY:h.anchorY,rotation:h.rotation,scaleX:h.scaleX,scaleY:h.scaleY,children:[]};for(let y of l.items){let b=n.images?.[y.resourceId];if(!b){console.warn(`Image resource not found: ${y.resourceId}`);continue}g.children.push({type:"sprite",id:`${We}-${y.id}`,src:b.fileId,width:b.width,height:b.height,x:0,y:0})}return c.children.push(g),ue({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...p),e},La=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:u,skipOnlyViewedLines:f,isLineCompleted:d,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:y,saveSlots:b=[]})=>{let{elements:w,animations:E}=e;if(!t.dialogue||o)return e;let I=w.find(L=>L.id==="story");if(!I)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:L={}}=n,V=L[t.dialogue.ui.resourceId];if(V){let M={elements:V.elements},O=fe({variables:h,runtime:g,saveSlots:b,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:d,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:u,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:f,skipTransitionsAndAnimations:p}),D={functions:Ce},F=Lt(M,O,D),k=ee(F,O,D),W=Se(_e(k?.elements,{isLineCompleted:d,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(W))for(let x of W)I.children.push(x);else W&&I.children.push(W)}}$a(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let N=Ae({animationsDef:t.dialogue.ui?.animations,resources:n,previousResourceId:r?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:r?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return ue({animationInstances:N,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&E.push(...N),e},ka=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,runtime:c,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:b,animations:w}=e;if(t.choice&&n){let E=Ye(b);if(!E)return e;let I=n?.layouts[t.choice.resourceId];if(I&&I.elements){let L={elements:I.elements},V=ee(L,{...fe({variables:a,runtime:c,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:u,isChoiceVisible:f??!!t.choice,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:Ce}),M=Pr(Se(_e(V?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n));if(Array.isArray(M))for(let O of M)E.children.push(O);else M&&E.children.push(M)}let N=Ae({animationsDef:t.choice.animations,resources:n,previousResourceId:r?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:r?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});ue({animationInstances:N,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&w.push(...N)}return e},Pa=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,runtime:c,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:b,animations:w}=e;if(!y?.resourceId||!n)return e;let E=Ye(b);if(!E)return e;let I=n?.layouts?.[y.resourceId];if(!I)return console.warn(`Form layout not found: ${y.resourceId}`),e;let N={id:"form-container",type:"container",x:0,y:0,children:I.elements||[]},L={...fe({variables:a,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},V=ee(N,L,{functions:Ce}),M=Dr(Se(_e(Tr(V,y),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n),y);M&&E.children.push(M);let O=Ae({animationsDef:y.animations,resources:n,previousResourceId:r?.form?.resourceId,currentResourceId:y.resourceId,previousTargetId:r?.form?.resourceId?"form-container":void 0,currentTargetId:y.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return ue({animationInstances:O,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&w.push(...O),e},Ta=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,saveSlots:d=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=Ca(h.keyboard,h.keyup);if(g&&Object.keys(g).length>0&&(e.global.keyboard=g),!Array.isArray(h.elements)||h.elements.length===0)return e;let y=Ye(e.elements);if(!y)return e;let b={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(bo({container:b,resources:r,templateData:fe({variables:n,runtime:o,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:a,skipTransitionsAndAnimations:p})),e},Da=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Ye(i))return e;let c=r.sounds[t.bgm.resourceId];if(!c)return e;let l=fe({variables:o,runtime:n}).runtime;s.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:ba(l,t.bgm.volume??c.volume??Tt),startDelayMs:t.bgm.startDelayMs??null})}return e},Na=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx.items;for(let[s,a]of i.entries()){let c=r.sounds?.[a.resourceId];c&&o.push({id:Ia({item:a,index:s}),type:"sound",src:c.fileId,loop:a.loop??c.loop??!1,volume:ya(n,a.volume??c.volume??Tt),startDelayMs:a.startDelayMs??c.startDelayMs??null})}}return e},Va=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},ja=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,Ma=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let a=t.voice,{resourceId:c,loop:l,startDelayMs:u}=a,f=Va(r,n,c);if(!f)return e;let d=fe({variables:i,runtime:o}).runtime;return s.push({id:`voice-${n}-${c}`,type:"sound",src:f.fileId,volume:ja(a,d),loop:l??!1,startDelayMs:u??null}),e},Fa=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,saveSlots:d=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:b}=e;if(t.layout){let N=Ye(y);if(!N)return e;let L=n.layouts[t.layout.resourceId];if(!L)return e;Array.isArray(L.transitions)&&!p&&!h&&jr({animations:b,transitions:L.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let V={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:L.elements||[]};N.children.push(bo({container:V,resources:n,templateData:fe({variables:o,runtime:i,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:a,skipTransitionsAndAnimations:h}))}let w=r?.layout?.resourceId,E=t.layout?.resourceId,I=Ae({animationsDef:t.layout?.animations,resources:n,previousResourceId:w,currentResourceId:E,previousTargetId:w?`layout-${w}`:void 0,currentTargetId:E?`layout-${E}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return ue({animationInstances:I,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(...I),e},Ba=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:a}=e,c=t?.screen?.animations;if(!c)return e;let l=r!=null,u=Ae({animationsDef:c,resources:n,previousResourceId:l?"story":void 0,currentResourceId:"story",previousTargetId:l?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return ue({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...u),e},Ua=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:u,overlayStack:f=[],dialogueHistory:d=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:w}=e;return f&&f.length>0&&f.forEach((E,I)=>{let N=r.layouts[E.resourceId];if(!N){console.warn(`Overlay layout not found: ${E.resourceId}`);return}Array.isArray(N.transitions)&&(y||jr({animations:w,transitions:N.transitions,defaultTargetId:`overlayStack-${I}`,idPrefix:`overlayStack-${I}`,animationPathPrefix:`overlayStack[${I}]`}));let L={id:`overlayStack-${I}`,type:"container",x:0,y:0,children:[go({id:`overlayStack-${I}-blocker`,screen:h}),...N.elements||[]]},V=yo(d,r.characters),M=fe({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:u,historyDialogue:V,characters:r.characters||{},skipTransitionsAndAnimations:y}),O=ee(L,M,{functions:Ce}),[D,...F]=O.children||[],k=Se(_e({...O,children:F},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...k,children:D?[D,...k.children||[]]:k.children})}),e},za=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,confirmDialog:d,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:w}=e;if(!d?.resourceId)return e;let E=r.layouts?.[d.resourceId];if(!E)return console.warn(`ConfirmDialog layout not found: ${d.resourceId}`),e;Array.isArray(E.transitions)&&!y&&jr({animations:w,transitions:E.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let I={id:"confirmDialog",type:"container",x:0,y:0,children:[go({id:"confirmDialog-blocker",screen:h}),...E.elements||[]]},N=yo(p,r.characters),L=ee(I,fe({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,confirmDialog:d,historyDialogue:N,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:Ce}),[V,...M]=L.children||[],O=Se(_e({...L,children:M},{isLineCompleted:g,skipMode:a,skipTransitionsAndAnimations:y}),r);return b.push({...O,children:V?[V,...O.children||[]]:O.children}),e},Io=e=>xt(Sa,[Ta,_a,Ra,Oa,La,ka,Pa,Fa,Ba,Da,Na,Ma,Ua,za])(e);var Dt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},xo=1,Ur="choice",Nt="form",Mt=()=>({manual:{...Dt.manual},auto:{...Dt.auto},applyMode:Dt.applyMode}),zr=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...Mt()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},T=e=>{let t=re(e)?Le(e):e;return structuredClone(t)},P=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ft=e=>String(e),Co=()=>({sections:[],resources:[]}),Wa=e=>P(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Co(),qa=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Ya=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:qa(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),Ka=()=>({resourceId:void 0}),Ha=e=>{if(!P(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},Wr=(e,t)=>{let r=e?.story?.scenes??{};for(let[n,o]of Object.entries(r))if(o?.sections?.[t])return{sceneId:n,section:o.sections[t]};return{sceneId:void 0,section:void 0}},So=e=>{let t=e?.story?.scenes??{},r=new Map;for(let[n,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let a=r.get(s);if(a!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${a}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},_o=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Ro=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==xo)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Ja=(e,t={})=>{let r;try{r=Ro(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:_o(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},Ga=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Ja(t,r)])),Oo=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Fl(r));return t.length>0?t:void 0},Xa=e=>{!P(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!P(t))return;let r=Oo(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},Ao=(e,t,r,n="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!P(e))throw new Error(`Malformed ${n}.${t}[${r}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${n}.${t}[${r}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${n}.sections[${r}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},Qa=(e,t="viewedRegistry")=>{if(e===void 0)return Co();if(!P(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let r=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Ao(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Ao(o,"resources",i,t);return[s.resourceId,s]})))}},$o=(e,t,r)=>{if(!P(e))throw new Error(`Malformed save slot ${r}.`);let{sectionId:n,lineId:o}=e;if(typeof n!="string"||n.length===0)throw new Error(`Malformed save slot ${r}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${r}: missing lineId.`);let{sceneId:i,section:s}=Wr(t,n);if(!s)throw new Error(`Malformed save slot ${r}: section "${n}" does not exist in projectData.`);if(!s.lines?.some(c=>c.id===o))throw new Error(`Malformed save slot ${r}: line "${o}" does not exist in section "${n}".`);return{sceneId:i,sectionId:n,lineId:o}},Za=(e,t,r)=>{if(!P(e)||!Array.isArray(e.timeline))return at({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((a,c)=>{if(!P(a))return[];try{let l=$o(a,r,`rollback.timeline[${c}]`),u=jt({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:a.rollbackPolicy}),f=Oo(T(a.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(n.length===0)return at({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):n.length-1;(o<0||o>=n.length)&&(o=n.length-1);let i=n[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let a=n.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);a>=0?o=a:(n.push(jt({sectionId:t.sectionId,lineId:t.lineId})),o=n.length-1)}let s=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),o):0;return{currentIndex:o,isRestoring:!1,replayStartIndex:s,timeline:n}},ec=(e,t,r)=>{if(!P(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=Kr(t),o=$o(e.pointers?.read,t,`contexts[${r}].pointers.read`);if(e.variables!==void 0&&!P(e.variables))throw new Error(`Malformed save slot contexts[${r}].variables entry.`);if(e.runtime!==void 0&&!P(e.runtime))throw new Error(`Malformed save slot contexts[${r}].runtime entry.`);let i=e.variables?Ue(T(e.variables),t.resources?.variables??{}):{},s=pc({loadedContextRuntime:P(e.runtime)?T(e.runtime):{}}),a={currentPointerMode:"read",pointers:{read:o},configuration:P(e.configuration)?T(e.configuration):{},views:Array.isArray(e.views)?T(e.views):[],bgm:P(e.bgm)?T(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:Za(e.rollback,o,t)};return s&&(a.runtime=s),a},tc=(e,t)=>{if(!P(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((r,n)=>ec(r,t,n))}},rc=(e,t)=>{if(!P(e))throw new Error("Malformed save slot.");let r=Ro(e.formatVersion);return{...e,formatVersion:r,state:tc(e.state,t)}},wo=(e,t,{required:r=!1}={})=>{if(e===void 0){if(r)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let n=T(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},nc=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:wo(e.confirmActions,"confirmActions",{required:!0}),cancelActions:wo(e.cancelActions,"cancelActions")}},He=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},oc=e=>(P(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),Je=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},Lo=e=>{if(!(!P(e)||!e.animations))return{animations:T(e.animations)}},ic=(e,t)=>{let r=Lo(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},sc=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},ac=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},Vt=e=>String(e??""),ko=(e,t)=>{let r=Vt(t);return e?.trim===!0?r.trim():r},cc=e=>P(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>P(t)).map(([t,r])=>[t,{id:t,...T(r)}])):{},lc=(e,t)=>{if(!t||!P(e.global.formDrafts))return;let r=e.global.formDrafts[t];return P(r)?r:void 0},Po=(e,t)=>{let r=oc(e);P(r[t])||(r[t]={values:{},touched:{},errors:{},submitted:!1});let n=r[t];return P(n.values)||(n.values={}),P(n.touched)||(n.touched={}),P(n.errors)||(n.errors={}),typeof n.submitted!="boolean"&&(n.submitted=!1),n},qr=(e,t)=>{let r=ko(e,t);return e?.required===!0&&r.length===0?"required":null},uc=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=X({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:Pe(n.slice(0,o+1).map(i=>i.actions||{}))},fc=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=sc(t),o=ac(r,n);if(!n||!o)return null;let i=lc(e,o),s=cc(t),a=Qr({state:e}),c={},l=[],u={},f=!0;return Object.entries(s).forEach(([d,p])=>{let h=Vt(a?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},d)?Vt(i.values[d]):h,y=i?.touched?.[d]===!0,b=qr(p,g),w=i?.submitted||y?b:null,E=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,I={id:d,variableId:p.variableId,value:g,initialValue:h,valid:!b,error:w,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...E!==void 0?{maxLength:E}:{}};b&&(f=!1),c[d]=I,l.push(I),u[d]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:f,submitted:i?.submitted===!0,fields:c,fieldList:l,values:u,submitActions:{submitForm:{formId:n,formKey:o,actions:T(t.submitActions??{})}},cancelActions:{cancelForm:{formId:n,formKey:o,actions:T(t.cancelActions??{})}}}},De=[],vo="line",Yr="interaction",jt=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),Kr=e=>{let{contextVariableDefaultValues:t}=hr(e??{});return T(t)},To=()=>({...T(ot)}),Do=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:T(r),hasLoadedValues:!1};if(!P(e))throw new Error(`Malformed ${n}.`);let o=T(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=No(s,T(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},dc=({loadedGlobalRuntime:e={}})=>Do({loadedRuntime:e,runtimeIds:Ir,defaults:Te,path:"global.runtime"}).runtimeState,pc=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=Do({loadedRuntime:e,runtimeIds:Ar,defaults:To(),path:"context.runtime"});return r?t:void 0},Hr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},hc=e=>e.runtime?(Ar.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=T(ot[t]))}),e.runtime):(e.runtime=To(),e.runtime),mc=e=>Jn(e.global),gc=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:mc(e)}})},yc=e=>Hn[e],bc=(e,t)=>{let r=yc(e);if(r==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(r==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(r==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},No=(e,t)=>(bc(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),Vo=(e,t,r)=>{let n=No(t,r);if(t in ot){let o=Hr(e);if(!o)return n;let i=hc(o);return i[t]=n,n}return e.global[t]=n,n},jo=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:T(e)},configuration:{},views:[],bgm:Ka(),variables:Kr(t),rollback:at({pointer:e})}),Ge=e=>e?(e.currentPointerMode="read",P(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Ic=(e,{queueRender:t=!0}={})=>{let r=e.contexts?.[e.contexts.length-1],n=r?.pointers?.read;if(!r||!n?.sectionId||!n?.lineId)return null;let o=jo({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,Ac(e,{queueRender:t}),o},Ac=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,He(e),Je(e),e.global.nextLineConfig=Mt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},Mo=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},at=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[jt({sectionId:e.sectionId,lineId:e.lineId})]:[]}},Ve=(e,t={})=>{if(e?.rollback)return Mo(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let r=e?.pointers?.read;return e.rollback=at({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},Jr=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=Ve(r);if(n.isRestoring)return;n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1));let o=n.timeline[n.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){n.currentIndex=n.timeline.length-1;return}n.timeline.push(jt(t)),n.currentIndex=n.timeline.length-1},wc=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;if(!r||r.isRestoring||!Array.isArray(r.timeline)||typeof r.currentIndex!="number")return null;let n=De[De.length-1],o=typeof n?.checkpointIndex=="number"?n.checkpointIndex:r.currentIndex;return o<0||o>=r.timeline.length?null:(typeof n?.checkpointIndex!="number"&&o<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,o+1)),r.timeline[o]??null)},vc=({state:e},t={})=>{let r=t?.source===vo?vo:Yr,o=e.contexts?.[e.contexts.length-1]?.rollback;return!o||o.isRestoring||!Array.isArray(o.timeline)||typeof o.currentIndex!="number"||o.currentIndex<0||o.currentIndex>=o.timeline.length?(De.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),De.push({checkpointIndex:o.currentIndex,source:r}),e)},Ec=({state:e})=>(De.pop(),e),ye=(e,t,r)=>{let o=De[De.length-1]?.source??Yr;if(!Bl(t,o))return;let i=wc(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:T(r)}))},Eo=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:a}of n){let c=e.projectData.resources?.variables?.[o],l=c?.scope,u=c?.type;if(xe(c))throw new Error(`Cannot update computed variable: ${o}`);if(c?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);St(l,o),_t(u,i,o),mr(u,i,s,o,{roundTo:a}),l==="context"&&(r.variables[o]=Rt(r.variables[o],i,s,{roundTo:a}))}},xc=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{Ul(e,r,n)})},Cc=(e,t)=>{let{sectionId:r,lineId:n}=t,s=X({state:e},{sectionId:r})?.lines?.find(a=>a.id===n)?.actions;s&&Object.entries(s).forEach(([a,c])=>{ri(e,a,c)})},Fo=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=Ve(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&<({state:e}),e.global.skipMode&&Ne({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=Kr(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=T(Dt),e.global.overlayStack=[],He(e),Je(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let a=i;a<=t;a++)a>i&&zr(e),Cc(e,n.timeline[a]),xc(e,n.timeline[a]);let s=Ge(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(a=>a?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},Sc=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;So(t);let a=t.story.initialSceneId,c=t.story.scenes[a],l=c.initialSectionId,u=c.sections[l],f={sceneId:a,sectionId:l,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:d}=hr(t),p={...d,...Ue(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:Qa(s,"accountViewedRegistry"),nextLineConfig:Mt(),saveSlots:Ga(n),overlayStack:[],variables:p,...dc({loadedGlobalRuntime:i})},contexts:[jo({pointer:f,projectData:t})]}},_c=({state:e})=>e.global.overlayStack||[],Rc=({state:e})=>e.global.pendingEffects,Bo=({state:e})=>e.global.skipMode,Oc=({state:e})=>e.global.autoMode,Uo=({state:e})=>e.global.dialogueUIHidden,zo=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(!r)return[];let{sectionId:n,lineId:o}=r.pointers.read,i=X({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),a=i.lines.slice(0,s+1),c=[],l={};for(let u of a){let f=u.actions||{};if(l=Pe([l,f]),!f.dialogue)continue;let d=l.dialogue||{},p="";d.character?.name!==void 0?p=d.character.name:d.characterId&&(p=e.projectData.resources?.characters?.[d.characterId]?.name||"");let h=Ya({sectionId:n,lineId:u.id,content:f.dialogue.append===!0?d.content:f.dialogue.content,dialogueState:d,characterName:p});if(f.dialogue.append===!0&&c.length>0){c[c.length-1]={...c[c.length-1],content:h.content,text:h.text,characterId:h.characterId,character:h.character,characterName:h.characterName};continue}c.push(h)}return c},$c=({state:e})=>e.global.confirmDialog??null,ct=({state:e},{pointer:t}={})=>{let r=t??de({state:e})?.pointer,n=uc({state:e,pointer:r});return fc({state:e,form:n.form,pointer:r})},Lc=({state:e},{pointer:t}={})=>!!ct({state:e},{pointer:t}),be=({state:e},{pointer:t}={})=>{let r=ct({state:e},{pointer:t});if(r)return{source:Nt,formId:r.id,formKey:r.key};let n=Wo({state:e,pointer:t});return n?{source:Ur,resourceId:n}:null},kc=({state:e,registry:t},r)=>{let{sectionId:n,lineId:o}=r,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===n);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let a=X({state:e},{sectionId:n});if(!a||!a.lines||!Array.isArray(a.lines))return s.lastLineId===o;let c=a.lines.findIndex(u=>u.id===s.lastLineId),l=a.lines.findIndex(u=>u.id===o);return c===-1||l===-1?s.lastLineId===o:l<=c},Pc=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},Gr=({state:e},t)=>kc({state:e,registry:e.global.accountViewedRegistry},t),Tc=({state:e},t)=>Pc({registry:e.global.accountViewedRegistry},t),Dc=({state:e})=>e.global.nextLineConfig,Wo=({state:e,pointer:t}={})=>{let r=t??de({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=X({state:e},{sectionId:n})?.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},qo=({state:e})=>!!Wo({state:e}),Nc=({state:e})=>structuredClone(e),Yo=({state:e})=>e.global.saveSlots,Vc=({state:e},t)=>{let r=t?.slotId,n=Ft(r);return e.global.saveSlots[n]},Xr=({state:e})=>ze(e),jc=({state:e},t)=>Ie(e,t?.runtimeId),Qr=({state:e})=>{let t={...e.global?.variables??{},...Hr(e)?.variables??{}};return Ct({variables:t,runtime:ze(e),variableConfigs:e.projectData.resources?.variables??{}})},de=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},X=({state:e},t)=>{let{sectionId:r}=t;return Wr(e.projectData,r).section},Zr=({state:e})=>{let t=de({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=X({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},Ko=({state:e})=>{let{sectionId:t,lineId:r}=de({state:e}).pointer,o=X({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===r),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 Pe(a)},Mc=({state:e})=>{let t=Ho({state:e}),n=Zr({state:e})?.actions??{},o=Pe([t??{},n]);return gr(t??{},o??{})},Fc=({state:e},{sectionId:t})=>{let r=X({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},a=Pe([o,s]),c=gr(o,a);n.push({id:i.id,changes:c,presentationState:a}),o=yr(a)}return n},Bc=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=Fc({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},Ho=({state:e})=>{let{sectionId:t,lineId:r}=de({state:e}).pointer,o=X({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===r);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 yr(Pe(a))},en=({state:e},{slotsPerPage:t=6}={})=>{let o=((Xr({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[Ft(a)]||{};i.push({...c,slotId:a})}return{saveSlots:i}},Uc=Yo,zc=en,Wc=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;return!r||!Array.isArray(r.timeline)||typeof r.currentIndex!="number"?!1:r.currentIndex>=0&&r.currentIndex<r.timeline.length-1},qc=({state:e},t={})=>{let r=Ko({state:e}),n=Ho({state:e}),o=Zr({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:T(i)}:o,a=i?.animations&&n===null?{}:n,{sectionId:c}=de({state:e}).pointer,{sceneId:l}=Wr(e.projectData,c),u=Xr({state:e}),f=t?.activePersistentAnimations??[],d=t?.restoredPersistentAnimations??[],p=ct({state:e}),h=qo({state:e}),g=Qr({state:e}),{saveSlots:y}=en({state:e}),b=Wc(e);return Io({presentationState:r,previousPresentationState:a,currentLineActions:s,resources:e.projectData.resources,currentSceneId:l,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:oi({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:zo({state:e}),saveSlots:y,variables:g,runtime:u,activePersistentAnimations:f,restoredPersistentAnimations:d})},Yc=({state:e},t)=>(e.global.confirmDialog=nc(t),e.global.pendingEffects.push({name:"render"}),e),Kc=({state:e})=>(e.global.confirmDialog&&(He(e),e.global.pendingEffects.push({name:"render"})),e),Hc=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),ye(e,"pushOverlay",t),e),Jc=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),ye(e,"popOverlay",void 0),e),Gc=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),ye(e,"replaceLastOverlay",t),e),Xc=({state:e})=>(e.global.overlayStack=[],He(e),Je(e),e.global.pendingEffects.push({name:"render"}),ye(e,"clearOverlays",void 0),e),Qc=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"})},Bt=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,ic(e,r),Je(e);let n=be({state:e},{pointer:t}),o=n?.source===Ur,i=n?.source===Nt;return n&&Qc(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},Jo=({state:e})=>(be({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:Ie(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),lt=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Zc=({state:e})=>{let t=e.global.autoMode;return be({state:e})&&!t||(t?lt({state:e}):Jo({state:e})),e},Go=({state:e})=>(be({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),Ne=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),el=({state:e})=>{let t=Bo({state:e});return be({state:e})&&!t||(t?Ne({state:e}):Go({state:e})),e},Ut=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),ye(e,"showDialogueUI",void 0),e),Xo=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),ye(e,"hideDialogueUI",void 0),e),tl=({state:e})=>(Uo({state:e})?Ut({state:e}):Xo({state:e}),e),je=(e,t,r)=>(Vo(e,t,r),gc(e),e.global.pendingEffects.push({name:"render"}),e),ut=(e,t,r,n)=>{let o=Vo(e,t,r);return e.global.pendingEffects.push({name:"render"}),ye(e,n,{value:o}),e},rl=({state:e},t)=>je(e,"dialogueTextSpeed",t?.value),nl=({state:e},t)=>je(e,"autoForwardDelay",t?.value),ol=({state:e},t)=>je(e,"skipUnseenText",t?.value),il=({state:e},t)=>je(e,"skipTransitionsAndAnimations",t?.value),sl=({state:e},t)=>je(e,"soundVolume",t?.value),al=({state:e},t)=>je(e,"musicVolume",t?.value),cl=({state:e},t)=>je(e,"muteAll",t?.value),ll=({state:e},t)=>ut(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),ul=({state:e})=>{let t=Ie(e,"saveLoadPagination")+1;return ut(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},fl=({state:e})=>{let t=Ie(e,"saveLoadPagination")-1;return ut(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},dl=({state:e},t)=>ut(e,"menuPage",t?.value,"setMenuPage"),pl=({state:e},t)=>ut(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),hl=({state:e})=>(e.global.pendingEffects=[],e),ml=({state:e},t)=>(e.global.pendingEffects.push(t),e),Qo=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!Lo(n),i=X({state:e},{sectionId:t});if(!i)return console.warn(`Section not found: ${t}`),e;let s=i.lines?.[0];if(!s)return console.warn(`Section ${t} has no lines`),e;if(r&&!Ic(e,{queueRender:!o}))return e;e.global.autoMode&<({state:e}),r&&e.global.skipMode&&Ne({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let c=Ge(a),l=c.read;r||Ke(e,{sectionId:l?.sectionId,lineId:l?.lineId}),a.rollback||Ve(a,{compatibilityAnchor:!0}),c.read={sectionId:t,lineId:s.id},r?a.rollback=at({pointer:c.read}):Jr(e,{sectionId:t,lineId:s.id})}return Bt(e,a?.pointers?.read,{screenTransition:n}),e},gl=({state:e},t)=>Qo(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),Zo=e=>(e.global.accountViewedRegistry=Wa(e.global.accountViewedRegistry),e.global.accountViewedRegistry),tn=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(r=>({scope:r.scope,path:r.path,op:r.op,value:T(r.value)}))}})},ei=(e,t)=>{tn(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(r=>({sectionId:r.sectionId,...r.lastLineId===void 0?{}:{lineId:r.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},yl=(e,t,{sectionId:r,lineId:n})=>{if(!r||!n)return!1;let o=P(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===r);if(i){if(i.lastLineId===void 0)return!1;let s=X({state:e},{sectionId:r});if(s?.lines){let a=s.lines.findIndex(l=>l.id===i.lastLineId),c=s.lines.findIndex(l=>l.id===n);if(a===-1||c>a)return i.lastLineId===n?!1:(i.lastLineId=n,!0)}else return i.lastLineId===n?!1:(i.lastLineId=n,!0);return!1}else return o.sections.push({sectionId:r,lastLineId:n}),!0},Ke=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;yl(e,Zo(e),t)&&ei(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},bl=({state:e},t)=>(Ke(e,t),e.global.pendingEffects.push({name:"render"}),e),Il=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=Zo(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),ei(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},ti=({state:e},t)=>{let r=Ha(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,a=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;r&&n?(e.global.nextLineConfig={manual:r,auto:n},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(r&&(e.global.nextLineConfig.manual=r),n&&(e.global.nextLineConfig.auto=n),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let c=e.global.nextLineConfig.auto?.enabled,l=be({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"}),ye(e,"setNextLineConfig",t),e},Al=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:n}=t,o=t?.savedAt,i=Ft(r),s=T(e.contexts);s?.forEach(l=>{Ge(l),Mo(l.rollback),Xa(l.rollback)});let a={contexts:s},c={formatVersion:xo,slotId:_o(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:a};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},wl=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=Ft(r),o=e.global.saveSlots[n];if(o){let i=rc(o,e.projectData);e.contexts=i.state.contexts,e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=Mt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,He(e),Je(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},vl=({state:e},t)=>{let{projectData:r}=t;So(r),e.projectData=r;let n=r?.resources?.variables??{};return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables=Ue(e.global.variables,n)),e.contexts?.forEach(o=>{Object.prototype.hasOwnProperty.call(o??{},"variables")&&(o.variables=Ue(o.variables,n))}),He(e),Je(e),e.global.pendingEffects.push({name:"render"}),e},El=({state:e},t)=>{let{sectionId:r,lineId:n}=t;if(!n)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=r||o.pointers.read?.sectionId;if(r&&!X({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=X({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(l=>l.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let c=Ge(o);return c.read={sectionId:i,lineId:n},Bt(e,c.read),e},xl=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return Ut({state:e}),e;let r=be({state:e});if(r?.source===Ur&&t?.bypassChoice!==!0||r?.source===Nt&&t?._interactionSource!==Nt)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=de({state:e})?.pointer,f=u?.sectionId,d=u?.lineId;f&&d&&Ke(e,{sectionId:f,lineId:d}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ie(e,"autoForwardDelay")}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=de({state:e})?.pointer,o=n?.sectionId,i=X({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],a=i?.lines||[],l=a.findIndex(u=>u.id===n?.lineId)+1;if(l<a.length){let u=a[l],f=!Ie(e,"skipUnseenText");if(e.global.skipMode&&f&&!Gr({state:e},{sectionId:o,lineId:u.id}))return Ne({state:e}),e;if(s&&!s.rollback&&Ve(s,{compatibilityAnchor:!0}),s){let h=Ge(s),g=h.read?.lineId;g&&o&&Ke(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:u.id}}Jr(e,{sectionId:o,lineId:u.id}),zr(e);let{activeInteraction:d}=Bt(e,{sectionId:o,lineId:u.id}),p=e.global.nextLineConfig;p?.auto?.enabled&&!d&&p.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}})}else e.global.autoMode&<({state:e}),e.global.skipMode&&Ne({state:e});return e},Cl=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=be({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ie(e,"autoForwardDelay")}});let r=de({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&Ke(e,{sectionId:n,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},Sl=({state:e},t)=>Qo(e,{sectionId:t?.sectionId,screen:t?.screen}),_l=({state:e})=>{if(e.global.dialogueUIHidden)return Ut({state:e}),e;if(be({state:e}))return e;let t=de({state:e})?.pointer,r=t?.sectionId,n=X({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],a=i.findIndex(c=>c.id===t?.lineId)+1;if(a<i.length){let c=i[a],l=!Ie(e,"skipUnseenText");if(e.global.skipMode&&l&&!Gr({state:e},{sectionId:r,lineId:c.id}))return Ne({state:e}),e;if(o&&!o.rollback&&Ve(o,{compatibilityAnchor:!0}),o){let f=Ge(o),d=f.read?.lineId;d&&r&&Ke(e,{sectionId:r,lineId:d}),f.read={sectionId:r,lineId:c.id}}Jr(e,{sectionId:r,lineId:c.id}),zr(e);let{activeInteraction:u}=Bt(e,{sectionId:r,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},rn=(e,t={})=>{let r=ct({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},Rl=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let r=e.projectData.resources?.variables?.[t.variableId],n=r?.scope,o=r?.type;if(xe(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return St(n,t.variableId),_t(o,"set",t.variableId),{variableConfig:r,scope:n}},Ol=(e,t)=>({id:e.id,key:e.key,valid:!0,values:T(t),fields:T(e.fields),fieldList:T(e.fieldList)}),$l=({state:e},t={})=>{let r=rn(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=Po(e,r.key),i=Vt(t.value),s=r.fields[n],a=qr(s,i);return o.values[n]=i,o.touched[n]=!0,a?o.errors[n]=a:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},Ll=({state:e},t={})=>{let r=rn(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=Po(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([f,d])=>{let p=Object.prototype.hasOwnProperty.call(n.values,f)?n.values[f]:d.value,h=qr(d,p);n.touched[f]=!0,h&&(i[f]=h),o[f]=ko(d,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:T(i),form:{id:r.id,key:r.key,values:T(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let a=!1,c=[],l=[];Object.entries(r.fields).forEach(([f,d])=>{let{scope:p}=Rl(e,d),h=p==="context"?s.variables:e.global.variables,g=o[f];h[d.variableId]=Rt(h[d.variableId],"set",g),p==="context"&&(a=!0,l.push({variableId:d.variableId,op:"set",value:g})),(p==="device"||p==="account")&&c.push({scope:p,path:`variables.${d.variableId}`,op:"set",value:T(h[d.variableId])})}),a&&ye(e,"updateVariable",{id:"submitForm",operations:l}),tn(e,c);let u=Ol(r,o);return delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},kl=({state:e},t={})=>{let r=rn(e,t);return r?(delete e.global.formDrafts?.[r.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:r.id,key:r.key,values:T(r.values),fields:T(r.fields),fieldList:T(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},Pl=({state:e},t)=>{let{id:r,operations:n=[]}=t;if(!r)throw new Error("updateVariable requires an id field");if(typeof r!="string"||!/^[a-zA-Z0-9]+$/.test(r))throw new Error(`updateVariable id must be alphanumeric, got: "${r}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],a=[];return n.forEach(({variableId:c,op:l,value:u,roundTo:f})=>{let d=e.projectData.resources?.variables?.[c],p=d?.scope,h=d?.type;if(xe(d))throw new Error(`Cannot update computed variable: ${c}`);if(d?.readonly===!0)throw new Error(`Cannot update readonly variable: ${c}`);St(p,c),_t(h,l,c),mr(h,l,u,c,{roundTo:f});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:c,op:l,value:u};f!==void 0&&(y.roundTo=f),a.push(y)}g[c]=Rt(g[c],l,u,{roundTo:f}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${c}`,op:"set",value:T(g[c])})}),i&&ye(e,"updateVariable",{id:r,operations:a}),tn(e,s),e.global.pendingEffects.push({name:"render"}),e},Tl=e=>(t,r)=>e({state:t},r),Dl=e=>({variables:Ct({variables:{...e.global?.variables??{},...Hr(e)?.variables??{}},runtime:ze(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:ze(e)}),Nl=e=>{if(!P(e))throw new Error("conditional action payload must be an object");if(!Array.isArray(e.branches))throw new Error("conditional action requires branches array");if(e.branches.length===0)throw new Error("conditional action requires at least one branch")},Vl=(e,t,r)=>{if(!P(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!P(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==r-1)throw new Error("conditional else branch must be the last branch")},jl=(e,t)=>{Nl(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(Vl(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!rt(n.when,Dl(e)))){Object.entries(n.actions).forEach(([i,s])=>{ri(e,i,s)});return}}},Ml={conditional:{replayLine:jl},updateVariable:{recordSources:[Yr],replayLine:Eo,replayRecorded:Eo,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Tl(ti)}},zt=e=>Ml[e]??null,Fl=e=>zt(e)?.persistInSaveSlot===!0,Bl=(e,t)=>{let r=zt(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},Ul=(e,t,r)=>{zt(t)?.replayRecorded?.(e,r)},ri=(e,t,r)=>{zt(t)?.replayLine?.(e,r)},ni=({state:e},t)=>{let{offset:r}=t;if(r===void 0||typeof r!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let n=e.contexts[e.contexts.length-1];if(!n)return null;let o=n.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+r;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},oi=({state:e})=>ni({state:e},{offset:-1})!==null,zl=({state:e},t)=>{let{offset:r=-1}=t;if(r>=0)throw new Error("rollbackByOffset requires a negative offset");let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let o=Ve(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:Fo(e,i)},Wl=({state:e},t)=>{let{sectionId:r,lineId:n}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=Ve(o,{compatibilityAnchor:!o.rollback}),a=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===r&&c.lineId===n);if(a===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return a===i.currentIndex?e:Fo(e,a)},ii=e=>{let t=Sc(e);return Mn(t,{selectPendingEffects:Rc,selectSkipMode:Bo,selectAutoMode:Oc,selectIsChoiceVisible:qo,selectIsFormVisible:Lc,selectActiveInteraction:be,selectActiveForm:ct,selectDialogueUIHidden:Uo,selectDialogueHistory:zo,selectConfirmDialog:$c,selectIsLineAccountViewed:Gr,selectIsResourceAccountViewed:Tc,selectNextLineConfig:Dc,selectSystemState:Nc,selectSaveSlotMap:Yo,selectSaveSlots:Uc,selectSaveSlot:Vc,selectRuntime:Xr,selectRuntimeValue:jc,selectAllVariables:Qr,selectCurrentPointer:de,selectSection:X,selectCurrentLine:Zr,selectPresentationState:Ko,selectPresentationChanges:Mc,selectSectionLineChanges:Bc,selectSaveSlotPage:en,selectCurrentPageSlots:zc,selectRenderState:qc,selectOverlayStack:_c,selectLineIdByOffset:ni,selectCanRollback:oi,startAutoMode:Jo,stopAutoMode:lt,toggleAutoMode:Zc,startSkipMode:Go,stopSkipMode:Ne,toggleSkipMode:el,showDialogueUI:Ut,hideDialogueUI:Xo,toggleDialogueUI:tl,setDialogueTextSpeed:rl,setAutoForwardDelay:nl,setSkipUnseenText:ol,setSkipTransitionsAndAnimations:il,setSoundVolume:sl,setMusicVolume:al,setMuteAll:cl,setSaveLoadPagination:ll,incrementSaveLoadPagination:ul,decrementSaveLoadPagination:fl,setMenuPage:dl,setMenuEntryPoint:pl,showConfirmDialog:Yc,hideConfirmDialog:Kc,resetStoryAtSection:gl,clearPendingEffects:hl,appendPendingEffect:ml,beginRollbackActionBatch:vc,endRollbackActionBatch:Ec,addViewedLine:bl,addViewedResource:Il,setNextLineConfig:ti,saveSlot:Al,loadSlot:wl,updateProjectData:vl,sectionTransition:Sl,jumpToLine:El,nextLine:xl,markLineCompleted:Cl,rollbackToLine:Wl,rollbackByOffset:zl,pushOverlay:Hc,popOverlay:Jc,replaceLastOverlay:Gc,clearOverlays:Xc,updateFormField:$l,submitForm:Ll,cancelForm:kl,updateVariable:Pl,nextLineFromSystem:_l},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var ql="route-engine",Yl="projectPersistence";var ai=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),J=e=>Object.prototype.toString.call(e)==="[object Object]",si="variables.",Kl=(e={})=>{let t=J(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!J(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lineId=="string"?{lineId:r.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!J(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Hl=(e={})=>{let t=J(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!J(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lastLineId=="string"?{lastLineId:r.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!J(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Jl=(e,t)=>{let r=Hl(e),n=Kl(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let a=o.find(c=>c.sectionId===s.sectionId);if(!a){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(a.lastLineId!==void 0){if(s.lineId===void 0){delete a.lastLineId;return}a.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(c=>c.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},ci=(e={})=>{let t=J(e)?e:{};return{saveSlots:J(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:J(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:J(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:J(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:J(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Gl=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!J(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(si)?t.path.slice(si.length):null;if(n!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(n.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${r}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:n}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${r}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${r}].`)})},Xl=(e,t)=>{let r={};return Gl(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=Jl(r.accountViewedRegistry??e.accountViewedRegistry,n.value);return}let o=n.scope==="device"?"globalDeviceVariables":"globalAccountVariables";r[o]={...e[o],...r[o],[n.variableId]:n.value}}),r},nn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},Ql=e=>{let t=nn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Zl=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},eu=({indexedDB:e,databaseName:t,objectStoreName:r})=>new Promise((n,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(r)||s.createObjectStore(r,{keyPath:"namespace"})},i.onsuccess=()=>{n(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),tu=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let c=n.transaction(t,"readonly").objectStore(t).get(r);c.onsuccess=()=>{o(c.result??null)},c.onerror=()=>{i(c.error??new Error(`Failed to read persisted namespace "${r}" from IndexedDB.`))}})},ft=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let a=o.transaction(t,"readwrite"),c=a.objectStore(t),l=c.get(r),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 "${r}" before updating IndexedDB.`))},l.onsuccess=()=>{let p=ci(l.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...ai(),...p,...h},y=c.put(g);y.onerror=()=>{f(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},a.oncomplete=()=>{d()},a.onerror=()=>{f(a.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},a.onabort=()=>{f(a.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},ru=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let s=n.transaction(t,"readwrite"),c=s.objectStore(t).delete(r),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 "${r}" from IndexedDB.`))},s.oncomplete=()=>{f()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},on=(e={})=>{let{indexedDB:t,databaseName:r=ql,objectStoreName:n=Yl,namespace:o}=e,i=Zl(t),s=Ql(o),a=eu({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let c=await tu({databasePromise:a,objectStoreName:n,namespace:s});return{...ai(),...ci(c)}},clear:async()=>ru({databasePromise:a,objectStoreName:n,namespace:s}),saveSlots:async c=>ft({databasePromise:a,objectStoreName:n,namespace:s,patch:{saveSlots:J(c)?c:{}}}),saveGlobalDeviceVariables:async c=>ft({databasePromise:a,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:J(c)?c:{}}}),saveGlobalAccountVariables:async c=>ft({databasePromise:a,objectStoreName:n,namespace:s,patch:{globalAccountVariables:J(c)?c:{}}}),saveGlobalRuntime:async c=>ft({databasePromise:a,objectStoreName:n,namespace:s,patch:{globalRuntime:J(c)?c:{}}}),applyScopedDataUpdates:async c=>ft({databasePromise:a,objectStoreName:n,namespace:s,patch:l=>Xl(l,c)})}},nu=on;var ou=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),iu=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),li="conditional",sn="form",su=new Set(["submitForm","cancelForm"]),dt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function an(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:a}=e,c=(A=new Map,C=Date.now())=>new Map(Array.from(A.entries()).filter(([,_])=>C<_.expiresAt).map(([_,U])=>[_,{animation:structuredClone(U.animation),startedAt:U.startedAt,expiresAt:U.expiresAt}])),l=(A=new Map)=>Array.from(A.values()).map(C=>structuredClone(C.animation)),u=(A=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,C])=>A<C.expiresAt))},f=()=>{for(;t.selectPendingEffects().length>0;){let A=[...t.selectPendingEffects()];t.clearPendingEffects();try{a(A)}catch(C){throw t.clearPendingEffects(),A.forEach(_=>{t.appendPendingEffect(_)}),C}}},d=({initialState:A,namespace:C})=>{t=ii(A),r=0,n=nn(C),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),f()},p=()=>n,h=()=>t.selectPresentationState(),g=()=>t.selectPresentationChanges(),y=A=>t.selectSectionLineChanges(A),b=(A={})=>{r+=1;let C=Date.now();u(C);let _=i.size>0,U=c(o,C),z=_?c(i,C):new Map,he={...t.selectRenderState({activePersistentAnimations:l(U),restoredPersistentAnimations:l(z)}),id:`render-${r}`};return s.set(he.id,{builtAt:C,persistentAnimationSessions:new Map([...z.entries(),...U.entries()]),usedRestoredPersistentAnimationSessions:_}),he},w=(A={})=>b(A),E=(A={})=>b(A),I=A=>{let C=typeof A?.id=="string"&&A.id.length>0?A.id:null,_=C?s.get(C):null;C&&s.delete(C);let U=new Map;co(A?.animations).forEach(z=>{let oe=kt(z);if(!oe)return;let he=_?.persistentAnimationSessions?.get(oe)??o.get(oe),pt=Math.max(0,uo(z)),un=he?.startedAt??_?.builtAt??Date.now();U.set(oe,{animation:structuredClone(z),startedAt:un,expiresAt:un+pt})}),o=U,_?.usedRestoredPersistentAnimationSessions&&(i=new Map)},N=()=>t.selectSystemState(),L=()=>t.selectSaveSlotMap(),V=A=>t.selectSaveSlot(A),M=A=>t.selectSaveSlotPage(A),O=()=>t.selectSkipMode(),D=()=>t.selectAutoMode(),F=()=>t.selectRuntime(),k=()=>t.selectIsChoiceVisible(),W=()=>t.selectIsFormVisible(),x=()=>t.selectActiveInteraction(),S=(A,C,_={})=>A!=="nextLine"||!dt(C)?C:_.bypassChoice===!0?{...C,bypassChoice:!0}:_.interactionSource===sn?{...C,_interactionSource:sn}:C,B=(A,C)=>{if(!t[A])return;ou.has(A)&&(iu.has(A)?i=c(o):i=new Map,o=new Map);let _=t[A](C);return f(),_},K=(A,C,_,U={})=>{if(A===li){let z=j(_),oe=br({[A]:C},z);Me(oe[A],_,U);return}B(A,C)},q=(A,C)=>{K(A,C)},j=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:C,..._}=A,U=t.selectAllVariables?t.selectAllVariables():void 0;return{..._,_event:C,variables:U,runtime:t.selectRuntime?t.selectRuntime():{}}},pe=A=>{if(!dt(A))throw new Error("conditional action payload must be an object");if(!Array.isArray(A.branches))throw new Error("conditional action requires branches array");if(A.branches.length===0)throw new Error("conditional action requires at least one branch")},Z=(A,C,_)=>{if(!dt(A))throw new Error(`conditional branch at index ${C} must be an object`);if(!dt(A.actions))throw new Error(`conditional branch at index ${C} requires actions object`);if(!Object.prototype.hasOwnProperty.call(A,"when")&&C!==_-1)throw new Error("conditional else branch must be the last branch")},Me=(A,C,_)=>{pe(A);for(let U=0;U<A.branches.length;U+=1){let z=A.branches[U];Z(z,U,A.branches.length);let oe=j(C);if(!(Object.prototype.hasOwnProperty.call(z,"when")&&!rt(z.when,oe))){qt(z.actions,C,_);return}}},di=(A,C)=>({...A??{},_form:C}),pi=(A,C,_,U)=>{let z=B(A,C),oe=z?.submitted===!0&&z.valid===!0,he=z?.cancelled===!0;!oe&&!he||dt(C.actions)&&qt(C.actions,di(_,z.form),{...U,interactionSource:sn})},hi=(A,C,_,U)=>{let z=j(_),he=br({[A]:C},z)[A];if(A===li){Me(he,_,U);return}let pt=S(A,he,U);if(su.has(A)){pi(A,pt,_,U);return}B(A,pt)},qt=(A,C,_)=>{Object.entries(A).forEach(([U,z])=>{hi(U,z,C,_)})},ln=(A,C,_={})=>{t.beginRollbackActionBatch({source:_.rollbackSource});try{qt(A,C,_)}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:K,handleInternalAction:q,handleActions:ln,selectRenderState:w,prepareRenderState:E,commitRenderState:I,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:N,selectSaveSlotMap:L,selectSaveSlot:V,selectSaveSlotPage:M,selectSaveSlots:L,selectRuntime:F,selectIsChoiceVisible:k,selectIsFormVisible:W,selectActiveInteraction:x,handleLineActions:()=>{let A=t.selectCurrentLine();return A?.actions?(ln(A.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var cn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},au=80,fi=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},cu=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&fi({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},lu=({engine:e,ticker:t,autoTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let a=n.delay??1e3;r.getElapsed()>=a&&(t.remove(i),r.setCallback(null),r.setElapsed(0),Wt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},uu=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},fu=({engine:e,ticker:t,skipTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let a=n?.delay??au;r.getElapsed()>=a&&(r.setElapsed(0),Wt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},du=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},pu=({engine:e,ticker:t,nextLineConfigTimerState:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let a=n.delay??1e3;r.getElapsed()>=a&&(r.setElapsed(0),Wt(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},hu=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},mu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},gu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},yu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},bu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},Iu=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},ui={render:fi,saveSlots:mu,saveGlobalDeviceVariables:gu,saveGlobalAccountVariables:yu,saveGlobalRuntime:bu,applyScopedDataUpdates:Iu,handleLineActions:cu,startAutoNextTimer:lu,clearAutoNextTimer:uu,startSkipNextTimer:fu,clearSkipNextTimer:du,nextLineConfigTimer:pu,clearNextLineConfigTimer:hu},Au=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Wt=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},wu=(e=[])=>{let t=new Set,r=[];for(let n=e.length-1;n>=0;n-=1){let o=e[n];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!Au.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},vu=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:a})=>{let c=cn(),l=cn(),u=cn(),f=s??null,d=Promise.resolve(),p=null,h=null,g=!1,y=0,b=x=>{if(o){o(x);return}console.error("RouteEngine persistence write failed.",x)},w=()=>{if(f)return f;let x=e();return f=on({indexedDB:i,namespace:a??x?.getNamespace?.()}),f},E=x=>{d=d.catch(()=>{}).then(()=>{let S=w();return x(S)}).catch(S=>{b(S)})},I=x=>{let S=typeof x?.id=="string"&&x.id.length>0?x.id:null;y+=1,p=S,g=!1},N=()=>y,L=(x={})=>{if(x?.aborted===!0)return!1;let S=typeof x?.id=="string"&&x.id.length>0?x.id:null;return S?S!==p||S===h?!1:(h=S,!0):p!==null||g?!1:(g=!0,!0)},V=(x,S={})=>{if(x!=="renderComplete"||!L(S))return!1;let B=e();return Wt(B,"markLineCompleted",{}),!0},M=x=>typeof x?.selectActiveInteraction=="function"?x.selectActiveInteraction():typeof x?.selectIsChoiceVisible=="function"&&x.selectIsChoiceVisible()?{source:"choice"}:null,O=(x,S)=>!(!x||typeof x!="object"||Array.isArray(x)||x._interactionSource!==S?.source||S.source==="form"&&x._formKey&&x._formKey!==S.formKey||S.source==="form"&&x.formKey&&x.formKey!==S.formKey),D=(x={},S)=>{if(O(x,S))return!0;let B=x?.actions;return!B||typeof B!="object"||Array.isArray(B)?!1:Object.values(B).some(K=>O(K,S))},F=(x,S={})=>{if(!S?.actions)return!1;let B=M(x);return!B||B.source==="choice"?!1:!D(S,B)},k=({preprocessPayload:x,onEvent:S}={})=>async(B,K={})=>{let q=e();if(F(q,K))return S?.(B,K);let j=await x?.(B,K)??K;if(F(q,j))return S?.(B,j);if(V(B,j),j?.actions){let pe=j?._event?{_event:j._event}:j?.event?{_event:j.event}:void 0,Z;j?.bypassChoice===!0?Z={bypassChoice:!0}:j?._interactionSource&&(Z={interactionSource:j._interactionSource}),Z?q.handleActions(j.actions,pe,Z):q.handleActions(j.actions,pe)}return S?.(B,j)},W=x=>{let S=e(),B=wu(x);B.forEach(q=>{if(!ui[q.name]&&!n)throw new Error(`Unhandled pending effect "${q.name}".`)});let K={engine:S,routeGraphics:t,ticker:r,autoTimer:c,skipTimer:l,nextLineConfigTimerState:u,trackRenderDispatch:I,getRenderDispatchCount:N,enqueuePersistenceWrite:E};for(let q of B){let j=ui[q.name];if(j){j(K,q.payload);continue}n(q,K)}};return W.handleRouteGraphicsEvent=V,W.createRouteGraphicsEventHandler=k,W},Eu=vu;var xu=(e,t={})=>{let{resources:r={}}=t;return Br(e,r)};var Uf=an;export{Eu as createEffectsHandler,nu as createIndexedDbPersistence,Uf as default,ws as resolveComputedVariables,xu as resolveLayoutReferences};
|
|
1
|
+
var bi=Object.defineProperty;var Ii=(e,t)=>{for(var r in t)bi(e,r,{get:t[r],enumerable:!0})};var gn=Symbol.for("immer-nothing"),fn=Symbol.for("immer-draftable"),te=Symbol.for("immer-state");function se(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Fe=Object.getPrototypeOf;function re(e){return!!e&&!!e[te]}function Oe(e){return e?yn(e)||Array.isArray(e)||!!e[fn]||!!e.constructor?.[fn]||bt(e)||It(e):!1}var Ai=Object.prototype.constructor.toString();function yn(e){if(!e||typeof e!="object")return!1;let t=Fe(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===Ai}function ht(e,t){yt(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function yt(e){let t=e[te];return t?t.type_:Array.isArray(e)?1:bt(e)?2:It(e)?3:0}function Ht(e,t){return yt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function bn(e,t,r){let n=yt(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function wi(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function bt(e){return e instanceof Map}function It(e){return e instanceof Set}function Re(e){return e.copy_||e.base_}function Jt(e,t){if(bt(e))return new Map(e);if(It(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=yn(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[te];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],a=n[s];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(n[s]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[s]})}return Object.create(Fe(e),n)}else{let n=Fe(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function er(e,t=!1){return At(e)||re(e)||!Oe(e)||(yt(e)>1&&(e.set=e.add=e.clear=e.delete=vi),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>er(n,!0))),e}function vi(){se(2)}function At(e){return Object.isFrozen(e)}var Ei={};function $e(e){let t=Ei[e];return t||se(0,e),t}var Xe;function In(){return Xe}function xi(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function dn(e,t){t&&($e("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Gt(e){Xt(e),e.drafts_.forEach(Ci),e.drafts_=null}function Xt(e){e===Xe&&(Xe=e.parent_)}function pn(e){return Xe=xi(Xe,e)}function Ci(e){let t=e[te];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function hn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[te].modified_&&(Gt(t),se(4)),Oe(e)&&(e=mt(t,e),t.parent_||gt(t,e)),t.patches_&&$e("Patches").generateReplacementPatches_(r[te].base_,e,t.patches_,t.inversePatches_)):e=mt(t,r,[]),Gt(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==gn?e:void 0}function mt(e,t,r){if(At(t))return t;let n=t[te];if(!n)return ht(t,(o,i)=>mn(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return gt(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let o=n.copy_,i=o,s=!1;n.type_===3&&(i=new Set(o),o.clear(),s=!0),ht(i,(a,c)=>mn(e,n,o,a,c,r,s)),gt(e,o,!1),r&&e.patches_&&$e("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function mn(e,t,r,n,o,i,s){if(re(o)){let a=i&&t&&t.type_!==3&&!Ht(t.assigned_,n)?i.concat(n):void 0,c=mt(e,o,a);if(bn(r,n,c),re(c))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(Oe(o)&&!At(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;mt(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&>(e,o)}}function gt(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&er(t,r)}function Si(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:In(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=tr;r&&(o=[n],i=Qe);let{revoke:s,proxy:a}=Proxy.revocable(o,i);return n.draft_=a,n.revoke_=s,a}var tr={get(e,t){if(t===te)return e;let r=Re(e);if(!Ht(r,t))return _i(e,r,t);let n=r[t];return e.finalized_||!Oe(n)?n:n===Yt(e.base_,t)?(Kt(e),e.copy_[t]=Zt(n,e)):n},has(e,t){return t in Re(e)},ownKeys(e){return Reflect.ownKeys(Re(e))},set(e,t,r){let n=An(Re(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=Yt(Re(e),t),i=o?.[te];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(wi(r,o)&&(r!==void 0||Ht(e.base_,t)))return!0;Kt(e),Qt(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return Yt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Kt(e),Qt(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Re(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){se(11)},getPrototypeOf(e){return Fe(e.base_)},setPrototypeOf(){se(12)}},Qe={};ht(tr,(e,t)=>{Qe[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Qe.deleteProperty=function(e,t){return Qe.set.call(this,e,t,void 0)};Qe.set=function(e,t,r){return tr.set.call(this,e[0],t,r,e[0])};function Yt(e,t){let r=e[te];return(r?Re(r):e)[t]}function _i(e,t,r){let n=An(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function An(e,t){if(!(t in e))return;let r=Fe(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=Fe(r)}}function Qt(e){e.modified_||(e.modified_=!0,e.parent_&&Qt(e.parent_))}function Kt(e){e.copy_||(e.copy_=Jt(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Ri=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,n)=>{if(typeof t=="function"&&typeof r!="function"){let i=r;r=t;let s=this;return function(c=i,...l){return s.produce(c,u=>r.call(this,u,...l))}}typeof r!="function"&&se(6),n!==void 0&&typeof n!="function"&&se(7);let o;if(Oe(t)){let i=pn(this),s=Zt(t,void 0),a=!0;try{o=r(s),a=!1}finally{a?Gt(i):Xt(i)}return dn(i,n),hn(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===gn&&(o=void 0),this.autoFreeze_&&er(o,!0),n){let i=[],s=[];$e("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else se(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...a)=>this.produceWithPatches(s,c=>t(c,...a));let n,o;return[this.produce(t,r,(s,a)=>{n=s,o=a}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Oe(e)||se(8),re(e)&&(e=Le(e));let t=pn(this),r=Zt(e,void 0);return r[te].isManual_=!0,Xt(t),r}finishDraft(e,t){let r=e&&e[te];(!r||!r.isManual_)&&se(9);let{scope_:n}=r;return dn(n,t),hn(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let o=t[r];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}r>-1&&(t=t.slice(r+1));let n=$e("Patches").applyPatches_;return re(e)?n(e,t):this.produce(e,o=>n(o,t))}};function Zt(e,t){let r=bt(e)?$e("MapSet").proxyMap_(e,t):It(e)?$e("MapSet").proxySet_(e,t):Si(e,t);return(t?t.scope_:In()).drafts_.push(r),r}function Le(e){return re(e)||se(10,e),wn(e)}function wn(e){if(!Oe(e)||At(e))return e;let t=e[te],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=Jt(e,t.scope_.immer_.useStrictShallowCopy_)}else r=Jt(e,!0);return ht(r,(n,o)=>{bn(r,n,wn(o))}),t&&(t.finalized_=!1),r}var ne=new Ri,rr=ne.produce,Lu=ne.produceWithPatches.bind(ne),ku=ne.setAutoFreeze.bind(ne),Pu=ne.setUseStrictShallowCopy.bind(ne),Tu=ne.applyPatches.bind(ne),Du=ne.createDraft.bind(ne),Nu=ne.finishDraft.bind(ne);var m={LITERAL:0,VARIABLE:1,INTERPOLATION:2,FUNCTION:3,BINARY:4,UNARY:5,CONDITIONAL:6,LOOP:7,OBJECT:8,ARRAY:9,PARTIAL:10,PATH_REFERENCE:11},R={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},Be={NOT:0};var v=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},Q=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var nr=e=>{if(!e||e.trim()==="")throw new v("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new v(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${r}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let r of t)if(e.trim().endsWith(r))throw new v(`Incomplete comparison expression - missing right operand (got: '${e}')`)},vn=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,r]=e.split(" in ");if(!r||r.trim()==="")throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);let n=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of n){if(!o)throw new 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 En=(e,t,r=!1)=>{if(t===null)return new Q(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new Q(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new Q(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new Q(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},xn=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new Q(`Unknown function '${e}' (${r})`)};var Oi=(e,t,r={})=>{let n={},o={};r&&typeof r=="object"&&(r.functions!==void 0||r.partials!==void 0?(n=r.functions||{},o=r.partials||{}):typeof r=="object"&&(n=r));let s=$(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},$=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return Y(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return Y(e.path,r,n);if(e.type===m.INTERPOLATION)return Li(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return Sn(e,t,r,n);case m.BINARY:return _n(e,t,r,n);case m.UNARY:return Rn(e,t,r,n);case m.CONDITIONAL:return Pi(e,t,r,n);case m.LOOP:return ji(e,t,r,n);case m.OBJECT:return Fi(e,t,r,n);case m.ARRAY:return Bi(e,t,r,n);case m.PARTIAL:return Ui(e,t,r,n);case m.PATH_REFERENCE:return zi(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Cn=new Map,$i=e=>{let t=[],r="",n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")r&&(t.push({type:"property",value:r}),r=""),n=!0;else if(i==="]"){if(n&&r){let s=r.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let a=s.slice(1,-1);t.push({type:"property",value:a})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},Y=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=Cn.get(e);if(!n){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),n=[];for(let c of i){let l=$i(c.trim());n.push(...l)}Cn.set(e,n)}let o=t;for(let i=0;i<n.length;i++){let s=n[i];if(s.type==="property"&&s.value in r){o=r[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},Li=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=$(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},Sn=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw xn(e.name,o);let s=e.args.map(a=>$(a,t,r,n));return i(...s)},we=(e,t,r,n)=>{if(e.var&&!e.type)return Y(e.var,r,n);switch(e.type){case m.VARIABLE:return Y(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return _n(e,t,r,n);case m.UNARY:return Rn(e,t,r,n);case m.FUNCTION:return Sn(e,t,r,n);default:return $(e,t,r,n)}},_n=(e,t,r,n)=>{if(e.op===R.AND||e.op===R.OR){let s=we(e.left,t,r,n),a=we(e.right,t,r,n);switch(e.op){case R.AND:return s&&a;case R.OR:return s||a}}let o=$(e.left,t,r,n),i=$(e.right,t,r,n);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 Q(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case R.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new Q(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Rn=(e,t,r,n)=>{let o=e.op===Be.NOT?we(e.operand,t,r,n):$(e.operand,t,r,n);if(e.op===Be.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},ki=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(Y(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?$(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)a[l]=u.value;else if(u.type===m.VARIABLE)a[l]=Y(u.path,r,n);else if(u.type===m.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===m.VARIABLE){let p=Y(d.path,r,n);f.push(p!=null?String(p):"")}else{let p=$(d,t,r,n);f.push(p!=null?String(p):"")}a[l]=f.join("")}else a[l]=$(u,t,r,n)}return a}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?$(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)a[l]=u.value;else if(u.type===m.VARIABLE)a[l]=Y(u.path,r,n);else if(u.type===m.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===m.VARIABLE){let p=Y(d.path,r,n);f.push(p!=null?String(p):"")}else{let p=$(d,t,r,n);f.push(p!=null?String(p):"")}a[l]=f.join("")}else a[l]=$(u,t,r,n)}return a}}}return null},Pi=(e,t,r,n)=>{let o=ki(e,t,r,n);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||we(s,t,r,n))return $(e.bodies[i],t,r,n)}return On},Ti=(e,t)=>{let r=e.body,n=e.itemVar;if(r.type===m.CONDITIONAL&&r.conditions.length===1&&r.conditions[0].type===m.VARIABLE){let o=r.conditions[0].path,i=r.bodies[0];if(o.startsWith(n+".")){let s=o.substring(n.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let 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===m.LITERAL)u[d]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)u[d]=l;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);u[d]=l[g]}else return null}else if(p.type===m.INTERPOLATION){let h=[],g=!0;for(let y of p.parts)if(typeof y=="string")h.push(y);else if(y.type===m.VARIABLE){let b=y.path;if(b===n)h.push(l!=null?String(l):"");else if(b.startsWith(n+".")){let w=b.substring(n.length+1),E=l[w];h.push(E!=null?String(E):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[d]=h.join("")}else return null}a.push(u)}}return a}}}return null},Di=(e,t)=>{let r=e.body,n=e.itemVar,o=Ti(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let a of r.properties)if(a.parsedKey)return null;let i=[],s=!0;for(let a of r.properties){let c=a.key,l=a.value;if(l.type===m.LITERAL)i.push({key:c,type:"literal",value:l.value});else if(l.type===m.VARIABLE){let u=l.path;if(u===n)i.push({key:c,type:"item"});else if(u.startsWith(n+".")){let f=u.substring(n.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===m.INTERPOLATION&&l.parts.length===1){let u=l.parts[0];if(u.type===m.VARIABLE){let f=u.path;if(f===n)i.push({key:c,type:"item_string"});else if(f.startsWith(n+".")){let d=f.substring(n.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},Ni=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.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={...n,[a]:u,...c&&{[c]:l}};d.__paths__||(d.__paths__=n.__paths__||{});let p=e.iterable.path||"";if(n&&n.__paths__&&p){let h=p.split("."),g=h[0];g in n.__paths__&&(p=n.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}d.__paths__={...d.__paths__,[a]:`${p}[${l}]`,...c&&{[c]:l}};for(let h of s.properties){let g=h.parsedKey?$(h.parsedKey,t,r,d):h.key,y=h.value;if(y.type===m.LITERAL)f[g]=y.value;else if(y.type===m.VARIABLE){let b=y.path;if(b===a)f[g]=u;else if(b===c)f[g]=l;else if(b.startsWith(a+".")){let w=b.substring(a.length+1);!w.includes(".")&&!w.includes("[")?f[g]=u[w]:f[g]=Y(b,r,{...n,[a]:u,...c&&{[c]:l}})}else f[g]=Y(b,r,{...n,[a]:u,...c&&{[c]:l}})}else if(y.type===m.INTERPOLATION){let b=[];for(let w of y.parts)if(typeof w=="string")b.push(w);else if(w.type===m.VARIABLE){let E=w.path,I;if(E===a)I=u;else if(E===c)I=l;else if(E.startsWith(a+".")){let N=E.substring(a.length+1);!N.includes(".")&&!N.includes("[")?I=u[N]:I=Y(E,r,{...n,[a]:u,...c&&{[c]:l}})}else I=Y(E,r,{...n,[a]:u,...c&&{[c]:l}});b.push(I!=null?String(I):"")}else{let E={...n,[a]:u,...c&&{[c]:l}},I=$(w,t,r,E);b.push(I!=null?String(I):"")}f[g]=b.join("")}else{let b={...n,[a]:u,...c&&{[c]:l}};f[g]=$(y,t,r,b)}}i.push(f)}return i}return null},Vi=(e,t,r)=>{let n=e.body;if(n.type===m.OBJECT&&n.properties.length===1&&n.properties[0].key==="$if item.visible"){let i=n.properties[0].value;if(i.type===m.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===m.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===m.OBJECT&&s.properties.length===2){let a=s.properties[0],c=s.properties[1];if(a.key==="id"&&a.value.type===m.VARIABLE&&a.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===m.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},ji=(e,t,r,n)=>{let o=$(e.iterable,t,r,n);if(!Array.isArray(o)){let l,u=!1;if(e.iterable.type===m.FUNCTION){u=!0;let d=e.iterable.args.map(p=>p.type===m.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===m.VARIABLE?p.path:p.type===m.FUNCTION?`${p.name}(...)`:"?").join(", ");l=`${e.iterable.name}(${d})`}else l=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw En(f,o,u)}if(!e.indexVar){let l=Vi(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=Di(e,o);if(l!==null)return l}let i=Ni(e,t,r,n,o);if(i!==null)return i;let s=[],a=e.iterable.path||"";if(n&&n.__paths__&&a){let l=a.split("."),u=l[0];u in n.__paths__&&(a=n.__paths__[u],l.length>1&&(a+="."+l.slice(1).join(".")))}let c=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(l=>l.type===m.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?{...n,[e.itemVar]:o[l],[e.indexVar]:l}:{...n,[e.itemVar]:o[l]};u.__paths__||(u.__paths__=n.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${a}[${l}]`},e.indexVar&&(u.__paths__[e.indexVar]=l);let f=$(e.body,t,r,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},Mi=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?$(o.parsedKey,t,r,n):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let a={},c={},l=!0;for(let u of s.properties){let f=u.parsedKey?$(u.parsedKey,t,r,n):u.key,d=u.value;if(d.type===m.LITERAL)c[f]=d.value;else if(d.type===m.VARIABLE)c[f]=Y(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=Y(h.path,r,n);p.push(g!=null?String(g):"")}else{l=!1;break}if(!l)break;c[f]=p.join("")}else if(d.type===m.OBJECT&&d.properties.length<=5){let p={};for(let h of d.properties){let g=h.key,y=h.value;if(y.type===m.LITERAL)p[g]=y.value;else if(y.type===m.VARIABLE)p[g]=Y(y.path,r,n);else if(y.type===m.INTERPOLATION){let b=[];for(let w of y.parts)if(typeof w=="string")b.push(w);else if(w.type===m.VARIABLE){let E=Y(w.path,r,n);b.push(E!=null?String(E):"")}else{l=!1;break}if(!l)break;p[g]=b.join("")}else{l=!1;break}}if(!l)break;c[f]=p}else{l=!1;break}}if(l)return a[i]=c,a}}return null},Fi=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!we(e.whenCondition,o,r,n))return;let i=Mi(e,t,r,n);if(i!==null)return i;if(e.fast){let l={};for(let u of e.properties){let f=u.parsedKey?$(u.parsedKey,t,r,n):u.key,d=u.value;if(d.type===m.LITERAL)l[f]=d.value;else if(d.type===m.VARIABLE)l[f]=Y(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=Y(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=$(h,t,r,n);p.push(g!=null?String(g):"")}l[f]=p.join("")}else l[f]=$(d,t,r,n)}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,r,n);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,r,n)}else{let u=l.value;if(u&&u.type===m.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=$(f.value,t,r,n);d!==void 0&&(s[l.key]=d)}else{let d=$(l.value,t,r,n);d!==void 0&&(s[l.key]=d)}}else{let f=l.parsedKey?$(l.parsedKey,t,r,n):l.key,d=$(l.value,t,r,n);d!==void 0&&(s[f]=d)}}return s},On={},Bi=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=$(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=$(i,t,r,n);s!==On&&s!==void 0&&o.push(s)}return o},Ui=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,a=t.partials||{},c=t.functions||t;if(s&&!we(s,c,r,n))return;if(!a[o])throw new Q(`Partial '${o}' is not defined`);let l=n._partialStack||[];if(l.includes(o))throw new Q(`Circular partial reference detected: ${o}`);let u=a[o],f=r,d={...n,_partialStack:[...l,o]};if(n){f={...r};for(let p of Object.keys(n))p.startsWith("_")||(f[p]=n[p])}if(i){let p=$(i,t,r,n);f={...f,...p}}return $(u,t,f,d)},zi=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],a=i.slice(1);if(!n||!(s in n))throw new Q(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(n.__paths__||(n.__paths__={}),!(s in n.__paths__))throw new Q(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=n.__paths__[s];if(typeof c=="number"){if(a.length>0)throw new Q(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return a.length>0&&(c+="."+a.join(".")),c};var or=Oi;var Wi=/\$\{([^}]*)\}/g,qi=/#\{([^}]*)\}/g,Ln=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=Yi(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},Yi=(e,t={})=>e.trim()?Ki(e).map(n=>Hi(n.trim(),t)):[],Ki=e=>{let t=[],r="",n=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,r+=a):o&&a===i&&c!=="\\"?(o=!1,i="",r+=a):!o&&a==="("?(n++,r+=a):!o&&a===")"?(n--,r+=a):!o&&a===","&&n===0?(t.push(r),r=""):r+=a}return r&&t.push(r),t},Hi=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:m.LITERAL,value:parseFloat(e)};if(e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};let r=Ln(e,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};let n=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:a,type:c}of o){let l=0;for(;l<n.length;){let u=ke(n.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 H(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},kn=/^\w+\(.*\)$/,Ji=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Gi=e=>{if(!(!e||e.trim()===""||kn.test(e))&&Ji.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}"`)},$n=e=>{let t=e.trim();if(kn.test(t))throw new v(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new v(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new v(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new v(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("?")&&t.includes(":"))throw new v(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:m.PATH_REFERENCE,path:t}},Ze=(e,t={})=>{let r=e.trim();Gi(r);let n=Ln(r,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};if(r.includes("[")&&!/[\s+\-*/%|&?:]/.test(r)){let o=0;for(let i of r)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:r}},ir=(e,t={})=>{let r=e,n=[];(e.includes("\\${")||e.includes("\\#{"))&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),r=r.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\(#\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(Wi)],i=[...r.matchAll(qi)],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=r;for(let u=0;u<n.length;u++)l=l.replace(`__ESCAPED_${u}__`,n[u]);return{type:m.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:l,type:u}=s[0];try{return u==="variable"?Ze(l[1],t):$n(l[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};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 h=r.substring(c,p);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&a.push(h)}try{let h;u==="variable"?h=Ze(d.trim(),t):h=$n(d.trim()),a.push(h)}catch(h){if(h.message==="Invalid array index syntax")a.push(f);else throw h}c=p+f.length}if(c<r.length){let l=r.substring(c);for(let u=0;u<n.length;u++)l=l.replace(`__ESCAPED_${u}__`,n[u]);l&&a.push(l)}return{type:m.INTERPOLATION,parts:a}};var cr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Dn=e=>Object.keys(e),G=e=>e.join("."),ve=(e,t,r)=>{let n=Dn(e).filter(o=>!t.has(o));if(n.length>0)throw new v(`Unexpected key '${n[0]}' in condition JSON at '${G(r)}'`)},Ee=(e,t)=>typeof e=="string"?ir(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Qi(e,t):Zi(e,t):{type:m.LITERAL,value:e},Xi=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new v("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new v("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new v("Empty $each body not allowed");if(r.$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 ${n}`]:r}},Qi=(e,t)=>{let r=[],n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let c=Xi(i),l=Object.keys(c);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let u=Tn(l[0],c[l[0]],t,!0);r.push(u),n=!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=Tn(a[0],i[a[0]],t);r.push(c),n=!0;continue}}let s=Ee(i,t);r.push(s),(s.type===m.FUNCTION||s.type===m.CONDITIONAL||s.type===m.LOOP||s.type===m.PARTIAL||s.type===m.OBJECT&&!s.fast||s.type===m.ARRAY&&!s.fast)&&(n=!0)}return{type:m.ARRAY,items:r,fast:!n}},Zi=(e,t)=>{let r=[],n=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new 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[b]of i)for(let w of c)if(b===w||b.startsWith(w+" ")||b.startsWith(w+"#")){l.push(w);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={},h=!1;for(let[b,w]of Object.entries(d)){let E=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(E=b.slice(1)),p[E]=w,h=!0}let g=null;if(h&&(g=Ee(p,t),g.type===m.OBJECT)){let b=!1;for(let w of g.properties)if(w.value.type===m.VARIABLE||w.value.type===m.INTERPOLATION||w.value.type===m.FUNCTION||w.value.type===m.CONDITIONAL||w.value.type===m.OBJECT&&!w.value.fast||w.value.type===m.ARRAY&&!w.value.fast){b=!0;break}b&&(g.fast=!1)}let y={type:m.PARTIAL,name:u,data:g};return f!==void 0&&(y.whenCondition=Pn(f,t)),y}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'");o=Pn(l,t),n=!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=es(i,s,t);r.push({key:c,value:u.node}),n=!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=Ee(l,t);(u.type===m.FUNCTION||u.type===m.CONDITIONAL||u.type===m.PARTIAL||u.type===m.OBJECT&&!u.fast||u.type===m.ARRAY&&!u.fast)&&(n=!0);let f=ir(c,t),d={key:c,value:u};(f.type!==m.LITERAL||f.value!==c)&&(d.parsedKey=f),r.push(d),s++}}}let a={type:m.OBJECT,properties:r,fast:!n};return o&&(a.whenCondition=o),a},es=(e,t,r={})=>{let n=[],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());nr(l);let u=H(l,r);for(n.push(u),o.push(Ee(a,r)),i++;i<e.length;){let[f,d]=e[i],p=!1,h;if(c?f.startsWith(`$elif#${c} `)?(h=f.substring(`$elif#${c} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f===`$else#${c}`||f===`$else#${c}:`)&&(p=!0,h=null):f.startsWith("$elif ")?(h=f.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f==="$else"||f==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{nr(h);let g=H(h,r);n.push(g)}if(o.push(Ee(d,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:c},nextIndex:i}},sr={eq:R.EQ,neq:R.NEQ,gt:R.GT,gte:R.GTE,lt:R.LT,lte:R.LTE,in:R.IN,add:R.ADD,sub:R.SUBTRACT},ar={all:R.AND,any:R.OR},ts=new Set(["var","literal","call","not",...Object.keys(sr),...Object.keys(ar)]),rs=(e,t,r)=>{if(!Array.isArray(e))throw new v(`Condition JSON operator '${t}' at '${G(r)}' requires an array`);if(e.length!==2)throw new v(`Condition JSON operator '${t}' at '${G(r)}' requires exactly 2 operands`);return e},ns=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new v(`Condition JSON operator '${t}' at '${G(o)}' requires an array`);if(e.length===0)throw new v(`Condition JSON operator '${t}' at '${G(o)}' requires at least 1 condition`);return e.map((s,a)=>me(s,n,[...o,a])).reduce((s,a)=>({type:m.BINARY,op:r,left:s,right:a}))},os=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],ve(e,new Set(["call","args"]),r);else if(cr(e.call))n=e.call.name,o=e.call.args??[],ve(e,new Set(["call"]),r),ve(e.call,new Set(["name","args"]),[...r,"call"]);else throw new v(`Condition JSON call at '${G(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new v(`Condition JSON call at '${G(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new v(`Invalid condition JSON function name '${n}' at '${G(r)}'`);if(!Array.isArray(o))throw new v(`Condition JSON call '${n}' at '${G(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>me(i,t,[...r,"args",s]))}},me=(e,t={},r=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:m.LITERAL,value:e};if(Array.isArray(e))throw new v(`Condition JSON array at '${G(r)}' must be wrapped in an operator or { literal: [...] }`);if(!cr(e))throw new v(`Invalid condition JSON value at '${G(r)}'`);let n=Dn(e);if(n.length===0)throw new v(`Condition JSON object at '${G(r)}' must contain an operator`);let o=n.filter(s=>ts.has(s));if(o.length===0)throw new v(`Unknown condition JSON operator '${n[0]}' at '${G(r)}'`);if(o.length>1)throw new v(`Condition JSON at '${G(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(ve(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new v(`Condition JSON var at '${G(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return ve(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return os(e,t,r);if(i==="not")return ve(e,new Set(["not"]),r),{type:m.UNARY,op:Be.NOT,operand:me(e.not,t,[...r,"not"])};if(i in ar)return ve(e,new Set([i]),r),ns(e[i],i,ar[i],t,[...r,i]);if(i in sr){ve(e,new Set([i]),r);let s=rs(e[i],i,[...r,i]);return{type:m.BINARY,op:sr[i],left:me(s[0],t,[...r,i,0]),right:me(s[1],t,[...r,i,1])}}throw new v(`Unknown condition JSON operator '${i}' at '${G(r)}'`)},Pn=(e,t={})=>{if(e==null)throw new v("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new v("Empty condition expression after '$when'");return H(e,t)}return cr(e)||Array.isArray(e)?me(e,t):{type:m.LITERAL,value:e}},H=(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 H(l,t)}let r=ke(e,"||");if(r!==-1)return{type:m.BINARY,op:R.OR,left:H(e.substring(0,r).trim(),t),right:H(e.substring(r+2).trim(),t)};let n=ke(e,"&&");if(n!==-1)return{type:m.BINARY,op:R.AND,left:H(e.substring(0,n).trim(),t),right:H(e.substring(n+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=ke(e,l);if(f!==-1)return{type:m.BINARY,op:u,left:H(e.substring(0,f).trim(),t),right:H(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=ke(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:m.BINARY,op:s.type,left:H(e.substring(0,i).trim(),t),right:H(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let l of c)if(ke(e,l)!==-1)throw new v(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:m.UNARY,op:Be.NOT,operand:H(e.substring(1).trim(),t)}:Nn(e,t)},ke=(e,t)=>{let r=0,n=0;for(;n<=e.length-t.length;){if(e[n]==="(")r++;else if(e[n]===")")r--;else if(r===0&&e.substring(n,n+t.length)===t)return n;n++}return-1},is=e=>{if(e=e.trim(),e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:m.LITERAL,value:""};if(e==="{}")return{type:m.LITERAL,value:{}};if(e==="[]")return{type:m.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:m.LITERAL,value:t}:{type:m.VARIABLE,path:e}},Nn=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return Ze(r,t);let o=is(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return Ze(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},ss=(e,t=!1)=>{let r=t?"$each":"$for";try{vn(e)}catch(n){if(n instanceof v&&t){let o=n.message.replace(/\$for/g,"$each");throw new v(o.replace("Parse Error: ",""))}throw n}},Tn=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new v(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],a=i[2].trim();ss(a,n);let c=a.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let y=n?"$each":"$for";throw new v(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${a}')`)}let l=c[1].trim(),u=c[2].trim(),f,d=null;if(l.includes(",")){let y=l.split(",").map(b=>b.trim());if(y.length!==2)throw new v(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);f=y[0],d=y[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 h=Nn(u,r),g=Ee(t,r);return{type:m.LOOP,itemVar:f,indexVar:d,iterable:h,body:g,flatten:s!=="nested"}};var as=(e,t={})=>{let{functions:r={}}=t;return Ee(e,r)},wt=as;var et={};Ii(et,{now:()=>cs});var cs=()=>Date.now();var ls=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...et,...n},s=wt(e,{functions:i}),a={};for(let[c,l]of Object.entries(o))a[c]=wt(l,{functions:i});return or(s,t,{functions:i,partials:a})},ee=ls;var us=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",fs=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,ds=(e,t)=>{if(us(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new v("Empty condition expression");return H(e,t)}return me(e,t)},ps=(e,t={},r={})=>{let n=fs(r),o={...et,...n},i=ds(e,o);return!!we(i,{functions:o,partials:{}},t,{})},lr=ps;var rt=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return lr(e,t)},Un=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:a=c=>c}=r;for(let[c,l]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>l(s(n),...u):i[c]=(...u)=>{let f;return n=rr(n,p=>{let h=l(a(p),...u);f=h!==void 0&&!re(h)?h:void 0}),f});return{...o,...i}},xt=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return rr(n,i=>{o.forEach(s=>{t.forEach(a=>{a(i,s)})})})};var hs=(e,t)=>{if(e.default!==void 0)return e.default;let r=["number","boolean","string","object"];if(!r.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${r.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},ce=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),tt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),zn=e=>{let t=re(e)?Le(e):e;return structuredClone(t)},xe=e=>ce(e,"computed"),Ue=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!xe(t[r]))),ms=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),ur=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},gs=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=ms(e),[n,o,...i]=r;if(n==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return ur(s,i)}return n==="runtime"?ur(t.runtime,r.slice(1)):ur(t,r)},ys=(e,t,r)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(r!==void 0&&t.length!==r)throw new Error(`Computed expression operator "${e}" requires ${r} operand(s)`)},Vn=(e,t)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(t.length===0)throw new Error(`Computed expression operator "${e}" requires at least one operand`)},bs=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},ae=(e,t,r,n)=>(ys(e,t,n),t.map(o=>Et(o,r))),ie=(e,t,r,n)=>{let o=ae(e,t,r,n);return o.forEach(i=>bs(e,i)),o},Is=(e,t,r)=>{switch(e){case"var":return gs(t,r);case"add":{let[n,o]=ie(e,t,r,2);return n+o}case"sub":{let[n,o]=ie(e,t,r,2);return n-o}case"mul":{let[n,o]=ie(e,t,r,2);return n*o}case"div":{let[n,o]=ie(e,t,r,2);return n/o}case"mod":{let[n,o]=ie(e,t,r,2);return n%o}case"neg":{let[n]=ie(e,t,r,1);return-n}case"round":{let[n]=ie(e,t,r,1);return Math.round(n)}case"floor":{let[n]=ie(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=ie(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=ie(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=ie(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=ie(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=ae(e,t,r,2);return n==o}case"neq":{let[n,o]=ae(e,t,r,2);return n!=o}case"gt":{let[n,o]=ae(e,t,r,2);return n>o}case"gte":{let[n,o]=ae(e,t,r,2);return n>=o}case"lt":{let[n,o]=ae(e,t,r,2);return n<o}case"lte":{let[n,o]=ae(e,t,r,2);return n<=o}case"in":{let[n,o]=ae(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return Vn(e,t),t.every(n=>!!Et(n,r));case"or":case"any":return Vn(e,t),t.some(n=>!!Et(n,r));case"not":{let[n]=ae(e,t,r,1);return!n}case"length":{let[n]=ae(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:tt(n)?Object.keys(n).length:0}case"includes":{let[n,o]=ae(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return zn(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},Et=(e,t={})=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let r=Object.entries(e);if(r.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[n,o]]=r;return Is(n,o,t)},As=(e,t={})=>rt(e,{variables:t.variables,runtime:t.runtime}),ws=(e,t)=>{if(!tt(e))throw new Error(`${t} must be an object`);let r=ce(e,"expr"),n=ce(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},fr=(e,t,r)=>(ws(e,t),ce(e,"value")?zn(e.value):Et(e.expr,r)),vs=(e,t={},r="unknown")=>{if(!tt(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=ce(e,"expr"),o=ce(e,"value");if(ce(e,"branches")){if(n||o)throw new Error(`Computed variable "${r}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${r}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${r}" branches must not be empty`);if(!tt(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let a=e.branches[s];if(!tt(a))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!ce(a,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(As(a.when,t))return fr(a,`Computed variable "${r}" branch ${s}`,t)}return fr(e.default,`Computed variable "${r}" default`,t)}if(n===o)throw new Error(`Computed variable "${r}" must contain exactly one of expr, value, or branches`);return fr(e,`Computed variable "${r}"`,t)},Es=(e,t,r)=>{switch(t){case"number":if(typeof r!="number"||!Number.isFinite(r))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(r)?"array":typeof r}`);return;case"boolean":if(typeof r!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(r)?"array":typeof r}`);return;case"string":if(typeof r!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(r)?"array":typeof r}`);return;case"object":if(r===null||typeof r!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof r}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},Ct=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=Ue(e,r),i=Object.entries(r).filter(([,f])=>xe(f)).map(([f])=>f),s={},a=[],c=f=>{if(ce(s,f))return s[f];let d=r[f];if(!xe(d))return o[f];let p=a.indexOf(f);if(p>=0){let h=[...a.slice(p),f].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}a.push(f);try{let h=vs(d.computed,u,f);return Es(f,d.type,h),s[f]=h,h}finally{a.pop()}},l=new Proxy({},{get:(f,d)=>{if(typeof d=="string")return c(d)},has:(f,d)=>typeof d=="string"&&(ce(o,d)||i.includes(d)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(f,d)=>{if(!(typeof d!="string"||!ce(o,d)&&!i.includes(d)))return{enumerable:!0,configurable:!0}}}),u={variables:l,runtime:t,resolveVariable:c};return n?(i.forEach(f=>{c(f)}),{...o,...s}):l},xs=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>Ct({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),hr=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(xe(o))return;let i=hs(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},St=(e,t)=>{let r=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!r.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${r.join(", ")}`)},_t=(e,t,r)=>{let n={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=n[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${r}`);if(!Object.values(n).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${r}" of type "${e}". Valid operations: ${o.join(", ")}`)},Cs=2,jn=12,Wn=(e=Cs)=>{if(!Number.isInteger(e)||e<0||e>jn)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${jn}.`);return e},Ss=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},vt=e=>typeof e=="number"&&Number.isFinite(e),mr=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!vt(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!vt(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!vt(r))throw new Error(`Operation "divide" requires value to be a number for variable "${n}".`);if(t==="divide"){if(r===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${n}".`);Wn(o.roundTo)}}},Rt=(e,t,r,n={})=>{let o=(s,a,c)=>{let l=s??a;if(!vt(l))throw new Error(`Operation "${t}" requires ${c} to be a number.`);return l},i=s=>{let a=o(s,void 0,"value");if(a===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return a};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return Ss(o(e,0,"current value")/i(r),Wn(n.roundTo));case"increment":return o(e,0,"current value")+o(r,1,"value");case"decrement":return o(e,0,"current value")-o(r,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var qn=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let r=new Date(e),n=o=>String(o).padStart(2,"0");return t.replace("DD",n(r.getDate())).replace("MM",n(r.getMonth()+1)).replace("YYYY",r.getFullYear()).replace("YY",String(r.getFullYear()).slice(-2)).replace("HH",n(r.getHours())).replace("mm",n(r.getMinutes())).replace("ss",n(r.getSeconds()))},_s=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let a=i.character?.sprite;return a&&Object.keys(a).length>0&&(s.sprite=a),Object.keys(s).length>0?s:void 0},n=r(e),o=r(t);return JSON.stringify(n)===JSON.stringify(o)?null:n&&!o?{changeType:"delete",data:e}:o&&!n?{changeType:"add",data:t}:o&&n?{changeType:"update",data:t}:null},Mn=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};return e.transformId!==void 0&&(t.transformId=e.transformId),e.loop!==void 0&&(t.loop=e.loop),t},Fn=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},Bn=(e,t)=>t&&!e?{changeType:"add",data:t}:e&&!t?{changeType:"delete",data:e}:e&&t&&JSON.stringify(e)!==JSON.stringify(t)?{changeType:"update",data:t}:null,Rs=(e,t)=>{let r={},n=Bn(Mn(e),Mn(t)),o=Bn(Fn(e),Fn(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},gr=(e={},t={})=>{let r={},n=["sfx","voice"],o=a=>{let c=e[a],l=t[a];l&&!c?r[a]={changeType:"add",data:l}:c&&!l?n.includes(a)||(r[a]={changeType:"delete",data:c}):c&&l&&JSON.stringify(c)!==JSON.stringify(l)&&(r[a]={changeType:"update",data:l})},i=Rs(e.background,t.background);i&&(r.background=i),o("bgm"),o("voice");let s=_s(e.dialogue,t.dialogue);return s&&(r.dialogue=s),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),r},yr=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,!t.background.resourceId&&!t.background.colorId&&delete t.background);let r=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};r("layout"),r("choice"),r("form"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let n=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(a=>{let c={...a};return delete c.animations,i(c)?c:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return n("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),n("visual",o=>o.resourceId||o.transformId),t},Os=(e,t)=>{if(!e||!t)return;let r=e;for(let n of t.split(".")){if(r==null||!(n in Object(r)))return;r=r[n]}return r},$s=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let r=e.slice(7),n=Os(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},Ls={conditional:new Set(["branches"]),updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"]),form:new Set(["submitActions","cancelActions"]),submitForm:new Set(["actions"]),cancelForm:new Set(["actions"])},Yn=(e,t)=>{let r=e[e.length-1];return r?Ls[r]?.has(t)===!0:!1},dr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>dr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Yn(r,n)?o:dr(o,t,[...r,n])])):$s(e,t),pr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>pr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Yn(r,n)?o:pr(o,t,[...r,n])])):typeof e=="string"?ee(e,t):e,br=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let r=dr(e,t._event);return pr(r,t)};var ge=e=>structuredClone(re(e)?Le(e):e),nt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:ge(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Jn=(e,t)=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let r=e.map(n=>ge(n)).filter(n=>t(n)||n.animations);return{hasValidItems:r.length>0,processedItems:r}},le=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Kn=e=>e?.animations?.playback?.continuity==="persistent",Ot=(e,t)=>le(e??{},t)&&e[t]!==void 0,ks=e=>{if(e){if(e.character&&le(e.character,"name"))return e.character.name;if(le(e,"characterName"))return e.characterName}},Gn=e=>!!e?.character&&le(e.character,"sprite"),Ps=e=>{let t={},r=!1,n=ks(e);return n!==void 0&&(t.name=n,r=!0),Gn(e)&&(t.sprite=ge(e.character.sprite),r=!0),r?t:void 0},Hn=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Ts=({dialogueState:e,content:t,append:r=!1})=>{if(!r||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let n=Array.isArray(e.content)?e.content:[];n.length>0?e.initialRevealedContent=n.map(o=>ge(o)):delete e.initialRevealedContent,e.content=[...n,...t]},Ds=()=>({}),Ns=(e,t)=>{if(t.background){let r=Ot(t.background,"resourceId"),n=Ot(t.background,"colorId"),{animationsOnly:o,state:i}=nt(t.background,c=>Ot(c,"resourceId")||Ot(c,"colorId"));if(o){e.background=e.background?{...ge(e.background),...i}:i;return}if(!r&&!n){delete e.background;return}let s=e.background,a=ge(t.background);if(!r&&s?.resourceId&&(a.resourceId=s.resourceId,!le(a,"transformId")&&s.transformId&&(a.transformId=s.transformId)),!n&&s?.colorId&&(a.colorId=s.colorId),le(a,"resourceId")&&a.resourceId===void 0&&delete a.resourceId,le(a,"colorId")&&a.colorId===void 0&&delete a.colorId,le(a,"animations")&&a.animations===void 0&&delete a.animations,!a.resourceId&&!a.colorId){delete e.background;return}s?.resourceId===a.resourceId&&s?.transformId===a.transformId&&!le(a,"animations")&&Kn(s)&&(a.animations=ge(s.animations)),e.background=a}else e.background?.animations&&!Kn(e.background)&&(e.background.animations={})},Vs=(e,t)=>{if(!t.dialogue){e.dialogue&&(Hn(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let r=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:l,state:u}=nt(t.dialogue.ui,f=>!!f.resourceId);l?e.dialogue.ui={...e.dialogue.ui,...u}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let n=t.dialogue.append===!0&&r!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&Ts({dialogueState:e.dialogue,content:t.dialogue.content,append:n});let o=le(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=le(t.dialogue,"characterId"),s=Ps(t.dialogue),a=s!==void 0,c=Gn(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,a?e.dialogue.character=!i&&o&&e.dialogue.character?{...ge(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,c||Hn(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let l={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(l.character=ge(e.dialogue.character)),e.dialogue.lines.push(l)}},js=(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},Ms=(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}}},Fs=(e,t)=>{if(t.visual){let{hasValidItems:r,processedItems:n}=Jn(t.visual.items,o=>!!o.resourceId);r?e.visual={items:n}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(r=>r.animations?{...r,animations:{}}:r))},Bs=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:r,processedItems:n}=Jn(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);r?e.character={items:n}:delete e.character},Us=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},zs=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=nt(t.layout,o=>!!o.resourceId);if(r){e.layout=n;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},Ws=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=nt(t.choice,o=>!!o.resourceId);if(r){e.choice={...e.choice,...n};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},qs=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=nt(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=ge(t.form)}else e.form&&delete e.form},Ys=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},Ks=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},Hs=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},Pe=e=>xt(Ds,[Hs,Ns,js,Ms,Fs,Vs,Bs,Us,zs,Ws,qs,Ys,Ks])(e);var Js=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"}}),Te=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),ot=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Xn=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"}),Ir=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Ar=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Gs=(e,t)=>{if(t.startsWith("global.")){let r=t.slice(7);return e?.global?.[r]}if(t.startsWith("context.runtime.")){let r=t.slice(16),n=Array.isArray(e?.contexts)?e.contexts:[];return n[n.length-1]?.runtime?.[r]}},ze=e=>Object.fromEntries(Object.entries(Js).map(([t,r])=>{let n=Gs(e,r.source),o=n!==void 0?n:Te[t]??ot[t];return[t,o]})),Ie=(e,t)=>ze(e)[t],Qn=(e={})=>Object.fromEntries(Ir.map(t=>[t,e[t]??Te[t]]));var Ce={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:qn},Xs=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,Qs=(e,t)=>{let r=String(t||"").trim();if(!r)return;let n=r.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of n){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},Lt=(e,t,r)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),a=Xs.exec(s);if(a){let[,c,l,u]=a,f=Qs(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((p,h)=>{let g={...t,[c]:p};l&&(g[l]=h),d.forEach(y=>{let b=Lt(y,g,r),w=ee(b,g,r);Array.isArray(w)?o.push(...w):o.push(w)})});continue}}o.push(Lt(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=Lt(i,t,r)}),n},Vr=({animationType:e,animationId:t,animationPath:r})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${r}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},Zs=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);return Vr({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n&&(i.playback=structuredClone(n)),i},ea=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Vr({animationType:e.type,animationId:t,animationPath:r}),e.type},ta=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},ra=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},na=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),uo=e=>e?.playback?.continuity==="persistent",Sr=e=>Array.isArray(e)?e.map(Sr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=Sr(e[r]),t),{}),kt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify(Sr(t))},fo=(e=[])=>e.filter(t=>uo(t)).map(t=>structuredClone(t)),po=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,r)=>{let n=typeof r?.duration=="number"&&Number.isFinite(r.duration)?r.duration:0;return t+n},0):0,wr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,po(r)),0),ho=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(wr(e.tween),wr(e.prev?.tween),wr(e.next?.tween),po(e.mask?.progress)),Zn=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let r=new Set(t.map(kt).filter(Boolean));return e.some(n=>{if(!uo(n))return!1;let o=kt(n);return o?r.has(o):!1})},ue=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||Zn({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:Zn({animationInstances:e,activePersistentAnimations:o}),oa=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),ia=(e,t)=>{if(oa(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},sa=({resources:e,animationId:t,playback:r,instanceId:n,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?Zs({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},aa=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Vr({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},jr=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(aa(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},_r=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=ee(e,t);return r&&typeof r=="object"?e:r},Rr=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(r=>r===null||typeof r!="object"||Array.isArray(r)))throw new Error(`${t} must be an array of objects`);return e},ca=({content:e,path:t,variables:r})=>Rr(e,t).reduce((n,o)=>{let i=_r(o.text,{variables:r});return n+`${i??""}`.length},0),eo=(e=[])=>{let t=new Map;for(let r of e)r?.id&&t.set(r.id,(t.get(r.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,r])=>r>1).map(([r])=>r))},$t=(e,t=0,r=new Set)=>{if(!r.has(e?.id))return`character-container-${e.id}`;let n=e?.sprites?.map(({resourceId:o})=>o)||[];return n.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${n.join("-")}`},vr=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return r},la=(e,t={})=>{if(!t?.transformId)return;let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for background`);return r},ua=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},Or=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},fa=(e={})=>e.textStyles||{},da=(e={})=>e.images||{},pa=(e={})=>e.colors||{},ha=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,it=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,qe=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},to=(e,t,r)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);return e},Mr=(e,t)=>{if(typeof e!="string"||!ha.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(r=>r.repeat(2)).join("")}`:e},ro=(e,t,r)=>{let n=Mr(e,r);if(t===1)return n;let o=Number.parseInt(n.slice(1,3),16),i=Number.parseInt(n.slice(3,5),16),s=Number.parseInt(n.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},ma=(e={},t)=>{let r=fa(e)?.[t];if(!r)throw new Error(`Text style "${t}" not found`);let n=e.fonts?.[r.fontId];if(!n)throw new Error(`Font "${r.fontId}" not found for text style "${t}"`);let o=e.colors?.[r.colorId];if(!o)throw new Error(`Color "${r.colorId}" not found for text style "${t}"`);let i=to(r.colorAlpha,"colorAlpha",t),s={fontFamily:n.fileId,fontSize:r.fontSize??16,fontWeight:r.fontWeight??"400",fontStyle:r.fontStyle??"normal",lineHeight:r.lineHeight??1.2,fill:ro(o.hex,i,`Color "${r.colorId}" for text style "${t}"`)};if(r.align!==void 0&&(s.align=r.align),r.wordWrap!==void 0&&(s.wordWrap=r.wordWrap),r.breakWords!==void 0&&(s.breakWords=r.breakWords),r.wordWrapWidth!==void 0&&(s.wordWrapWidth=r.wordWrapWidth),r.strokeColorId){let a=e.colors?.[r.strokeColorId];if(!a)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let c=to(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=ro(a.hex,c,`Stroke color "${r.strokeColorId}" for text style "${t}"`)}else if(r.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return r.strokeWidth!==void 0&&(s.strokeWidth=r.strokeWidth),s},$r=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>$r(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${r}". Use textStyleId instead`);let n={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(n[o]=$r(i,t,it(r,o)));return e.textStyleId!==void 0&&(qe(e.textStyleId,r,"textStyleId"),n.textStyle=ma(t,e.textStyleId)),n},Fr=(e={},t)=>{let r=pa(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return Mr(r.hex,`Color "${t}"`)},mo=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Er=(e,t,r)=>{let n=e?.[t];if(!(!n||typeof n!="object"||Array.isArray(n))&&Object.prototype.hasOwnProperty.call(n,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${r}". Use ${mo(`${t}.fill`)} instead`)},ga=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>st(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;let n={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(n[o]=st(i,t,it(r,o)));return e.colorId!==void 0&&(qe(e.colorId,r,"colorId"),n.fill=Fr(t,e.colorId)),n},st=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>st(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${r}". Use ${mo("fill")} instead`);Er(e,"hover",r),Er(e,"click",r),Er(e,"rightClick",r)}let n={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){n[o]=ga(i,t,it(r,o));continue}n[o]=st(i,t,it(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(qe(e.colorId,r,"colorId"),n.fill=Fr(t,e.colorId)),n},xr=(e={},t)=>{let r=da(e)?.[t];return r||null},go=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",no=(e,t,r,n)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,n))throw new Error(`Inline ${t}.${n} is not allowed in sprite layout elements at "${r}". Use ${go(`${t}.${n}`)} instead`)},oo=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},Lr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Lr(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${r}". Use ${go(o)} instead`);no(e,"hover",r,"src"),no(e,"click",r,"src")}let n={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(n[o]=Lr(i,t,it(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){qe(e.imageId,r,"imageId");let o=xr(t,e.imageId),i=o?.fileId??e.imageId;n.src=i,n.width===void 0&&o?.width!==void 0&&(n.width=o.width),n.height===void 0&&o?.height!==void 0&&(n.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(qe(e.hoverImageId,r,"hoverImageId"),oo(n,"hover",xr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(qe(e.clickImageId,r,"clickImageId"),oo(n,"click",xr(t,e.clickImageId)?.fileId??e.clickImageId)),n},Br=(e,t={},r="root")=>Lr(st($r(e,t,r),t,r),t,r),Se=Br,Ye=(e=[])=>e.find(t=>t.id==="story"),ya="#000000",kr="bg-cg-background-color",ba=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?Mr(r?.backgroundColor??ya,"screen.backgroundColor"):Fr(e,t.colorId),Ia=({resources:e,background:t,screen:r={width:1920,height:1080}})=>({id:kr,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:ba({resources:e,background:t,screen:r})}),Aa=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.layouts?.[t]):!1,io=({resources:e={},resourceId:t,colorId:r})=>{let n=ua(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:Or({resourceId:t,kind:n})}:r!==void 0?{resourceId:kr,targetId:kr}:{resourceId:void 0,targetId:void 0}},yo=100,Tt=yo,bo=(e,t)=>e*t/yo,wa=(e={},t=Tt)=>e?.muteAll?0:bo(t,e?.soundVolume??Te.soundVolume),va=(e={},t=Tt)=>e?.muteAll?0:bo(t,e?.musicVolume??Te.musicVolume),Ea=({item:e,index:t}={})=>`sfx:${t}:${e?.resourceId}`,fe=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,confirmDialog:f,form:d,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:b}={})=>{let w={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??a??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},E=Ra({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e}),I={variables:e,runtime:w,saveSlots:r,isChoiceVisible:c,isFormVisible:l,canRollback:u,confirmDialog:f,form:d,historyDialogue:p,characters:h};return E&&(I.dialogue=E,I.dialogueLines=E.lines),I},so=100,Pt=(e,t)=>{if(Array.isArray(e))return e.map(n=>Pt(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=Pt(r[n],t)}),r.type==="text-revealing"?t(r):r},xa=e=>Pt(e,t=>({...t,revealEffect:"none"})),Ca=e=>Pt(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,so):so;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),_e=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?xa(e):r?Ca(e):e,Io=({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:{}}}}),Pr=e=>{if(Array.isArray(e))return e.map(Pr);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Pr(s);let r=t.click?.payload;if(!r||typeof r!="object"||Array.isArray(r))return t;let n=r.actions,o=n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"nextLine")?{...n.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...r,bypassChoice:!0,...o?{actions:{...n,nextLine:o}}:{}}}}},Sa=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),ao=(e,t)=>{let r=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},n=r.actions&&typeof r.actions=="object"?r.actions:{};return{...e||{},payload:{...r,actions:{...n,...t}}}},Tr=(e,t)=>{if(Array.isArray(e))return e.map(i=>Tr(i,t));if(!e||typeof e!="object")return e;let r={};for(let[i,s]of Object.entries(e))r[i]=Tr(s,t);if(r.type!=="input"||typeof r.field!="string")return r;let n=t?.fields?.[r.field];if(!n)return r;let o={updateFormField:{formId:t.id,formKey:t.key,field:n.id,value:"_event.value",_interactionSource:"form"}};return{...r,value:n.value,placeholder:r.placeholder===void 0?n.placeholder:r.placeholder,multiline:r.multiline===void 0?n.multiline:r.multiline,...r.maxLength===void 0&&n.maxLength!==void 0?{maxLength:n.maxLength}:{},change:ao(r.change,o),submit:ao(r.submit,t.submitActions)}},Dr=(e,t)=>{if(Array.isArray(e))return e.map(n=>Dr(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Dr(o,t);for(let n of Sa){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form",_formId:t.id,_formKey:t.key}})}return r},Nr=({characterId:e,character:t,characterName:r,characters:n={}}={})=>{let o=e?n?.[e]:void 0,i=t?.name!==void 0?t.name:r!==void 0?r:o?.name||"";return{...o||{},...t||{},name:i}},Ao=(e=[],t={})=>e.map(r=>{let n=Nr({characterId:r.characterId,character:r.character,characterName:r.characterName,characters:t}),o=typeof r.text=="string"?r.text:Array.isArray(r.content)?r.content.map(i=>i?.text??"").join(""):"";return{...r,text:o,character:n,characterName:n.name}}),_a=e=>!(!e||e.mode==="adv"&&e.content===void 0),Ra=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n}={})=>{if(!t&&!_a(e))return;let o=e.content===void 0?[{text:""}]:Rr(e.content,"dialogue.content"),i=e.content===void 0?0:ca({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),s=(e.lines||[]).map((c,l)=>{let u=Rr(c.content,`dialogue.lines[${l}].content`),f=Nr({characterId:c.characterId,character:c.character,characterName:c.characterName,characters:r});return{...c,content:u.map(d=>({...d,text:_r(d.text,{variables:n})})),character:f,characterName:f.name}}),a=Nr({characterId:e.characterId,character:e.character,characters:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:a,content:o.map(c=>({...c,text:_r(c.text,{variables:n})})),initialRevealedCharacters:i,lines:s}},wo=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=ee(e,r,{functions:Ce});return Se(_e(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},Cr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),co=({renderStateKeyboard:e,keyboard:t,phase:r})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([n,o])=>{let i=e[n]??{},s=r==="keydown"?o?.keydown:o?.keyup;if(r==="keydown"&&s&&typeof s=="object"){e[n]={...i,keydown:{payload:Cr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:Cr(o.keyup)});return}e[n]={...i,[r]:{payload:Cr(o)}}})},Oa=(e={},t={})=>{let r={};return co({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),co({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},Ae=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:a})=>{if(!e)return[];let c=[],l=({instanceId:b,targetId:w})=>{let E=sa({resources:t,animationId:p,playback:h,instanceId:b,targetId:w,animationPath:s});E&&c.push(E)},u=r!=null&&r!==!1,f=n!=null&&n!==!1,d=o&&i&&o===i;ia(e,s);let p=ta(e),h=ra(e),g=t?.animations?.[p],y=ea(g,{animationId:p,animationPath:s});if(y==="update")return f&&i?l({instanceId:`${a}-animation-update`,targetId:i}):u&&o&&l({instanceId:`${a}-animation-update`,targetId:o}),c;if(y==="transition"){let b=`${a}-animation-transition`,w=h?.continuity==="persistent"?b:`${a}-animation-in`;if(u&&f&&d)return l({instanceId:b,targetId:i}),c;u&&l({instanceId:`${a}-animation-out`,targetId:o}),f&&l({instanceId:w,targetId:i})}return c},$a=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),La=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:a,variables:c,runtime:l,activePersistentAnimations:u,restoredPersistentAnimations:f,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,saveSlots:w=[]})=>{let{elements:E,animations:I}=e;if(t.background){let N=n===void 0?!0:na(n?.background??{},"animations"),L=E.find(K=>K.id==="story");if(!L)return e;let V=la(o,t.background),M=r?.background?.resourceId,O=r?.background?.colorId,D=t.background.resourceId??(t.background.animations?M:void 0),F=t.background.colorId??(t.background.animations?O:void 0),k=Aa(o,D),W={...t.background,colorId:F};if((F!==void 0||k)&&L.children.push(Ia({resources:o,background:W,screen:i})),D){let{images:K={},videos:q={}}=o,j=K[D]||q[D];if(j){let pe=q[D]!==void 0,Z={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...V},Me={id:Or({resourceId:D,kind:pe?"video":"sprite"}),type:pe?"video":"sprite",x:Z.x,y:Z.y,src:j.fileId,width:j.width,height:j.height,alpha:1,anchorX:Z.anchorX,anchorY:Z.anchorY,rotation:Z.rotation,scaleX:Z.scaleX,scaleY:Z.scaleY};pe&&(Me.loop=t.background.loop??!1,Me.volume=j.volume??50),L.children.push(Me)}}if(D){let{layouts:K={}}=o,q=K[D];if(q){let j={id:Or({resourceId:D,kind:"container"}),type:"container",children:q.elements};V&&Object.assign(j,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...V});let pe=ee(j,fe({variables:c,runtime:l,saveSlots:w,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,characters:o.characters||{},skipTransitionsAndAnimations:a}),{functions:Ce});L.children.push(Se(_e(pe,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:a}),o))}}let x=io({resources:o,resourceId:M,colorId:O}),S=io({resources:o,resourceId:D,colorId:F}),B=Ae({animationsDef:t.background.animations,resources:o,previousResourceId:x.resourceId,currentResourceId:S.resourceId,previousTargetId:x.targetId,currentTargetId:S.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});ue({animationInstances:B,isLineCompleted:s,skipTransitionsAndAnimations:a,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:N})&&I.push(...B)}return e},ka=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:a,animations:c}=e;if(t.character&&n){let l=a.find(h=>h.id==="story");if(!l)return e;let u=t.character.items||[],f=r?.character?.items||[],d=eo(u),p=eo(f);for(let h=0;h<u.length;h++){let g=u[h],{transformId:y,sprites:b}=g,w=f.find(F=>F.id===g.id),E=f.findIndex(F=>F.id===g.id),I=w?.sprites&&w.sprites.length>0,N=b&&b.length>0,L=E>=0?$t(w,E,p):void 0,V=Ae({animationsDef:g.animations,resources:n,previousResourceId:L,currentResourceId:N?$t(g,h,d):void 0,previousTargetId:L,currentTargetId:N?$t(g,h,d):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&I&&ue({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){c.push(...V);continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let M=$t(g,h,d),O=n.transforms[y];if(!O){console.warn("Transform not found:",y);continue}let D={type:"container",id:M,x:g.x??O.x,y:g.y??O.y,anchorX:O.anchorX,anchorY:O.anchorY,rotation:O.rotation,scaleX:O.scaleX,scaleY:O.scaleY,children:[]};for(let F of b){let k=n.images[F.resourceId];if(!k){console.warn(`Image resource not found: ${F.resourceId}`);continue}D.children.push({type:"sprite",id:`${M}-${F.id}`,src:k.fileId,width:k.width,height:k.height,x:0,y:0})}l.children.push(D),ue({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...V)}}return e},Pa=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:a,activePersistentAnimations:c,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,saveSlots:g=[]})=>{let{elements:y,animations:b}=e;if(t.visual&&n){let w=y.find(I=>I.id==="story");if(!w)return e;let E=t.visual.items;for(let I of E){if(I.resourceId){let{images:M={},videos:O={},spritesheets:D={}}=n,F=D[I.resourceId];if(F){let k=vr(n,I),W=I.animationName;if(W){let x=F.animations?.[W];if(!x)throw new Error(`Animation '${W}' not found in spritesheet resource '${I.resourceId}'`);let S={id:`visual-${I.id}`,type:"animated-sprite",x:I.x??k.x,y:I.y??k.y,width:I.width??F.width,height:I.height??F.height,alpha:I.alpha??1,anchorX:k.anchorX,anchorY:k.anchorY,rotation:k.rotation,scaleX:k.scaleX,scaleY:k.scaleY,spritesheetSrc:F.fileId,spritesheetData:F.jsonData,animation:{frames:x.frames,animationSpeed:I.animationSpeed??x.animationSpeed??.5,loop:I.loop??x.loop??!0}};w.children.push(structuredClone(S))}}else{let k=M[I.resourceId]||O[I.resourceId];if(k){let W=O[I.resourceId]!==void 0,x=vr(n,I),S={id:`visual-${I.id}`,type:W?"video":"sprite",src:k.fileId,width:k.width,height:k.height,x:x.x,y:x.y,anchorX:x.anchorX,anchorY:x.anchorY,rotation:x.rotation,scaleX:x.scaleX,scaleY:x.scaleY};W&&(S.loop=k.loop??!1,S.volume=k.volume??50),w.children.push(S)}}}if(I.resourceId){let{layouts:M={}}=n,O=M[I.resourceId];if(O){let D=vr(n,I),F={id:`visual-${I.id}`,type:"container",children:structuredClone(O.elements),x:D.x,y:D.y,anchorX:D.anchorX,anchorY:D.anchorY,rotation:D.rotation,scaleX:D.scaleX,scaleY:D.scaleY},k=ee(F,fe({variables:s,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i}),{functions:Ce});w.children.push(Se(_e(k,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),n))}}let L=(r?.visual?.items||[]).find(M=>M.id===I.id),V=Ae({animationsDef:I.animations,resources:n,previousResourceId:L?.resourceId,currentResourceId:I.resourceId,previousTargetId:L?.resourceId?`visual-${I.id}`:void 0,currentTargetId:I.resourceId?`visual-${I.id}`:void 0,animationPath:`visual.items[${I.id}].animations`,idPrefix:I.id});ue({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:c})&&b.push(...V)}}return e},We="dialogue-character-sprite",lo=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,Ta=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:a}=e,c=Ye(e.elements);if(!c)return e;let l=t.dialogue?.character?.sprite,u=r?.dialogue?.character?.sprite,f=lo(l),d=lo(u),p=Ae({animationsDef:l?.animations,resources:n,previousResourceId:d?We:void 0,currentResourceId:f?We:void 0,previousTargetId:d?We:void 0,currentTargetId:f?We:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!f)return l?.animations&&d&&ue({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...p),e;let h=n.transforms?.[l.transformId];if(!h)return console.warn("Transform not found:",l.transformId),e;let g={type:"container",id:We,x:h.x,y:h.y,anchorX:h.anchorX,anchorY:h.anchorY,rotation:h.rotation,scaleX:h.scaleX,scaleY:h.scaleY,children:[]};for(let y of l.items){let b=n.images?.[y.resourceId];if(!b){console.warn(`Image resource not found: ${y.resourceId}`);continue}g.children.push({type:"sprite",id:`${We}-${y.id}`,src:b.fileId,width:b.width,height:b.height,x:0,y:0})}return c.children.push(g),ue({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...p),e},Da=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:u,skipOnlyViewedLines:f,isLineCompleted:d,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:y,saveSlots:b=[]})=>{let{elements:w,animations:E}=e;if(!t.dialogue||o)return e;let I=w.find(L=>L.id==="story");if(!I)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:L={}}=n,V=L[t.dialogue.ui.resourceId];if(V){let M={elements:V.elements},O=fe({variables:h,runtime:g,saveSlots:b,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:d,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:u,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:f,skipTransitionsAndAnimations:p}),D={functions:Ce},F=Lt(M,O,D),k=ee(F,O,D),W=Se(_e(k?.elements,{isLineCompleted:d,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(W))for(let x of W)I.children.push(x);else W&&I.children.push(W)}}Ta(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let N=Ae({animationsDef:t.dialogue.ui?.animations,resources:n,previousResourceId:r?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:r?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return ue({animationInstances:N,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&E.push(...N),e},Na=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,runtime:c,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:b,animations:w}=e;if(t.choice&&n){let E=Ye(b);if(!E)return e;let I=n?.layouts[t.choice.resourceId];if(I&&I.elements){let L={elements:I.elements},V=ee(L,{...fe({variables:a,runtime:c,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:u,isChoiceVisible:f??!!t.choice,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:Ce}),M=Pr(Se(_e(V?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n));if(Array.isArray(M))for(let O of M)E.children.push(O);else M&&E.children.push(M)}let N=Ae({animationsDef:t.choice.animations,resources:n,previousResourceId:r?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:r?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});ue({animationInstances:N,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&w.push(...N)}return e},Va=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,runtime:c,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:b,animations:w}=e;if(!y?.resourceId||!n)return e;let E=Ye(b);if(!E)return e;let I=n?.layouts?.[y.resourceId];if(!I)return console.warn(`Form layout not found: ${y.resourceId}`),e;let N={id:"form-container",type:"container",x:0,y:0,children:I.elements||[]},L={...fe({variables:a,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},V=ee(N,L,{functions:Ce}),M=Dr(Se(_e(Tr(V,y),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n),y);M&&E.children.push(M);let O=Ae({animationsDef:y.animations,resources:n,previousResourceId:r?.form?.resourceId,currentResourceId:y.resourceId,previousTargetId:r?.form?.resourceId?"form-container":void 0,currentTargetId:y.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return ue({animationInstances:O,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&w.push(...O),e},ja=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,saveSlots:d=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=Oa(h.keyboard,h.keyup);if(g&&Object.keys(g).length>0&&(e.global.keyboard=g),!Array.isArray(h.elements)||h.elements.length===0)return e;let y=Ye(e.elements);if(!y)return e;let b={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(wo({container:b,resources:r,templateData:fe({variables:n,runtime:o,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:a,skipTransitionsAndAnimations:p})),e},Ma=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Ye(i))return e;let c=r.sounds[t.bgm.resourceId];if(!c)return e;let l=fe({variables:o,runtime:n}).runtime;s.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:va(l,t.bgm.volume??c.volume??Tt),startDelayMs:t.bgm.startDelayMs??null})}return e},Fa=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx.items;for(let[s,a]of i.entries()){let c=r.sounds?.[a.resourceId];c&&o.push({id:Ea({item:a,index:s}),type:"sound",src:c.fileId,loop:a.loop??c.loop??!1,volume:wa(n,a.volume??c.volume??Tt),startDelayMs:a.startDelayMs??c.startDelayMs??null})}}return e},Ba=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},Ua=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,za=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let a=t.voice,{resourceId:c,loop:l,startDelayMs:u}=a,f=Ba(r,n,c);if(!f)return e;let d=fe({variables:i,runtime:o}).runtime;return s.push({id:`voice-${n}-${c}`,type:"sound",src:f.fileId,volume:Ua(a,d),loop:l??!1,startDelayMs:u??null}),e},Wa=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,saveSlots:d=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:b}=e;if(t.layout){let N=Ye(y);if(!N)return e;let L=n.layouts[t.layout.resourceId];if(!L)return e;Array.isArray(L.transitions)&&!p&&!h&&jr({animations:b,transitions:L.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let V={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:L.elements||[]};N.children.push(wo({container:V,resources:n,templateData:fe({variables:o,runtime:i,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:a,skipTransitionsAndAnimations:h}))}let w=r?.layout?.resourceId,E=t.layout?.resourceId,I=Ae({animationsDef:t.layout?.animations,resources:n,previousResourceId:w,currentResourceId:E,previousTargetId:w?`layout-${w}`:void 0,currentTargetId:E?`layout-${E}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return ue({animationInstances:I,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(...I),e},qa=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:a}=e,c=t?.screen?.animations;if(!c)return e;let l=r!=null,u=Ae({animationsDef:c,resources:n,previousResourceId:l?"story":void 0,currentResourceId:"story",previousTargetId:l?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return ue({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...u),e},Ya=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:u,overlayStack:f=[],dialogueHistory:d=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:w}=e;return f&&f.length>0&&f.forEach((E,I)=>{let N=r.layouts[E.resourceId];if(!N){console.warn(`Overlay layout not found: ${E.resourceId}`);return}Array.isArray(N.transitions)&&(y||jr({animations:w,transitions:N.transitions,defaultTargetId:`overlayStack-${I}`,idPrefix:`overlayStack-${I}`,animationPathPrefix:`overlayStack[${I}]`}));let L={id:`overlayStack-${I}`,type:"container",x:0,y:0,children:[Io({id:`overlayStack-${I}-blocker`,screen:h}),...N.elements||[]]},V=Ao(d,r.characters),M=fe({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:u,historyDialogue:V,characters:r.characters||{},skipTransitionsAndAnimations:y}),O=ee(L,M,{functions:Ce}),[D,...F]=O.children||[],k=Se(_e({...O,children:F},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...k,children:D?[D,...k.children||[]]:k.children})}),e},Ka=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,confirmDialog:d,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:w}=e;if(!d?.resourceId)return e;let E=r.layouts?.[d.resourceId];if(!E)return console.warn(`ConfirmDialog layout not found: ${d.resourceId}`),e;Array.isArray(E.transitions)&&!y&&jr({animations:w,transitions:E.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let I={id:"confirmDialog",type:"container",x:0,y:0,children:[Io({id:"confirmDialog-blocker",screen:h}),...E.elements||[]]},N=Ao(p,r.characters),L=ee(I,fe({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:u,form:f,confirmDialog:d,historyDialogue:N,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:Ce}),[V,...M]=L.children||[],O=Se(_e({...L,children:M},{isLineCompleted:g,skipMode:a,skipTransitionsAndAnimations:y}),r);return b.push({...O,children:V?[V,...O.children||[]]:O.children}),e},vo=e=>xt($a,[ja,La,ka,Pa,Da,Na,Va,Wa,qa,Ma,Fa,za,Ya,Ka])(e);var Dt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},_o=1,Ur="choice",Nt="form",Mt=()=>({manual:{...Dt.manual},auto:{...Dt.auto},applyMode:Dt.applyMode}),zr=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...Mt()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},T=e=>{let t=re(e)?Le(e):e;return structuredClone(t)},P=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ft=e=>String(e),Ro=()=>({sections:[],resources:[]}),Ha=e=>P(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Ro(),Ja=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Ga=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:Ja(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),Xa=()=>({resourceId:void 0}),Qa=e=>{if(!P(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},Wr=(e,t)=>{let r=e?.story?.scenes??{};for(let[n,o]of Object.entries(r))if(o?.sections?.[t])return{sceneId:n,section:o.sections[t]};return{sceneId:void 0,section:void 0}},Oo=e=>{let t=e?.story?.scenes??{},r=new Map;for(let[n,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let a=r.get(s);if(a!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${a}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},$o=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Lo=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==_o)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Za=(e,t={})=>{let r;try{r=Lo(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:$o(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},ec=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Za(t,r)])),ko=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Wl(r));return t.length>0?t:void 0},tc=e=>{!P(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!P(t))return;let r=ko(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},Eo=(e,t,r,n="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!P(e))throw new Error(`Malformed ${n}.${t}[${r}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${n}.${t}[${r}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${n}.sections[${r}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},rc=(e,t="viewedRegistry")=>{if(e===void 0)return Ro();if(!P(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let r=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Eo(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Eo(o,"resources",i,t);return[s.resourceId,s]})))}},Po=(e,t,r)=>{if(!P(e))throw new Error(`Malformed save slot ${r}.`);let{sectionId:n,lineId:o}=e;if(typeof n!="string"||n.length===0)throw new Error(`Malformed save slot ${r}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${r}: missing lineId.`);let{sceneId:i,section:s}=Wr(t,n);if(!s)throw new Error(`Malformed save slot ${r}: section "${n}" does not exist in projectData.`);if(!s.lines?.some(c=>c.id===o))throw new Error(`Malformed save slot ${r}: line "${o}" does not exist in section "${n}".`);return{sceneId:i,sectionId:n,lineId:o}},nc=(e,t,r)=>{if(!P(e)||!Array.isArray(e.timeline))return at({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((a,c)=>{if(!P(a))return[];try{let l=Po(a,r,`rollback.timeline[${c}]`),u=jt({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:a.rollbackPolicy}),f=ko(T(a.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(n.length===0)return at({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):n.length-1;(o<0||o>=n.length)&&(o=n.length-1);let i=n[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let a=n.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);a>=0?o=a:(n.push(jt({sectionId:t.sectionId,lineId:t.lineId})),o=n.length-1)}let s=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),o):0;return{currentIndex:o,isRestoring:!1,replayStartIndex:s,timeline:n}},oc=(e,t,r)=>{if(!P(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=Kr(t),o=Po(e.pointers?.read,t,`contexts[${r}].pointers.read`);if(e.variables!==void 0&&!P(e.variables))throw new Error(`Malformed save slot contexts[${r}].variables entry.`);if(e.runtime!==void 0&&!P(e.runtime))throw new Error(`Malformed save slot contexts[${r}].runtime entry.`);let i=e.variables?Ue(T(e.variables),t.resources?.variables??{}):{},s=yc({loadedContextRuntime:P(e.runtime)?T(e.runtime):{}}),a={currentPointerMode:"read",pointers:{read:o},configuration:P(e.configuration)?T(e.configuration):{},views:Array.isArray(e.views)?T(e.views):[],bgm:P(e.bgm)?T(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:nc(e.rollback,o,t)};return s&&(a.runtime=s),a},ic=(e,t)=>{if(!P(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((r,n)=>oc(r,t,n))}},sc=(e,t)=>{if(!P(e))throw new Error("Malformed save slot.");let r=Lo(e.formatVersion);return{...e,formatVersion:r,state:ic(e.state,t)}},xo=(e,t,{required:r=!1}={})=>{if(e===void 0){if(r)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let n=T(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},ac=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:xo(e.confirmActions,"confirmActions",{required:!0}),cancelActions:xo(e.cancelActions,"cancelActions")}},He=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},cc=e=>(P(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),Je=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},To=e=>{if(!(!P(e)||!e.animations))return{animations:T(e.animations)}},lc=(e,t)=>{let r=To(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},uc=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},fc=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},Vt=e=>String(e??""),Do=(e,t)=>{let r=Vt(t);return e?.trim===!0?r.trim():r},dc=e=>P(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>P(t)).map(([t,r])=>[t,{id:t,...T(r)}])):{},pc=(e,t)=>{if(!t||!P(e.global.formDrafts))return;let r=e.global.formDrafts[t];return P(r)?r:void 0},No=(e,t)=>{let r=cc(e);P(r[t])||(r[t]={values:{},touched:{},errors:{},submitted:!1});let n=r[t];return P(n.values)||(n.values={}),P(n.touched)||(n.touched={}),P(n.errors)||(n.errors={}),typeof n.submitted!="boolean"&&(n.submitted=!1),n},qr=(e,t)=>{let r=Do(e,t);return e?.required===!0&&r.length===0?"required":null},hc=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=X({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:Pe(n.slice(0,o+1).map(i=>i.actions||{}))},mc=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=uc(t),o=fc(r,n);if(!n||!o)return null;let i=pc(e,o),s=dc(t),a=Qr({state:e}),c={},l=[],u={},f=!0;return Object.entries(s).forEach(([d,p])=>{let h=Vt(a?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},d)?Vt(i.values[d]):h,y=i?.touched?.[d]===!0,b=qr(p,g),w=i?.submitted||y?b:null,E=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,I={id:d,variableId:p.variableId,value:g,initialValue:h,valid:!b,error:w,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...E!==void 0?{maxLength:E}:{}};b&&(f=!1),c[d]=I,l.push(I),u[d]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:f,submitted:i?.submitted===!0,fields:c,fieldList:l,values:u,submitActions:{submitForm:{formId:n,formKey:o,actions:T(t.submitActions??{})}},cancelActions:{cancelForm:{formId:n,formKey:o,actions:T(t.cancelActions??{})}}}},De=[],Co="line",Yr="interaction",jt=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),Kr=e=>{let{contextVariableDefaultValues:t}=hr(e??{});return T(t)},Vo=()=>({...T(ot)}),jo=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:T(r),hasLoadedValues:!1};if(!P(e))throw new Error(`Malformed ${n}.`);let o=T(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Mo(s,T(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},gc=({loadedGlobalRuntime:e={}})=>jo({loadedRuntime:e,runtimeIds:Ir,defaults:Te,path:"global.runtime"}).runtimeState,yc=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=jo({loadedRuntime:e,runtimeIds:Ar,defaults:Vo(),path:"context.runtime"});return r?t:void 0},Hr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},bc=e=>e.runtime?(Ar.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=T(ot[t]))}),e.runtime):(e.runtime=Vo(),e.runtime),Ic=e=>Qn(e.global),Ac=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Ic(e)}})},wc=e=>Xn[e],vc=(e,t)=>{let r=wc(e);if(r==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(r==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(r==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},Mo=(e,t)=>(vc(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),Fo=(e,t,r)=>{let n=Mo(t,r);if(t in ot){let o=Hr(e);if(!o)return n;let i=bc(o);return i[t]=n,n}return e.global[t]=n,n},Bo=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:T(e)},configuration:{},views:[],bgm:Xa(),variables:Kr(t),rollback:at({pointer:e})}),Ge=e=>e?(e.currentPointerMode="read",P(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Ec=(e,{queueRender:t=!0}={})=>{let r=e.contexts?.[e.contexts.length-1],n=r?.pointers?.read;if(!r||!n?.sectionId||!n?.lineId)return null;let o=Bo({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,xc(e,{queueRender:t}),o},xc=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,He(e),Je(e),e.global.nextLineConfig=Mt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},Uo=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},at=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[jt({sectionId:e.sectionId,lineId:e.lineId})]:[]}},Ve=(e,t={})=>{if(e?.rollback)return Uo(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let r=e?.pointers?.read;return e.rollback=at({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},Jr=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=Ve(r);if(n.isRestoring)return;n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1));let o=n.timeline[n.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){n.currentIndex=n.timeline.length-1;return}n.timeline.push(jt(t)),n.currentIndex=n.timeline.length-1},Cc=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;if(!r||r.isRestoring||!Array.isArray(r.timeline)||typeof r.currentIndex!="number")return null;let n=De[De.length-1],o=typeof n?.checkpointIndex=="number"?n.checkpointIndex:r.currentIndex;return o<0||o>=r.timeline.length?null:(typeof n?.checkpointIndex!="number"&&o<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,o+1)),r.timeline[o]??null)},Sc=({state:e},t={})=>{let r=t?.source===Co?Co:Yr,o=e.contexts?.[e.contexts.length-1]?.rollback;return!o||o.isRestoring||!Array.isArray(o.timeline)||typeof o.currentIndex!="number"||o.currentIndex<0||o.currentIndex>=o.timeline.length?(De.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),De.push({checkpointIndex:o.currentIndex,source:r}),e)},_c=({state:e})=>(De.pop(),e),ye=(e,t,r)=>{let o=De[De.length-1]?.source??Yr;if(!ql(t,o))return;let i=Cc(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:T(r)}))},So=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:a}of n){let c=e.projectData.resources?.variables?.[o],l=c?.scope,u=c?.type;if(xe(c))throw new Error(`Cannot update computed variable: ${o}`);if(c?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);St(l,o),_t(u,i,o),mr(u,i,s,o,{roundTo:a}),l==="context"&&(r.variables[o]=Rt(r.variables[o],i,s,{roundTo:a}))}},Rc=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{Yl(e,r,n)})},Oc=(e,t)=>{let{sectionId:r,lineId:n}=t,s=X({state:e},{sectionId:r})?.lines?.find(a=>a.id===n)?.actions;s&&Object.entries(s).forEach(([a,c])=>{ii(e,a,c)})},zo=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=Ve(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&<({state:e}),e.global.skipMode&&Ne({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=Kr(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=T(Dt),e.global.overlayStack=[],He(e),Je(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let a=i;a<=t;a++)a>i&&zr(e),Oc(e,n.timeline[a]),Rc(e,n.timeline[a]);let s=Ge(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(a=>a?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},$c=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;Oo(t);let a=t.story.initialSceneId,c=t.story.scenes[a],l=c.initialSectionId,u=c.sections[l],f={sceneId:a,sectionId:l,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:d}=hr(t),p={...d,...Ue(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:rc(s,"accountViewedRegistry"),nextLineConfig:Mt(),saveSlots:ec(n),overlayStack:[],variables:p,...gc({loadedGlobalRuntime:i})},contexts:[Bo({pointer:f,projectData:t})]}},Lc=({state:e})=>e.global.overlayStack||[],kc=({state:e})=>e.global.pendingEffects,Wo=({state:e})=>e.global.skipMode,Pc=({state:e})=>e.global.autoMode,qo=({state:e})=>e.global.dialogueUIHidden,Yo=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(!r)return[];let{sectionId:n,lineId:o}=r.pointers.read,i=X({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),a=i.lines.slice(0,s+1),c=[],l={};for(let u of a){let f=u.actions||{};if(l=Pe([l,f]),!f.dialogue)continue;let d=l.dialogue||{},p="";d.character?.name!==void 0?p=d.character.name:d.characterId&&(p=e.projectData.resources?.characters?.[d.characterId]?.name||"");let h=Ga({sectionId:n,lineId:u.id,content:f.dialogue.append===!0?d.content:f.dialogue.content,dialogueState:d,characterName:p});if(f.dialogue.append===!0&&c.length>0){c[c.length-1]={...c[c.length-1],content:h.content,text:h.text,characterId:h.characterId,character:h.character,characterName:h.characterName};continue}c.push(h)}return c},Tc=({state:e})=>e.global.confirmDialog??null,ct=({state:e},{pointer:t}={})=>{let r=t??de({state:e})?.pointer,n=hc({state:e,pointer:r});return mc({state:e,form:n.form,pointer:r})},Dc=({state:e},{pointer:t}={})=>!!ct({state:e},{pointer:t}),be=({state:e},{pointer:t}={})=>{let r=ct({state:e},{pointer:t});if(r)return{source:Nt,formId:r.id,formKey:r.key};let n=Ko({state:e,pointer:t});return n?{source:Ur,resourceId:n}:null},Nc=({state:e,registry:t},r)=>{let{sectionId:n,lineId:o}=r,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===n);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let a=X({state:e},{sectionId:n});if(!a||!a.lines||!Array.isArray(a.lines))return s.lastLineId===o;let c=a.lines.findIndex(u=>u.id===s.lastLineId),l=a.lines.findIndex(u=>u.id===o);return c===-1||l===-1?s.lastLineId===o:l<=c},Vc=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},Gr=({state:e},t)=>Nc({state:e,registry:e.global.accountViewedRegistry},t),jc=({state:e},t)=>Vc({registry:e.global.accountViewedRegistry},t),Mc=({state:e})=>e.global.nextLineConfig,Ko=({state:e,pointer:t}={})=>{let r=t??de({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=X({state:e},{sectionId:n})?.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},Ho=({state:e})=>!!Ko({state:e}),Fc=({state:e})=>structuredClone(e),Jo=({state:e})=>e.global.saveSlots,Bc=({state:e},t)=>{let r=t?.slotId,n=Ft(r);return e.global.saveSlots[n]},Xr=({state:e})=>ze(e),Uc=({state:e},t)=>Ie(e,t?.runtimeId),Qr=({state:e})=>{let t={...e.global?.variables??{},...Hr(e)?.variables??{}};return Ct({variables:t,runtime:ze(e),variableConfigs:e.projectData.resources?.variables??{}})},de=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},X=({state:e},t)=>{let{sectionId:r}=t;return Wr(e.projectData,r).section},Zr=({state:e})=>{let t=de({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=X({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},Go=({state:e})=>{let{sectionId:t,lineId:r}=de({state:e}).pointer,o=X({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===r),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 Pe(a)},zc=({state:e})=>{let t=Xo({state:e}),n=Zr({state:e})?.actions??{},o=Pe([t??{},n]);return gr(t??{},o??{})},Wc=({state:e},{sectionId:t})=>{let r=X({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},a=Pe([o,s]),c=gr(o,a);n.push({id:i.id,changes:c,presentationState:a}),o=yr(a)}return n},qc=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=Wc({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},Xo=({state:e})=>{let{sectionId:t,lineId:r}=de({state:e}).pointer,o=X({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===r);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 yr(Pe(a))},en=({state:e},{slotsPerPage:t=6}={})=>{let o=((Xr({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[Ft(a)]||{};i.push({...c,slotId:a})}return{saveSlots:i}},Yc=Jo,Kc=en,Hc=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;return!r||!Array.isArray(r.timeline)||typeof r.currentIndex!="number"?!1:r.currentIndex>=0&&r.currentIndex<r.timeline.length-1},Jc=({state:e},t={})=>{let r=Go({state:e}),n=Xo({state:e}),o=Zr({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:T(i)}:o,a=i?.animations&&n===null?{}:n,{sectionId:c}=de({state:e}).pointer,{sceneId:l}=Wr(e.projectData,c),u=Xr({state:e}),f=t?.activePersistentAnimations??[],d=t?.restoredPersistentAnimations??[],p=ct({state:e}),h=Ho({state:e}),g=Qr({state:e}),{saveSlots:y}=en({state:e}),b=Hc(e);return vo({presentationState:r,previousPresentationState:a,currentLineActions:s,resources:e.projectData.resources,currentSceneId:l,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:ai({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:Yo({state:e}),saveSlots:y,variables:g,runtime:u,activePersistentAnimations:f,restoredPersistentAnimations:d})},Gc=({state:e},t)=>(e.global.confirmDialog=ac(t),e.global.pendingEffects.push({name:"render"}),e),Xc=({state:e})=>(e.global.confirmDialog&&(He(e),e.global.pendingEffects.push({name:"render"})),e),Qc=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),ye(e,"pushOverlay",t),e),Zc=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),ye(e,"popOverlay",void 0),e),el=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),ye(e,"replaceLastOverlay",t),e),tl=({state:e})=>(e.global.overlayStack=[],He(e),Je(e),e.global.pendingEffects.push({name:"render"}),ye(e,"clearOverlays",void 0),e),rl=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"})},Bt=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,lc(e,r),Je(e);let n=be({state:e},{pointer:t}),o=n?.source===Ur,i=n?.source===Nt;return n&&rl(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},Qo=({state:e})=>(be({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:Ie(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),lt=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),nl=({state:e})=>{let t=e.global.autoMode;return be({state:e})&&!t||(t?lt({state:e}):Qo({state:e})),e},Zo=({state:e})=>(be({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),Ne=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),ol=({state:e})=>{let t=Wo({state:e});return be({state:e})&&!t||(t?Ne({state:e}):Zo({state:e})),e},Ut=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),ye(e,"showDialogueUI",void 0),e),ei=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),ye(e,"hideDialogueUI",void 0),e),il=({state:e})=>(qo({state:e})?Ut({state:e}):ei({state:e}),e),je=(e,t,r)=>(Fo(e,t,r),Ac(e),e.global.pendingEffects.push({name:"render"}),e),ut=(e,t,r,n)=>{let o=Fo(e,t,r);return e.global.pendingEffects.push({name:"render"}),ye(e,n,{value:o}),e},sl=({state:e},t)=>je(e,"dialogueTextSpeed",t?.value),al=({state:e},t)=>je(e,"autoForwardDelay",t?.value),cl=({state:e},t)=>je(e,"skipUnseenText",t?.value),ll=({state:e},t)=>je(e,"skipTransitionsAndAnimations",t?.value),ul=({state:e},t)=>je(e,"soundVolume",t?.value),fl=({state:e},t)=>je(e,"musicVolume",t?.value),dl=({state:e},t)=>je(e,"muteAll",t?.value),pl=({state:e},t)=>ut(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),hl=({state:e})=>{let t=Ie(e,"saveLoadPagination")+1;return ut(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},ml=({state:e})=>{let t=Ie(e,"saveLoadPagination")-1;return ut(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},gl=({state:e},t)=>ut(e,"menuPage",t?.value,"setMenuPage"),yl=({state:e},t)=>ut(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),bl=({state:e})=>(e.global.pendingEffects=[],e),Il=({state:e},t)=>(e.global.pendingEffects.push(t),e),ti=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!To(n),i=X({state:e},{sectionId:t});if(!i)return console.warn(`Section not found: ${t}`),e;let s=i.lines?.[0];if(!s)return console.warn(`Section ${t} has no lines`),e;if(r&&!Ec(e,{queueRender:!o}))return e;e.global.autoMode&<({state:e}),r&&e.global.skipMode&&Ne({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let c=Ge(a),l=c.read;r||Ke(e,{sectionId:l?.sectionId,lineId:l?.lineId}),a.rollback||Ve(a,{compatibilityAnchor:!0}),c.read={sectionId:t,lineId:s.id},r?a.rollback=at({pointer:c.read}):Jr(e,{sectionId:t,lineId:s.id})}return Bt(e,a?.pointers?.read,{screenTransition:n}),e},Al=({state:e},t)=>ti(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),ri=e=>(e.global.accountViewedRegistry=Ha(e.global.accountViewedRegistry),e.global.accountViewedRegistry),tn=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(r=>({scope:r.scope,path:r.path,op:r.op,value:T(r.value)}))}})},ni=(e,t)=>{tn(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(r=>({sectionId:r.sectionId,...r.lastLineId===void 0?{}:{lineId:r.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},wl=(e,t,{sectionId:r,lineId:n})=>{if(!r||!n)return!1;let o=P(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===r);if(i){if(i.lastLineId===void 0)return!1;let s=X({state:e},{sectionId:r});if(s?.lines){let a=s.lines.findIndex(l=>l.id===i.lastLineId),c=s.lines.findIndex(l=>l.id===n);if(a===-1||c>a)return i.lastLineId===n?!1:(i.lastLineId=n,!0)}else return i.lastLineId===n?!1:(i.lastLineId=n,!0);return!1}else return o.sections.push({sectionId:r,lastLineId:n}),!0},Ke=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;wl(e,ri(e),t)&&ni(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},vl=({state:e},t)=>(Ke(e,t),e.global.pendingEffects.push({name:"render"}),e),El=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=ri(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),ni(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},oi=({state:e},t)=>{let r=Qa(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,a=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;r&&n?(e.global.nextLineConfig={manual:r,auto:n},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(r&&(e.global.nextLineConfig.manual=r),n&&(e.global.nextLineConfig.auto=n),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let c=e.global.nextLineConfig.auto?.enabled,l=be({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"}),ye(e,"setNextLineConfig",t),e},xl=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:n}=t,o=t?.savedAt,i=Ft(r),s=T(e.contexts);s?.forEach(l=>{Ge(l),Uo(l.rollback),tc(l.rollback)});let a={contexts:s},c={formatVersion:_o,slotId:$o(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:a};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Cl=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=Ft(r),o=e.global.saveSlots[n];if(o){let i=sc(o,e.projectData);e.contexts=i.state.contexts,e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=Mt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,He(e),Je(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},Sl=({state:e},t)=>{let{projectData:r}=t;Oo(r),e.projectData=r;let n=r?.resources?.variables??{};return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables=Ue(e.global.variables,n)),e.contexts?.forEach(o=>{Object.prototype.hasOwnProperty.call(o??{},"variables")&&(o.variables=Ue(o.variables,n))}),He(e),Je(e),e.global.pendingEffects.push({name:"render"}),e},_l=({state:e},t)=>{let{sectionId:r,lineId:n}=t;if(!n)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=r||o.pointers.read?.sectionId;if(r&&!X({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=X({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(l=>l.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let c=Ge(o);return c.read={sectionId:i,lineId:n},Bt(e,c.read),e},Rl=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return Ut({state:e}),e;let r=be({state:e});if(r?.source===Ur&&t?.bypassChoice!==!0||r?.source===Nt&&t?._interactionSource!==Nt)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=de({state:e})?.pointer,f=u?.sectionId,d=u?.lineId;f&&d&&Ke(e,{sectionId:f,lineId:d}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ie(e,"autoForwardDelay")}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=de({state:e})?.pointer,o=n?.sectionId,i=X({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],a=i?.lines||[],l=a.findIndex(u=>u.id===n?.lineId)+1;if(l<a.length){let u=a[l],f=!Ie(e,"skipUnseenText");if(e.global.skipMode&&f&&!Gr({state:e},{sectionId:o,lineId:u.id}))return Ne({state:e}),e;if(s&&!s.rollback&&Ve(s,{compatibilityAnchor:!0}),s){let h=Ge(s),g=h.read?.lineId;g&&o&&Ke(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:u.id}}Jr(e,{sectionId:o,lineId:u.id}),zr(e);let{activeInteraction:d}=Bt(e,{sectionId:o,lineId:u.id}),p=e.global.nextLineConfig;p?.auto?.enabled&&!d&&p.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}})}else e.global.autoMode&<({state:e}),e.global.skipMode&&Ne({state:e});return e},Ol=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=be({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ie(e,"autoForwardDelay")}});let r=de({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&Ke(e,{sectionId:n,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},$l=({state:e},t)=>ti(e,{sectionId:t?.sectionId,screen:t?.screen}),Ll=({state:e})=>{if(e.global.dialogueUIHidden)return Ut({state:e}),e;if(be({state:e}))return e;let t=de({state:e})?.pointer,r=t?.sectionId,n=X({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],a=i.findIndex(c=>c.id===t?.lineId)+1;if(a<i.length){let c=i[a],l=!Ie(e,"skipUnseenText");if(e.global.skipMode&&l&&!Gr({state:e},{sectionId:r,lineId:c.id}))return Ne({state:e}),e;if(o&&!o.rollback&&Ve(o,{compatibilityAnchor:!0}),o){let f=Ge(o),d=f.read?.lineId;d&&r&&Ke(e,{sectionId:r,lineId:d}),f.read={sectionId:r,lineId:c.id}}Jr(e,{sectionId:r,lineId:c.id}),zr(e);let{activeInteraction:u}=Bt(e,{sectionId:r,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},rn=(e,t={})=>{let r=ct({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},kl=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let r=e.projectData.resources?.variables?.[t.variableId],n=r?.scope,o=r?.type;if(xe(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return St(n,t.variableId),_t(o,"set",t.variableId),{variableConfig:r,scope:n}},Pl=(e,t)=>({id:e.id,key:e.key,valid:!0,values:T(t),fields:T(e.fields),fieldList:T(e.fieldList)}),Tl=({state:e},t={})=>{let r=rn(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=No(e,r.key),i=Vt(t.value),s=r.fields[n],a=qr(s,i);return o.values[n]=i,o.touched[n]=!0,a?o.errors[n]=a:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},Dl=({state:e},t={})=>{let r=rn(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=No(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([f,d])=>{let p=Object.prototype.hasOwnProperty.call(n.values,f)?n.values[f]:d.value,h=qr(d,p);n.touched[f]=!0,h&&(i[f]=h),o[f]=Do(d,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:T(i),form:{id:r.id,key:r.key,values:T(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let a=!1,c=[],l=[];Object.entries(r.fields).forEach(([f,d])=>{let{scope:p}=kl(e,d),h=p==="context"?s.variables:e.global.variables,g=o[f];h[d.variableId]=Rt(h[d.variableId],"set",g),p==="context"&&(a=!0,l.push({variableId:d.variableId,op:"set",value:g})),(p==="device"||p==="account")&&c.push({scope:p,path:`variables.${d.variableId}`,op:"set",value:T(h[d.variableId])})}),a&&ye(e,"updateVariable",{id:"submitForm",operations:l}),tn(e,c);let u=Pl(r,o);return delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},Nl=({state:e},t={})=>{let r=rn(e,t);return r?(delete e.global.formDrafts?.[r.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:r.id,key:r.key,values:T(r.values),fields:T(r.fields),fieldList:T(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},Vl=({state:e},t)=>{let{id:r,operations:n=[]}=t;if(!r)throw new Error("updateVariable requires an id field");if(typeof r!="string"||!/^[a-zA-Z0-9]+$/.test(r))throw new Error(`updateVariable id must be alphanumeric, got: "${r}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],a=[];return n.forEach(({variableId:c,op:l,value:u,roundTo:f})=>{let d=e.projectData.resources?.variables?.[c],p=d?.scope,h=d?.type;if(xe(d))throw new Error(`Cannot update computed variable: ${c}`);if(d?.readonly===!0)throw new Error(`Cannot update readonly variable: ${c}`);St(p,c),_t(h,l,c),mr(h,l,u,c,{roundTo:f});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:c,op:l,value:u};f!==void 0&&(y.roundTo=f),a.push(y)}g[c]=Rt(g[c],l,u,{roundTo:f}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${c}`,op:"set",value:T(g[c])})}),i&&ye(e,"updateVariable",{id:r,operations:a}),tn(e,s),e.global.pendingEffects.push({name:"render"}),e},jl=e=>(t,r)=>e({state:t},r),Ml=e=>({variables:Ct({variables:{...e.global?.variables??{},...Hr(e)?.variables??{}},runtime:ze(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:ze(e)}),Fl=e=>{if(!P(e))throw new Error("conditional action payload must be an object");if(!Array.isArray(e.branches))throw new Error("conditional action requires branches array");if(e.branches.length===0)throw new Error("conditional action requires at least one branch")},Bl=(e,t,r)=>{if(!P(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!P(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==r-1)throw new Error("conditional else branch must be the last branch")},Ul=(e,t)=>{Fl(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(Bl(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!rt(n.when,Ml(e)))){Object.entries(n.actions).forEach(([i,s])=>{ii(e,i,s)});return}}},zl={conditional:{replayLine:Ul},updateVariable:{recordSources:[Yr],replayLine:So,replayRecorded:So,persistInSaveSlot:!0},setNextLineConfig:{replayLine:jl(oi)}},zt=e=>zl[e]??null,Wl=e=>zt(e)?.persistInSaveSlot===!0,ql=(e,t)=>{let r=zt(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},Yl=(e,t,r)=>{zt(t)?.replayRecorded?.(e,r)},ii=(e,t,r)=>{zt(t)?.replayLine?.(e,r)},si=({state:e},t)=>{let{offset:r}=t;if(r===void 0||typeof r!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let n=e.contexts[e.contexts.length-1];if(!n)return null;let o=n.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+r;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},ai=({state:e})=>si({state:e},{offset:-1})!==null,Kl=({state:e},t)=>{let{offset:r=-1}=t;if(r>=0)throw new Error("rollbackByOffset requires a negative offset");let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let o=Ve(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:zo(e,i)},Hl=({state:e},t)=>{let{sectionId:r,lineId:n}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=Ve(o,{compatibilityAnchor:!o.rollback}),a=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===r&&c.lineId===n);if(a===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return a===i.currentIndex?e:zo(e,a)},ci=e=>{let t=$c(e);return Un(t,{selectPendingEffects:kc,selectSkipMode:Wo,selectAutoMode:Pc,selectIsChoiceVisible:Ho,selectIsFormVisible:Dc,selectActiveInteraction:be,selectActiveForm:ct,selectDialogueUIHidden:qo,selectDialogueHistory:Yo,selectConfirmDialog:Tc,selectIsLineAccountViewed:Gr,selectIsResourceAccountViewed:jc,selectNextLineConfig:Mc,selectSystemState:Fc,selectSaveSlotMap:Jo,selectSaveSlots:Yc,selectSaveSlot:Bc,selectRuntime:Xr,selectRuntimeValue:Uc,selectAllVariables:Qr,selectCurrentPointer:de,selectSection:X,selectCurrentLine:Zr,selectPresentationState:Go,selectPresentationChanges:zc,selectSectionLineChanges:qc,selectSaveSlotPage:en,selectCurrentPageSlots:Kc,selectRenderState:Jc,selectOverlayStack:Lc,selectLineIdByOffset:si,selectCanRollback:ai,startAutoMode:Qo,stopAutoMode:lt,toggleAutoMode:nl,startSkipMode:Zo,stopSkipMode:Ne,toggleSkipMode:ol,showDialogueUI:Ut,hideDialogueUI:ei,toggleDialogueUI:il,setDialogueTextSpeed:sl,setAutoForwardDelay:al,setSkipUnseenText:cl,setSkipTransitionsAndAnimations:ll,setSoundVolume:ul,setMusicVolume:fl,setMuteAll:dl,setSaveLoadPagination:pl,incrementSaveLoadPagination:hl,decrementSaveLoadPagination:ml,setMenuPage:gl,setMenuEntryPoint:yl,showConfirmDialog:Gc,hideConfirmDialog:Xc,resetStoryAtSection:Al,clearPendingEffects:bl,appendPendingEffect:Il,beginRollbackActionBatch:Sc,endRollbackActionBatch:_c,addViewedLine:vl,addViewedResource:El,setNextLineConfig:oi,saveSlot:xl,loadSlot:Cl,updateProjectData:Sl,sectionTransition:$l,jumpToLine:_l,nextLine:Rl,markLineCompleted:Ol,rollbackToLine:Hl,rollbackByOffset:Kl,pushOverlay:Qc,popOverlay:Zc,replaceLastOverlay:el,clearOverlays:tl,updateFormField:Tl,submitForm:Dl,cancelForm:Nl,updateVariable:Vl,nextLineFromSystem:Ll},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var Jl="route-engine",Gl="projectPersistence";var ui=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),J=e=>Object.prototype.toString.call(e)==="[object Object]",li="variables.",Xl=(e={})=>{let t=J(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!J(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lineId=="string"?{lineId:r.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!J(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Ql=(e={})=>{let t=J(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!J(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lastLineId=="string"?{lastLineId:r.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!J(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Zl=(e,t)=>{let r=Ql(e),n=Xl(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let a=o.find(c=>c.sectionId===s.sectionId);if(!a){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(a.lastLineId!==void 0){if(s.lineId===void 0){delete a.lastLineId;return}a.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(c=>c.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},fi=(e={})=>{let t=J(e)?e:{};return{saveSlots:J(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:J(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:J(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:J(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:J(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},eu=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!J(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(li)?t.path.slice(li.length):null;if(n!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(n.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${r}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:n}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${r}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${r}].`)})},tu=(e,t)=>{let r={};return eu(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=Zl(r.accountViewedRegistry??e.accountViewedRegistry,n.value);return}let o=n.scope==="device"?"globalDeviceVariables":"globalAccountVariables";r[o]={...e[o],...r[o],[n.variableId]:n.value}}),r},nn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},ru=e=>{let t=nn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},nu=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},ou=({indexedDB:e,databaseName:t,objectStoreName:r})=>new Promise((n,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(r)||s.createObjectStore(r,{keyPath:"namespace"})},i.onsuccess=()=>{n(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),iu=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let c=n.transaction(t,"readonly").objectStore(t).get(r);c.onsuccess=()=>{o(c.result??null)},c.onerror=()=>{i(c.error??new Error(`Failed to read persisted namespace "${r}" from IndexedDB.`))}})},ft=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let a=o.transaction(t,"readwrite"),c=a.objectStore(t),l=c.get(r),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 "${r}" before updating IndexedDB.`))},l.onsuccess=()=>{let p=fi(l.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...ui(),...p,...h},y=c.put(g);y.onerror=()=>{f(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},a.oncomplete=()=>{d()},a.onerror=()=>{f(a.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},a.onabort=()=>{f(a.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},su=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let s=n.transaction(t,"readwrite"),c=s.objectStore(t).delete(r),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 "${r}" from IndexedDB.`))},s.oncomplete=()=>{f()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},on=(e={})=>{let{indexedDB:t,databaseName:r=Jl,objectStoreName:n=Gl,namespace:o}=e,i=nu(t),s=ru(o),a=ou({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let c=await iu({databasePromise:a,objectStoreName:n,namespace:s});return{...ui(),...fi(c)}},clear:async()=>su({databasePromise:a,objectStoreName:n,namespace:s}),saveSlots:async c=>ft({databasePromise:a,objectStoreName:n,namespace:s,patch:{saveSlots:J(c)?c:{}}}),saveGlobalDeviceVariables:async c=>ft({databasePromise:a,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:J(c)?c:{}}}),saveGlobalAccountVariables:async c=>ft({databasePromise:a,objectStoreName:n,namespace:s,patch:{globalAccountVariables:J(c)?c:{}}}),saveGlobalRuntime:async c=>ft({databasePromise:a,objectStoreName:n,namespace:s,patch:{globalRuntime:J(c)?c:{}}}),applyScopedDataUpdates:async c=>ft({databasePromise:a,objectStoreName:n,namespace:s,patch:l=>tu(l,c)})}},au=on;var cu=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),lu=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),di="conditional",sn="form",uu=new Set(["submitForm","cancelForm"]),dt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function an(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:a}=e,c=(A=new Map,C=Date.now())=>new Map(Array.from(A.entries()).filter(([,_])=>C<_.expiresAt).map(([_,U])=>[_,{animation:structuredClone(U.animation),startedAt:U.startedAt,expiresAt:U.expiresAt}])),l=(A=new Map)=>Array.from(A.values()).map(C=>structuredClone(C.animation)),u=(A=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,C])=>A<C.expiresAt))},f=()=>{for(;t.selectPendingEffects().length>0;){let A=[...t.selectPendingEffects()];t.clearPendingEffects();try{a(A)}catch(C){throw t.clearPendingEffects(),A.forEach(_=>{t.appendPendingEffect(_)}),C}}},d=({initialState:A,namespace:C})=>{t=ci(A),r=0,n=nn(C),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),f()},p=()=>n,h=()=>t.selectPresentationState(),g=()=>t.selectPresentationChanges(),y=A=>t.selectSectionLineChanges(A),b=(A={})=>{r+=1;let C=Date.now();u(C);let _=i.size>0,U=c(o,C),z=_?c(i,C):new Map,he={...t.selectRenderState({activePersistentAnimations:l(U),restoredPersistentAnimations:l(z)}),id:`render-${r}`};return s.set(he.id,{builtAt:C,persistentAnimationSessions:new Map([...z.entries(),...U.entries()]),usedRestoredPersistentAnimationSessions:_}),he},w=(A={})=>b(A),E=(A={})=>b(A),I=A=>{let C=typeof A?.id=="string"&&A.id.length>0?A.id:null,_=C?s.get(C):null;C&&s.delete(C);let U=new Map;fo(A?.animations).forEach(z=>{let oe=kt(z);if(!oe)return;let he=_?.persistentAnimationSessions?.get(oe)??o.get(oe),pt=Math.max(0,ho(z)),un=he?.startedAt??_?.builtAt??Date.now();U.set(oe,{animation:structuredClone(z),startedAt:un,expiresAt:un+pt})}),o=U,_?.usedRestoredPersistentAnimationSessions&&(i=new Map)},N=()=>t.selectSystemState(),L=()=>t.selectSaveSlotMap(),V=A=>t.selectSaveSlot(A),M=A=>t.selectSaveSlotPage(A),O=()=>t.selectSkipMode(),D=()=>t.selectAutoMode(),F=()=>t.selectRuntime(),k=()=>t.selectIsChoiceVisible(),W=()=>t.selectIsFormVisible(),x=()=>t.selectActiveInteraction(),S=(A,C,_={})=>A!=="nextLine"||!dt(C)?C:_.bypassChoice===!0?{...C,bypassChoice:!0}:_.interactionSource===sn?{...C,_interactionSource:sn}:C,B=(A,C)=>{if(!t[A])return;cu.has(A)&&(lu.has(A)?i=c(o):i=new Map,o=new Map);let _=t[A](C);return f(),_},K=(A,C,_,U={})=>{if(A===di){let z=j(_),oe=br({[A]:C},z);Me(oe[A],_,U);return}B(A,C)},q=(A,C)=>{K(A,C)},j=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:C,..._}=A,U=t.selectAllVariables?t.selectAllVariables():void 0;return{..._,_event:C,variables:U,runtime:t.selectRuntime?t.selectRuntime():{}}},pe=A=>{if(!dt(A))throw new Error("conditional action payload must be an object");if(!Array.isArray(A.branches))throw new Error("conditional action requires branches array");if(A.branches.length===0)throw new Error("conditional action requires at least one branch")},Z=(A,C,_)=>{if(!dt(A))throw new Error(`conditional branch at index ${C} must be an object`);if(!dt(A.actions))throw new Error(`conditional branch at index ${C} requires actions object`);if(!Object.prototype.hasOwnProperty.call(A,"when")&&C!==_-1)throw new Error("conditional else branch must be the last branch")},Me=(A,C,_)=>{pe(A);for(let U=0;U<A.branches.length;U+=1){let z=A.branches[U];Z(z,U,A.branches.length);let oe=j(C);if(!(Object.prototype.hasOwnProperty.call(z,"when")&&!rt(z.when,oe))){qt(z.actions,C,_);return}}},mi=(A,C)=>({...A??{},_form:C}),gi=(A,C,_,U)=>{let z=B(A,C),oe=z?.submitted===!0&&z.valid===!0,he=z?.cancelled===!0;!oe&&!he||dt(C.actions)&&qt(C.actions,mi(_,z.form),{...U,interactionSource:sn})},yi=(A,C,_,U)=>{let z=j(_),he=br({[A]:C},z)[A];if(A===di){Me(he,_,U);return}let pt=S(A,he,U);if(uu.has(A)){gi(A,pt,_,U);return}B(A,pt)},qt=(A,C,_)=>{Object.entries(A).forEach(([U,z])=>{yi(U,z,C,_)})},ln=(A,C,_={})=>{t.beginRollbackActionBatch({source:_.rollbackSource});try{qt(A,C,_)}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:K,handleInternalAction:q,handleActions:ln,selectRenderState:w,prepareRenderState:E,commitRenderState:I,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:N,selectSaveSlotMap:L,selectSaveSlot:V,selectSaveSlotPage:M,selectSaveSlots:L,selectRuntime:F,selectIsChoiceVisible:k,selectIsFormVisible:W,selectActiveInteraction:x,handleLineActions:()=>{let A=t.selectCurrentLine();return A?.actions?(ln(A.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var cn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},fu=80,hi=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},du=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&hi({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},pu=({engine:e,ticker:t,autoTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let a=n.delay??1e3;r.getElapsed()>=a&&(t.remove(i),r.setCallback(null),r.setElapsed(0),Wt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},hu=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},mu=({engine:e,ticker:t,skipTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let a=n?.delay??fu;r.getElapsed()>=a&&(r.setElapsed(0),Wt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},gu=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},yu=({engine:e,ticker:t,nextLineConfigTimerState:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let a=n.delay??1e3;r.getElapsed()>=a&&(r.setElapsed(0),Wt(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},bu=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Iu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},Au=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},wu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},vu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},Eu=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},pi={render:hi,saveSlots:Iu,saveGlobalDeviceVariables:Au,saveGlobalAccountVariables:wu,saveGlobalRuntime:vu,applyScopedDataUpdates:Eu,handleLineActions:du,startAutoNextTimer:pu,clearAutoNextTimer:hu,startSkipNextTimer:mu,clearSkipNextTimer:gu,nextLineConfigTimer:yu,clearNextLineConfigTimer:bu},xu=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Wt=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},Cu=(e=[])=>{let t=new Set,r=[];for(let n=e.length-1;n>=0;n-=1){let o=e[n];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!xu.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},Su=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:a})=>{let c=cn(),l=cn(),u=cn(),f=s??null,d=Promise.resolve(),p=null,h=null,g=!1,y=0,b=x=>{if(o){o(x);return}console.error("RouteEngine persistence write failed.",x)},w=()=>{if(f)return f;let x=e();return f=on({indexedDB:i,namespace:a??x?.getNamespace?.()}),f},E=x=>{d=d.catch(()=>{}).then(()=>{let S=w();return x(S)}).catch(S=>{b(S)})},I=x=>{let S=typeof x?.id=="string"&&x.id.length>0?x.id:null;y+=1,p=S,g=!1},N=()=>y,L=(x={})=>{if(x?.aborted===!0)return!1;let S=typeof x?.id=="string"&&x.id.length>0?x.id:null;return S?S!==p||S===h?!1:(h=S,!0):p!==null||g?!1:(g=!0,!0)},V=(x,S={})=>{if(x!=="renderComplete"||!L(S))return!1;let B=e();return Wt(B,"markLineCompleted",{}),!0},M=x=>typeof x?.selectActiveInteraction=="function"?x.selectActiveInteraction():typeof x?.selectIsChoiceVisible=="function"&&x.selectIsChoiceVisible()?{source:"choice"}:null,O=(x,S)=>!(!x||typeof x!="object"||Array.isArray(x)||x._interactionSource!==S?.source||S.source==="form"&&x._formKey&&x._formKey!==S.formKey||S.source==="form"&&x.formKey&&x.formKey!==S.formKey),D=(x={},S)=>{if(O(x,S))return!0;let B=x?.actions;return!B||typeof B!="object"||Array.isArray(B)?!1:Object.values(B).some(K=>O(K,S))},F=(x,S={})=>{if(!S?.actions)return!1;let B=M(x);return!B||B.source==="choice"?!1:!D(S,B)},k=({preprocessPayload:x,onEvent:S}={})=>async(B,K={})=>{let q=e();if(F(q,K))return S?.(B,K);let j=await x?.(B,K)??K;if(F(q,j))return S?.(B,j);if(V(B,j),j?.actions){let pe=j?._event?{_event:j._event}:j?.event?{_event:j.event}:void 0,Z;j?.bypassChoice===!0?Z={bypassChoice:!0}:j?._interactionSource&&(Z={interactionSource:j._interactionSource}),Z?q.handleActions(j.actions,pe,Z):q.handleActions(j.actions,pe)}return S?.(B,j)},W=x=>{let S=e(),B=Cu(x);B.forEach(q=>{if(!pi[q.name]&&!n)throw new Error(`Unhandled pending effect "${q.name}".`)});let K={engine:S,routeGraphics:t,ticker:r,autoTimer:c,skipTimer:l,nextLineConfigTimerState:u,trackRenderDispatch:I,getRenderDispatchCount:N,enqueuePersistenceWrite:E};for(let q of B){let j=pi[q.name];if(j){j(K,q.payload);continue}n(q,K)}};return W.handleRouteGraphicsEvent=V,W.createRouteGraphicsEventHandler=k,W},_u=Su;var Ru=(e,t={})=>{let{resources:r={}}=t;return Br(e,r)};var Yf=an;export{_u as createEffectsHandler,au as createIndexedDbPersistence,Yf as default,xs as resolveComputedVariables,Ru as resolveLayoutReferences};
|
package/package.json
CHANGED