route-engine-js 1.16.0 → 1.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/RouteEngine.js +1 -1
- package/package.json +1 -1
package/dist/RouteEngine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var wi=Object.defineProperty;var vi=(e,t)=>{for(var r in t)wi(e,r,{get:t[r],enumerable:!0})};var gn=Symbol.for("immer-nothing"),fn=Symbol.for("immer-draftable"),te=Symbol.for("immer-state");function ae(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Be=Object.getPrototypeOf;function re(e){return!!e&&!!e[te]}function $e(e){return e?yn(e)||Array.isArray(e)||!!e[fn]||!!e.constructor?.[fn]||It(e)||At(e):!1}var Ei=Object.prototype.constructor.toString();function yn(e){if(!e||typeof e!="object")return!1;let t=Be(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)===Ei}function mt(e,t){bt(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function bt(e){let t=e[te];return t?t.type_:Array.isArray(e)?1:It(e)?2:At(e)?3:0}function Ht(e,t){return bt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function bn(e,t,r){let n=bt(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function xi(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function It(e){return e instanceof Map}function At(e){return e instanceof Set}function Re(e){return e.copy_||e.base_}function Jt(e,t){if(It(e))return new Map(e);if(At(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],l=n[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(n[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(Be(e),n)}else{let n=Be(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function er(e,t=!1){return wt(e)||re(e)||!$e(e)||(bt(e)>1&&(e.set=e.add=e.clear=e.delete=Ci),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>er(n,!0))),e}function Ci(){ae(2)}function wt(e){return Object.isFrozen(e)}var Si={};function Le(e){let t=Si[e];return t||ae(0,e),t}var Qe;function In(){return Qe}function _i(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function dn(e,t){t&&(Le("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Gt(e){Xt(e),e.drafts_.forEach(Oi),e.drafts_=null}function Xt(e){e===Qe&&(Qe=e.parent_)}function pn(e){return Qe=_i(Qe,e)}function Oi(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),ae(4)),$e(e)&&(e=gt(t,e),t.parent_||yt(t,e)),t.patches_&&Le("Patches").generateReplacementPatches_(r[te].base_,e,t.patches_,t.inversePatches_)):e=gt(t,r,[]),Gt(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==gn?e:void 0}function gt(e,t,r){if(wt(t))return t;let n=t[te];if(!n)return mt(t,(o,i)=>mn(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return yt(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),mt(i,(l,c)=>mn(e,n,o,l,c,r,s)),yt(e,o,!1),r&&e.patches_&&Le("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function mn(e,t,r,n,o,i,s){if(re(o)){let l=i&&t&&t.type_!==3&&!Ht(t.assigned_,n)?i.concat(n):void 0,c=gt(e,o,l);if(bn(r,n,c),re(c))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if($e(o)&&!wt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;gt(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&yt(e,o)}}function yt(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&er(t,r)}function Ri(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=Ze);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return n.draft_=l,n.revoke_=s,l}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_||!$e(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(xi(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(){ae(11)},getPrototypeOf(e){return Be(e.base_)},setPrototypeOf(){ae(12)}},Ze={};mt(tr,(e,t)=>{Ze[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Ze.deleteProperty=function(e,t){return Ze.set.call(this,e,t,void 0)};Ze.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=Be(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=Be(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 Li=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,...a){return s.produce(c,u=>r.call(this,u,...a))}}typeof r!="function"&&ae(6),n!==void 0&&typeof n!="function"&&ae(7);let o;if($e(t)){let i=pn(this),s=Zt(t,void 0),l=!0;try{o=r(s),l=!1}finally{l?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=[];Le("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else ae(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,c=>t(c,...l));let n,o;return[this.produce(t,r,(s,l)=>{n=s,o=l}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){$e(e)||ae(8),re(e)&&(e=ke(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_)&&ae(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=Le("Patches").applyPatches_;return re(e)?n(e,t):this.produce(e,o=>n(o,t))}};function Zt(e,t){let r=It(e)?Le("MapSet").proxyMap_(e,t):At(e)?Le("MapSet").proxySet_(e,t):Ri(e,t);return(t?t.scope_:In()).drafts_.push(r),r}function ke(e){return re(e)||ae(10,e),wn(e)}function wn(e){if(!$e(e)||wt(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 mt(r,(n,o)=>{bn(r,n,wn(o))}),t&&(t.finalized_=!1),r}var ne=new Li,rr=ne.produce,Tu=ne.produceWithPatches.bind(ne),Du=ne.setAutoFreeze.bind(ne),Nu=ne.setUseStrictShallowCopy.bind(ne),Vu=ne.applyPatches.bind(ne),ju=ne.createDraft.bind(ne),Mu=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},O={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},Ue={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 ki=(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 Ti(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 On(e,t,r,n);case m.CONDITIONAL:return Ni(e,t,r,n);case m.LOOP:return Bi(e,t,r,n);case m.OBJECT:return zi(e,t,r,n);case m.ARRAY:return Wi(e,t,r,n);case m.PARTIAL:return qi(e,t,r,n);case m.PATH_REFERENCE:return Yi(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Cn=new Map,Pi=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 l=s.slice(1,-1);t.push({type:"property",value:l})}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="",l=0;for(let c=0;c<e.length;c++){let a=e[c];a==="["?(l++,s+=a):a==="]"?(l--,s+=a):a==="."&&l===0?s&&(i.push(s),s=""):s+=a}s&&i.push(s),n=[];for(let c of i){let a=Pi(c.trim());n.push(...a)}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},Ti=(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(l=>$(l,t,r,n));return i(...s)},ve=(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 On(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===O.AND||e.op===O.OR){let s=ve(e.left,t,r,n),l=ve(e.right,t,r,n);switch(e.op){case O.AND:return s&&l;case O.OR:return s||l}}let o=$(e.left,t,r,n),i=$(e.right,t,r,n);switch(e.op){case O.EQ:return o==i;case O.NEQ:return o!=i;case O.GT:return o>i;case O.LT:return o<i;case O.GTE:return o>=i;case O.LTE:return o<=i;case O.IN:return Array.isArray(i)?i.includes(o):!1;case O.ADD:if(typeof o!="number"||typeof i!="number")throw new Q(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case O.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}`)}},On=(e,t,r,n)=>{let o=e.op===Ue.NOT?ve(e.operand,t,r,n):$(e.operand,t,r,n);if(e.op===Ue.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Di=(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 l={};for(let c of s.properties){let a=c.parsedKey?$(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)l[a]=u.value;else if(u.type===m.VARIABLE)l[a]=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):"")}l[a]=f.join("")}else l[a]=$(u,t,r,n)}return l}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let c of s.properties){let a=c.parsedKey?$(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)l[a]=u.value;else if(u.type===m.VARIABLE)l[a]=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):"")}l[a]=f.join("")}else l[a]=$(u,t,r,n)}return l}}}return null},Ni=(e,t,r,n)=>{let o=Di(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||ve(s,t,r,n))return $(e.bodies[i],t,r,n)}return Rn},Vi=(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 l=[];for(let c=0;c<t.length;c++){let a=t[c];if(a[s]){let u={};for(let f of i.properties){let d=f.key,p=f.value;if(p.type===m.LITERAL)u[d]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)u[d]=a;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);u[d]=a[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(a!=null?String(a):"");else if(b.startsWith(n+".")){let w=b.substring(n.length+1),E=a[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}l.push(u)}}return l}}}return null},ji=(e,t)=>{let r=e.body,n=e.itemVar,o=Vi(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let l of r.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of r.properties){let c=l.key,a=l.value;if(a.type===m.LITERAL)i.push({key:c,type:"literal",value:a.value});else if(a.type===m.VARIABLE){let u=a.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(a.type===m.INTERPOLATION&&a.parts.length===1){let u=a.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 l=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let a=t[c];l[c]={id:a.id,title:a.title!=null?String(a.title):"",completed:a.completed}}else for(let c=0;c<t.length;c++){let a=t[c],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=a;else if(f.type==="prop")u[f.key]=a[f.prop];else if(f.type==="item_string")u[f.key]=a!=null?String(a):"";else if(f.type==="prop_string"){let d=a[f.prop];u[f.key]=d!=null?String(d):""}l[c]=u}return l}}return null},Mi=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let l=e.itemVar,c=e.indexVar;for(let a=0;a<o.length;a++){let u=o[a],f={},d={...n,[l]:u,...c&&{[c]:a}};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__,[l]:`${p}[${a}]`,...c&&{[c]:a}};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===l)f[g]=u;else if(b===c)f[g]=a;else if(b.startsWith(l+".")){let w=b.substring(l.length+1);!w.includes(".")&&!w.includes("[")?f[g]=u[w]:f[g]=Y(b,r,{...n,[l]:u,...c&&{[c]:a}})}else f[g]=Y(b,r,{...n,[l]:u,...c&&{[c]:a}})}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===l)I=u;else if(E===c)I=a;else if(E.startsWith(l+".")){let N=E.substring(l.length+1);!N.includes(".")&&!N.includes("[")?I=u[N]:I=Y(E,r,{...n,[l]:u,...c&&{[c]:a}})}else I=Y(E,r,{...n,[l]:u,...c&&{[c]:a}});b.push(I!=null?String(I):"")}else{let E={...n,[l]:u,...c&&{[c]:a}},I=$(w,t,r,E);b.push(I!=null?String(I):"")}f[g]=b.join("")}else{let b={...n,[l]:u,...c&&{[c]:a}};f[g]=$(y,t,r,b)}}i.push(f)}return i}return null},Fi=(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 l=s.properties[0],c=s.properties[1];if(l.key==="id"&&l.value.type===m.VARIABLE&&l.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===m.CONDITIONAL){let a=[];for(let u=0;u<t.length;u++){let f=t[u];if(f.visible){let d={id:f.id};f.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${f.name}`):(d.highlight=!1,d.message=f.name),a.push(d)}}return a}}}}return null},Bi=(e,t,r,n)=>{let o=$(e.iterable,t,r,n);if(!Array.isArray(o)){let a,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(", ");a=`${e.iterable.name}(${d})`}else a=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${a}`;throw En(f,o,u)}if(!e.indexVar){let a=Fi(e,o,e.itemVar);if(a!==null)return a}if(!e.indexVar){let a=ji(e,o);if(a!==null)return a}let i=Mi(e,t,r,n,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(n&&n.__paths__&&l){let a=l.split("."),u=a[0];u in n.__paths__&&(l=n.__paths__[u],a.length>1&&(l+="."+a.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(a=>a.type===m.OBJECT&&a.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let a=0;a<o.length;a++){let u=e.indexVar?{...n,[e.itemVar]:o[a],[e.indexVar]:a}:{...n,[e.itemVar]:o[a]};u.__paths__||(u.__paths__=n.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${a}]`},e.indexVar&&(u.__paths__[e.indexVar]=a);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},Ui=(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 l={},c={},a=!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{a=!1;break}if(!a)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{a=!1;break}if(!a)break;p[g]=b.join("")}else{a=!1;break}}if(!a)break;c[f]=p}else{a=!1;break}}if(a)return l[i]=c,l}}return null},zi=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!ve(e.whenCondition,o,r,n))return;let i=Ui(e,t,r,n);if(i!==null)return i;if(e.fast){let a={};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)a[f]=d.value;else if(d.type===m.VARIABLE)a[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):"")}a[f]=p.join("")}else a[f]=$(d,t,r,n)}return a}let s={},l=null,c=!1;for(let a of e.properties)if(!a.key.startsWith("$if ")&&!a.key.match(/^\$if\s+\w+.*:?$/)&&!a.key.startsWith("$elif")&&!a.key.startsWith("$else")&&!a.key.startsWith("$for ")){c=!0;break}for(let a of e.properties)if(a.key.startsWith("$if ")||a.key.match(/^\$if\s+\w+.*:?$/)){let u=$(a.value,t,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(a.key.startsWith("$for ")){if(e.properties.length===1)return $(a.value,t,r,n)}else{let u=a.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[a.key]=d)}else{let d=$(a.value,t,r,n);d!==void 0&&(s[a.key]=d)}}else{let f=a.parsedKey?$(a.parsedKey,t,r,n):a.key,d=$(a.value,t,r,n);d!==void 0&&(s[f]=d)}}return s},Rn={},Wi=(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!==Rn&&s!==void 0&&o.push(s)}return o},qi=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},c=t.functions||t;if(s&&!ve(s,c,r,n))return;if(!l[o])throw new Q(`Partial '${o}' is not defined`);let a=n._partialStack||[];if(a.includes(o))throw new Q(`Circular partial reference detected: ${o}`);let u=l[o],f=r,d={...n,_partialStack:[...a,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)},Yi=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],l=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(l.length>0)throw new Q(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return l.length>0&&(c+="."+l.join(".")),c};var or=ki;var Ki=/\$\{([^}]*)\}/g,Hi=/#\{([^}]*)\}/g,Ln=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=Ji(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},Ji=(e,t={})=>e.trim()?Gi(e).map(n=>Xi(n.trim(),t)):[],Gi=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],c=s>0?e[s-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,r+=l):o&&l===i&&c!=="\\"?(o=!1,i="",r+=l):!o&&l==="("?(n++,r+=l):!o&&l===")"?(n--,r+=l):!o&&l===","&&n===0?(t.push(r),r=""):r+=l}return r&&t.push(r),t},Xi=(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:l,type:c}of o){let a=0;for(;a<n.length;){let u=Pe(n.substring(a),l);if(u===-1)break;let f=a+u;f>i&&(i=f,s={op:l,type:c}),a=f+l.length}}if(i!==-1)try{return H(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},kn=/^\w+\(.*\)$/,Qi=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Zi=e=>{if(!(!e||e.trim()===""||kn.test(e))&&Qi.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}},et=(e,t={})=>{let r=e.trim();Zi(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,(a,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\(#\{[^}]*\})/g,(a,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(Ki)],i=[...r.matchAll(Hi)],s=[...o.map(a=>({match:a,type:"variable"})),...i.map(a=>({match:a,type:"pathref"}))].sort((a,u)=>a.match.index-u.match.index);if(s.length===0){let a=r;for(let u=0;u<n.length;u++)a=a.replace(`__ESCAPED_${u}__`,n[u]);return{type:m.LITERAL,value:a}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:a,type:u}=s[0];try{return u==="variable"?et(a[1],t):$n(a[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw f}}let l=[],c=0;for(let{match:a,type:u}of s){let[f,d]=a,p=a.index;if(p>c){let h=r.substring(c,p);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&l.push(h)}try{let h;u==="variable"?h=et(d.trim(),t):h=$n(d.trim()),l.push(h)}catch(h){if(h.message==="Invalid array index syntax")l.push(f);else throw h}c=p+f.length}if(c<r.length){let a=r.substring(c);for(let u=0;u<n.length;u++)a=a.replace(`__ESCAPED_${u}__`,n[u]);a&&l.push(a)}return{type:m.INTERPOLATION,parts:l}};var cr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Dn=e=>Object.keys(e),G=e=>e.join("."),Ee=(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)}'`)},xe=(e,t)=>typeof e=="string"?ir(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?ts(e,t):rs(e,t):{type:m.LITERAL,value:e},es=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}},ts=(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=es(i),a=Object.keys(c);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let u=Tn(a[0],c[a[0]],t,!0);r.push(u),n=!0;continue}}catch(c){throw c instanceof v?c:new v(c.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let c=Tn(l[0],i[l[0]],t);r.push(c),n=!0;continue}}let s=xe(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}},rs=(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"],a=[];for(let[b]of i)for(let w of c)if(b===w||b.startsWith(w+" ")||b.startsWith(w+"#")){a.push(w);break}if(a.length>0)throw new v(`Cannot use $partial with ${a.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...d}=e,p={},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=xe(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,a]of i)if(c==="$when"){if(o!==null)throw new v("Multiple '$when' directives on the same object are not allowed");if(a==null)throw new v("Missing condition expression after '$when'");o=Pn(a,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,a]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new v("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=ns(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=xe(a,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 l={type:m.OBJECT,properties:r,fast:!n};return o&&(l.whenCondition=o),l},ns=(e,t,r={})=>{let n=[],o=[],i=t,[s,l]=e[i],c=null,a;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=f[1],a=f[2];else throw new v(`Invalid conditional syntax: ${s}`)}else a=s.substring(4),a.endsWith(":")&&(a=a.slice(0,-1).trim());nr(a);let u=H(a,r);for(n.push(u),o.push(xe(l,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(xe(d,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:c},nextIndex:i}},sr={eq:O.EQ,neq:O.NEQ,gt:O.GT,gte:O.GTE,lt:O.LT,lte:O.LTE,in:O.IN,add:O.ADD,sub:O.SUBTRACT},ar={all:O.AND,any:O.OR},os=new Set(["var","literal","call","not",...Object.keys(sr),...Object.keys(ar)]),is=(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},ss=(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,l)=>ge(s,n,[...o,l])).reduce((s,l)=>({type:m.BINARY,op:r,left:s,right:l}))},as=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],Ee(e,new Set(["call","args"]),r);else if(cr(e.call))n=e.call.name,o=e.call.args??[],Ee(e,new Set(["call"]),r),Ee(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)=>ge(i,t,[...r,"args",s]))}},ge=(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=>os.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(Ee(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 Ee(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return as(e,t,r);if(i==="not")return Ee(e,new Set(["not"]),r),{type:m.UNARY,op:Ue.NOT,operand:ge(e.not,t,[...r,"not"])};if(i in ar)return Ee(e,new Set([i]),r),ss(e[i],i,ar[i],t,[...r,i]);if(i in sr){Ee(e,new Set([i]),r);let s=is(e[i],i,[...r,i]);return{type:m.BINARY,op:sr[i],left:ge(s[0],t,[...r,i,0]),right:ge(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)?ge(e,t):{type:m.LITERAL,value:e}},H=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let a=e.slice(1,-1),u=0,f=!0;for(let d=0;d<a.length;d++)if(a[d]==="("?u++:a[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return H(a,t)}let r=Pe(e,"||");if(r!==-1)return{type:m.BINARY,op:O.OR,left:H(e.substring(0,r).trim(),t),right:H(e.substring(r+2).trim(),t)};let n=Pe(e,"&&");if(n!==-1)return{type:m.BINARY,op:O.AND,left:H(e.substring(0,n).trim(),t),right:H(e.substring(n+2).trim(),t)};let o=[{op:">=",type:O.GTE},{op:"<=",type:O.LTE},{op:"==",type:O.EQ},{op:"!=",type:O.NEQ},{op:">",type:O.GT},{op:"<",type:O.LT},{op:" in ",type:O.IN}];for(let{op:a,type:u}of o){let f=Pe(e,a);if(f!==-1)return{type:m.BINARY,op:u,left:H(e.substring(0,f).trim(),t),right:H(e.substring(f+a.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:O.ADD},{op:" - ",type:O.SUBTRACT}];for(let{op:a,type:u}of l){let f=0;for(;f<e.length;){let d=Pe(e.substring(f),a);if(d===-1)break;let p=f+d;p>i&&(i=p,s={op:a,type:u}),f=p+a.length}}if(i!==-1&&s)return{type: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 a of c)if(Pe(e,a)!==-1)throw new v(`Arithmetic operations are not allowed in conditionals: "${a}"`);return e.startsWith("!")?{type:m.UNARY,op:Ue.NOT,operand:H(e.substring(1).trim(),t)}:Nn(e,t)},Pe=(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},cs=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 et(r,t);let o=cs(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return et(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},ls=(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],l=i[2].trim();ls(l,n);let c=l.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let y=n?"$each":"$for";throw new v(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${l}')`)}let a=c[1].trim(),u=c[2].trim(),f,d=null;if(a.includes(",")){let y=a.split(",").map(b=>b.trim());if(y.length!==2)throw new v(`Invalid loop variables: ${a}. Expected format: "item" or "item, index"`);f=y[0],d=y[1]}else f=a;let p=["this","undefined","null","true","false"];if(p.includes(f))throw new v(`Reserved variable name: ${f}`);if(d&&p.includes(d))throw new v(`Reserved variable name: ${d}`);let h=Nn(u,r),g=xe(t,r);return{type:m.LOOP,itemVar:f,indexVar:d,iterable:h,body:g,flatten:s!=="nested"}};var us=(e,t={})=>{let{functions:r={}}=t;return xe(e,r)},vt=us;var tt={};vi(tt,{now:()=>fs});var fs=()=>Date.now();var ds=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...tt,...n},s=vt(e,{functions:i}),l={};for(let[c,a]of Object.entries(o))l[c]=vt(a,{functions:i});return or(s,t,{functions:i,partials:l})},ee=ds;var ps=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",hs=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,ms=(e,t)=>{if(ps(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new v("Empty condition expression");return H(e,t)}return ge(e,t)},gs=(e,t={},r={})=>{let n=hs(r),o={...tt,...n},i=ms(e,o);return!!ve(i,{functions:o,partials:{}},t,{})},lr=gs;var nt=(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:l=c=>c}=r;for(let[c,a]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>a(s(n),...u):i[c]=(...u)=>{let f;return n=rr(n,p=>{let h=a(l(p),...u);f=h!==void 0&&!re(h)?h:void 0}),f});return{...o,...i}},Ct=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return rr(n,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var ys=(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{}}},le=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),rt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),zn=e=>{let t=re(e)?ke(e):e;return structuredClone(t)},Ce=e=>le(e,"computed"),ze=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Ce(t[r]))),bs=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},Is=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=bs(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)},As=(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`)},ws=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},ce=(e,t,r,n)=>(As(e,t,n),t.map(o=>xt(o,r))),se=(e,t,r,n)=>{let o=ce(e,t,r,n);return o.forEach(i=>ws(e,i)),o},vs=(e,t,r)=>{switch(e){case"var":return Is(t,r);case"add":{let[n,o]=se(e,t,r,2);return n+o}case"sub":{let[n,o]=se(e,t,r,2);return n-o}case"mul":{let[n,o]=se(e,t,r,2);return n*o}case"div":{let[n,o]=se(e,t,r,2);return n/o}case"mod":{let[n,o]=se(e,t,r,2);return n%o}case"neg":{let[n]=se(e,t,r,1);return-n}case"round":{let[n]=se(e,t,r,1);return Math.round(n)}case"floor":{let[n]=se(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=se(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=se(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=se(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=se(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=ce(e,t,r,2);return n==o}case"neq":{let[n,o]=ce(e,t,r,2);return n!=o}case"gt":{let[n,o]=ce(e,t,r,2);return n>o}case"gte":{let[n,o]=ce(e,t,r,2);return n>=o}case"lt":{let[n,o]=ce(e,t,r,2);return n<o}case"lte":{let[n,o]=ce(e,t,r,2);return n<=o}case"in":{let[n,o]=ce(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return Vn(e,t),t.every(n=>!!xt(n,r));case"or":case"any":return Vn(e,t),t.some(n=>!!xt(n,r));case"not":{let[n]=ce(e,t,r,1);return!n}case"length":{let[n]=ce(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:rt(n)?Object.keys(n).length:0}case"includes":{let[n,o]=ce(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}`)}},xt=(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 vs(n,o,t)},Es=(e,t={})=>nt(e,{variables:t.variables,runtime:t.runtime}),xs=(e,t)=>{if(!rt(e))throw new Error(`${t} must be an object`);let r=le(e,"expr"),n=le(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},fr=(e,t,r)=>(xs(e,t),le(e,"value")?zn(e.value):xt(e.expr,r)),Cs=(e,t={},r="unknown")=>{if(!rt(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=le(e,"expr"),o=le(e,"value");if(le(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(!rt(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let l=e.branches[s];if(!rt(l))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!le(l,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(Es(l.when,t))return fr(l,`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)},Ss=(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}`)}},St=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=ze(e,r),i=Object.entries(r).filter(([,f])=>Ce(f)).map(([f])=>f),s={},l=[],c=f=>{if(le(s,f))return s[f];let d=r[f];if(!Ce(d))return o[f];let p=l.indexOf(f);if(p>=0){let h=[...l.slice(p),f].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}l.push(f);try{let h=Cs(d.computed,u,f);return Ss(f,d.type,h),s[f]=h,h}finally{l.pop()}},a=new Proxy({},{get:(f,d)=>{if(typeof d=="string")return c(d)},has:(f,d)=>typeof d=="string"&&(le(o,d)||i.includes(d)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(f,d)=>{if(!(typeof d!="string"||!le(o,d)&&!i.includes(d)))return{enumerable:!0,configurable:!0}}}),u={variables:a,runtime:t,resolveVariable:c};return n?(i.forEach(f=>{c(f)}),{...o,...s}):a},_s=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>St({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(Ce(o))return;let i=ys(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},_t=(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(", ")}`)},Ot=(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(", ")}`)},Os=2,jn=12,Wn=(e=Os)=>{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},Rs=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},Et=e=>typeof e=="number"&&Number.isFinite(e),mr=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!Et(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!Et(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!Et(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,l,c)=>{let a=s??l;if(!Et(a))throw new Error(`Operation "${t}" requires ${c} to be a number.`);return a},i=s=>{let l=o(s,void 0,"value");if(l===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return l};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return Rs(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 l=i.character?.sprite;return l&&Object.keys(l).length>0&&(s.sprite=l),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,Ls=(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=l=>{let c=e[l],a=t[l];a&&!c?r[l]={changeType:"add",data:a}:c&&!a?n.includes(l)||(r[l]={changeType:"delete",data:c}):c&&a&&JSON.stringify(c)!==JSON.stringify(a)&&(r[l]={changeType:"update",data:a})},i=Ls(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(l=>{let c={...l};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},ks=(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},Ps=(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=ks(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},Ts={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?Ts[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])])):Ps(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 ue=e=>structuredClone(re(e)?ke(e):e),ot=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:ue(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=>ue(n)).filter(n=>t(n)||n.animations);return{hasValidItems:r.length>0,processedItems:r}},oe=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Kn=e=>e?.animations?.playback?.continuity==="persistent",ye=(e,t)=>oe(e??{},t)&&e[t]!==void 0,Ds=e=>{if(e){if(e.character&&oe(e.character,"name"))return e.character.name;if(oe(e,"characterName"))return e.characterName}},Gn=e=>!!e?.character&&oe(e.character,"sprite"),Ns=e=>{let t={},r=!1,n=Ds(e);return n!==void 0&&(t.name=n,r=!0),Gn(e)&&(t.sprite=ue(e.character.sprite),r=!0),r?t:void 0},Hn=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Vs=({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=>ue(o)):delete e.initialRevealedContent,e.content=[...n,...t]},js=()=>({}),Ms=(e,t)=>{if(t.background){let r=ye(t.background,"resourceId"),n=ye(t.background,"colorId"),o=ye(t.background,"opacity"),i=ye(t.background,"blur"),{animationsOnly:s,state:l}=ot(t.background,u=>ye(u,"resourceId")||ye(u,"colorId")||ye(u,"opacity")||ye(u,"blur"));if(s){e.background=e.background?{...ue(e.background),...l}:l;return}if(!r&&!n&&!o&&!i){delete e.background;return}let c=e.background,a=ue(t.background);if(!r&&c?.resourceId&&(a.resourceId=c.resourceId,!oe(a,"transformId")&&c.transformId&&(a.transformId=c.transformId)),!n&&c?.colorId&&(a.colorId=c.colorId),!o&&ye(c,"opacity")&&(a.opacity=c.opacity),!i&&ye(c,"blur")&&(a.blur=ue(c.blur)),oe(a,"resourceId")&&a.resourceId===void 0&&delete a.resourceId,oe(a,"colorId")&&a.colorId===void 0&&delete a.colorId,oe(a,"animations")&&a.animations===void 0&&delete a.animations,oe(a,"opacity")&&a.opacity===void 0&&delete a.opacity,oe(a,"blur")&&a.blur===void 0&&delete a.blur,!a.resourceId&&!a.colorId){delete e.background;return}c?.resourceId===a.resourceId&&c?.transformId===a.transformId&&!oe(a,"animations")&&Kn(c)&&(a.animations=ue(c.animations)),e.background=a}else e.background?.animations&&!Kn(e.background)&&(e.background.animations={})},Fs=(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:a,state:u}=ot(t.dialogue.ui,f=>!!f.resourceId);a?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&&Vs({dialogueState:e.dialogue,content:t.dialogue.content,append:n});let o=oe(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=oe(t.dialogue,"characterId"),s=Ns(t.dialogue),l=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,l?e.dialogue.character=!i&&o&&e.dialogue.character?{...ue(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 a={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(a.character=ue(e.dialogue.character)),e.dialogue.lines.push(a)}},Bs=(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},Us=(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}}},zs=(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))},Ws=(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},qs=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Ys=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=ot(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},Ks=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=ot(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},Hs=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=ot(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=ue(t.form)}else e.form&&delete e.form},Js=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},Gs=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},Xs=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},Te=e=>Ct(js,[Xs,Ms,Bs,Us,zs,Fs,Ws,qs,Ys,Ks,Hs,Js,Gs])(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"}}),De=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),it=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"]),Zs=(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]}},We=e=>Object.fromEntries(Object.entries(Qs).map(([t,r])=>{let n=Zs(e,r.source),o=n!==void 0?n:De[t]??it[t];return[t,o]})),Ae=(e,t)=>We(e)[t],Qn=(e={})=>Object.fromEntries(Ir.map(t=>[t,e[t]??De[t]]));var Se={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:qn},ea=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,ta=(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),l=ea.exec(s);if(l){let[,c,a,u]=l,f=ta(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((p,h)=>{let g={...t,[c]:p};a&&(g[a]=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".`)},ra=({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},na=(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},oa=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},ia=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},fo=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),po=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))},ho=(e=[])=>e.filter(t=>po(t)).map(t=>structuredClone(t)),mo=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,mo(r)),0),go=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(wr(e.tween),wr(e.prev?.tween),wr(e.next?.tween),mo(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(!po(n))return!1;let o=kt(n);return o?r.has(o):!1})},fe=({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}),sa=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),aa=(e,t)=>{if(sa(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},ca=({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?ra({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},la=(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(la(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},Or=(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},ua=({content:e,path:t,variables:r})=>Or(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},fa=(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},da=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},Rr=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},pa=(e={})=>e.textStyles||{},ha=(e={})=>e.images||{},ma=(e={})=>e.colors||{},ga=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,st=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,Ye=(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"||!ga.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})`},ya=(e={},t)=>{let r=pa(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 l=e.colors?.[r.strokeColorId];if(!l)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let c=to(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=ro(l.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,st(r,o)));return e.textStyleId!==void 0&&(Ye(e.textStyleId,r,"textStyleId"),n.textStyle=ya(t,e.textStyleId)),n},Fr=(e={},t)=>{let r=ma(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return Mr(r.hex,`Color "${t}"`)},yo=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 ${yo(`${t}.fill`)} instead`)},ba=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>at(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]=at(i,t,st(r,o)));return e.colorId!==void 0&&(Ye(e.colorId,r,"colorId"),n.fill=Fr(t,e.colorId)),n},at=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>at(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 ${yo("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]=ba(i,t,st(r,o));continue}n[o]=at(i,t,st(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(Ye(e.colorId,r,"colorId"),n.fill=Fr(t,e.colorId)),n},xr=(e={},t)=>{let r=ha(e)?.[t];return r||null},bo=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 ${bo(`${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 ${bo(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,st(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){Ye(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&&(Ye(e.hoverImageId,r,"hoverImageId"),oo(n,"hover",xr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(Ye(e.clickImageId,r,"clickImageId"),oo(n,"click",xr(t,e.clickImageId)?.fileId??e.clickImageId)),n},Br=(e,t={},r="root")=>Lr(at($r(e,t,r),t,r),t,r),_e=Br,Ke=(e=[])=>e.find(t=>t.id==="story"),Ia="#000000",kr="bg-cg-background-color",Aa=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?Mr(r?.backgroundColor??Ia,"screen.backgroundColor"):Fr(e,t.colorId),Io=(e={})=>{if(fo(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},wa=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},io=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=Io(e),n=wa(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},va=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:kr,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:Aa({resources:e,background:t,screen:r})};if(n){let i=Io(t);i!==void 0&&(o.alpha=i)}return o},Ea=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.layouts?.[t]):!1,so=({resources:e={},resourceId:t,colorId:r})=>{let n=da(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:Rr({resourceId:t,kind:n})}:r!==void 0?{resourceId:kr,targetId:kr}:{resourceId:void 0,targetId:void 0}},Ao=100,Tt=Ao,wo=(e,t)=>e*t/Ao,xa=(e={},t=Tt)=>e?.muteAll?0:wo(t,e?.soundVolume??De.soundVolume),Ca=(e={},t=Tt)=>e?.muteAll?0:wo(t,e?.musicVolume??De.musicVolume),Sa=({item:e,index:t}={})=>`sfx:${t}:${e?.resourceId}`,de=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,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??l??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},E=La({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e}),I={variables:e,runtime:w,saveSlots:r,isChoiceVisible:c,isFormVisible:a,canRollback:u,confirmDialog:f,form:d,historyDialogue:p,characters:h};return E&&(I.dialogue=E,I.dialogueLines=E.lines),I},ao=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},_a=e=>Pt(e,t=>({...t,revealEffect:"none"})),Oa=e=>Pt(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,ao):ao;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),Oe=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?_a(e):r?Oa(e):e,vo=({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}}:{}}}}},Ra=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),co=(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:co(r.change,o),submit:co(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 Ra){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}},Eo=(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),La=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n}={})=>{if(!t&&!$a(e))return;let o=e.content===void 0?[{text:""}]:Or(e.content,"dialogue.content"),i=e.content===void 0?0:ua({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),s=(e.lines||[]).map((c,a)=>{let u=Or(c.content,`dialogue.lines[${a}].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}}),l=Nr({characterId:e.characterId,character:e.character,characters:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:l,content:o.map(c=>({...c,text:_r(c.text,{variables:n})})),initialRevealedCharacters:i,lines:s}},xo=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=ee(e,r,{functions:Se});return _e(Oe(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),lo=({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)}}})},ka=(e={},t={})=>{let r={};return lo({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),lo({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},we=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l})=>{if(!e)return[];let c=[],a=({instanceId:b,targetId:w})=>{let E=ca({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;aa(e,s);let p=oa(e),h=ia(e),g=t?.animations?.[p],y=na(g,{animationId:p,animationPath:s});if(y==="update")return f&&i?a({instanceId:`${l}-animation-update`,targetId:i}):u&&o&&a({instanceId:`${l}-animation-update`,targetId:o}),c;if(y==="transition"){let b=`${l}-animation-transition`,w=h?.continuity==="persistent"?b:`${l}-animation-in`;if(u&&f&&d)return a({instanceId:b,targetId:i}),c;u&&a({instanceId:`${l}-animation-out`,targetId:o}),f&&a({instanceId:w,targetId:i})}return c},Pa=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Ta=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:c,runtime:a,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:fo(n?.background??{},"animations"),k=E.find(K=>K.id==="story");if(!k)return e;let V=fa(o,t.background),M=r?.background?.resourceId,R=r?.background?.colorId,D=t.background.resourceId??(t.background.animations?M:void 0),F=t.background.colorId??(t.background.animations?R:void 0),L=Ea(o,D),W={...t.background,colorId:F};if((F!==void 0||L)&&k.children.push(va({resources:o,background:W,screen:i,includeOpacity:!L})),D){let{images:K={},videos:q={}}=o,j=K[D]||q[D];if(j){let he=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},Fe={id:Rr({resourceId:D,kind:he?"video":"sprite"}),type:he?"video":"sprite",x:Z.x,y:Z.y,src:j.fileId,width:j.width,height:j.height,...io(t.background,{includeDefaultAlpha:!0}),anchorX:Z.anchorX,anchorY:Z.anchorY,rotation:Z.rotation,scaleX:Z.scaleX,scaleY:Z.scaleY};he&&(Fe.loop=t.background.loop??!1,Fe.volume=j.volume??50),k.children.push(Fe)}}if(D){let{layouts:K={}}=o,q=K[D];if(q){let j={id:Rr({resourceId:D,kind:"container"}),type:"container",children:q.elements,...io(t.background)};V&&Object.assign(j,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...V});let he=ee(j,de({variables:c,runtime:a,saveSlots:w,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,characters:o.characters||{},skipTransitionsAndAnimations:l}),{functions:Se});k.children.push(_e(Oe(he,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:l}),o))}}let x=so({resources:o,resourceId:M,colorId:R}),S=so({resources:o,resourceId:D,colorId:F}),B=we({animationsDef:t.background.animations,resources:o,previousResourceId:x.resourceId,currentResourceId:S.resourceId,previousTargetId:x.targetId,currentTargetId:S.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});fe({animationInstances:B,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:N})&&I.push(...B)}return e},Da=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:c}=e;if(t.character&&n){let a=l.find(h=>h.id==="story");if(!a)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,k=E>=0?$t(w,E,p):void 0,V=we({animationsDef:g.animations,resources:n,previousResourceId:k,currentResourceId:N?$t(g,h,d):void 0,previousTargetId:k,currentTargetId:N?$t(g,h,d):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&I&&fe({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),R=n.transforms[y];if(!R){console.warn("Transform not found:",y);continue}let D={type:"container",id:M,x:g.x??R.x,y:g.y??R.y,anchorX:R.anchorX,anchorY:R.anchorY,rotation:R.rotation,scaleX:R.scaleX,scaleY:R.scaleY,children:[]};for(let F of b){let L=n.images[F.resourceId];if(!L){console.warn(`Image resource not found: ${F.resourceId}`);continue}D.children.push({type:"sprite",id:`${M}-${F.id}`,src:L.fileId,width:L.width,height:L.height,x:0,y:0})}a.children.push(D),fe({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...V)}}return e},Na=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:l,activePersistentAnimations:c,autoMode:a,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:R={},spritesheets:D={}}=n,F=D[I.resourceId];if(F){let L=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??L.x,y:I.y??L.y,width:I.width??F.width,height:I.height??F.height,alpha:I.alpha??1,anchorX:L.anchorX,anchorY:L.anchorY,rotation:L.rotation,scaleX:L.scaleX,scaleY:L.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 L=M[I.resourceId]||R[I.resourceId];if(L){let W=R[I.resourceId]!==void 0,x=vr(n,I),S={id:`visual-${I.id}`,type:W?"video":"sprite",src:L.fileId,width:L.width,height:L.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=L.loop??!1,S.volume=L.volume??50),w.children.push(S)}}}if(I.resourceId){let{layouts:M={}}=n,R=M[I.resourceId];if(R){let D=vr(n,I),F={id:`visual-${I.id}`,type:"container",children:structuredClone(R.elements),x:D.x,y:D.y,anchorX:D.anchorX,anchorY:D.anchorY,rotation:D.rotation,scaleX:D.scaleX,scaleY:D.scaleY},L=ee(F,de({variables:s,runtime:l,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:a,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i}),{functions:Se});w.children.push(_e(Oe(L,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),n))}}let k=(r?.visual?.items||[]).find(M=>M.id===I.id),V=we({animationsDef:I.animations,resources:n,previousResourceId:k?.resourceId,currentResourceId:I.resourceId,previousTargetId:k?.resourceId?`visual-${I.id}`:void 0,currentTargetId:I.resourceId?`visual-${I.id}`:void 0,animationPath:`visual.items[${I.id}].animations`,idPrefix:I.id});fe({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:c})&&b.push(...V)}}return e},qe="dialogue-character-sprite",uo=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,Va=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,c=Ke(e.elements);if(!c)return e;let a=t.dialogue?.character?.sprite,u=r?.dialogue?.character?.sprite,f=uo(a),d=uo(u),p=we({animationsDef:a?.animations,resources:n,previousResourceId:d?qe:void 0,currentResourceId:f?qe:void 0,previousTargetId:d?qe:void 0,currentTargetId:f?qe:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!f)return a?.animations&&d&&fe({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e;let h=n.transforms?.[a.transformId];if(!h)return console.warn("Transform not found:",a.transformId),e;let g={type:"container",id:qe,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 a.items){let b=n.images?.[y.resourceId];if(!b){console.warn(`Image resource not found: ${y.resourceId}`);continue}g.children.push({type:"sprite",id:`${qe}-${y.id}`,src:b.fileId,width:b.width,height:b.height,x:0,y:0})}return c.children.push(g),fe({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e},ja=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,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(k=>k.id==="story");if(!I)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:k={}}=n,V=k[t.dialogue.ui.resourceId];if(V){let M={elements:V.elements},R=de({variables:h,runtime:g,saveSlots:b,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:d,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:f,skipTransitionsAndAnimations:p}),D={functions:Se},F=Lt(M,R,D),L=ee(F,R,D),W=_e(Oe(L?.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)}}Va(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let N=we({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 fe({animationInstances:N,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&E.push(...N),e},Ma=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:c,autoMode:a,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=Ke(b);if(!E)return e;let I=n?.layouts[t.choice.resourceId];if(I&&I.elements){let k={elements:I.elements},V=ee(k,{...de({variables:l,runtime:c,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:a,skipMode:u,isChoiceVisible:f??!!t.choice,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:Se}),M=Pr(_e(Oe(V?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n));if(Array.isArray(M))for(let R of M)E.children.push(R);else M&&E.children.push(M)}let N=we({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"});fe({animationInstances:N,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&w.push(...N)}return e},Fa=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:c,autoMode:a,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=Ke(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||[]},k={...de({variables:l,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:a,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},V=ee(N,k,{functions:Se}),M=Dr(_e(Oe(Tr(V,y),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n),y);M&&E.children.push(M);let R=we({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 fe({animationInstances:R,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&w.push(...R),e},Ba=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,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=ka(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=Ke(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(xo({container:b,resources:r,templateData:de({variables:n,runtime:o,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:l,skipTransitionsAndAnimations:p})),e},Ua=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Ke(i))return e;let c=r.sounds[t.bgm.resourceId];if(!c)return e;let a=de({variables:o,runtime:n}).runtime;s.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:Ca(a,t.bgm.volume??c.volume??Tt),startDelayMs:t.bgm.startDelayMs??null})}return e},za=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx.items;for(let[s,l]of i.entries()){let c=r.sounds?.[l.resourceId];c&&o.push({id:Sa({item:l,index:s}),type:"sound",src:c.fileId,loop:l.loop??c.loop??!1,volume:xa(n,l.volume??c.volume??Tt),startDelayMs:l.startDelayMs??c.startDelayMs??null})}}return e},Wa=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},qa=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,Ya=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let l=t.voice,{resourceId:c,loop:a,startDelayMs:u}=l,f=Wa(r,n,c);if(!f)return e;let d=de({variables:i,runtime:o}).runtime;return s.push({id:`voice-${n}-${c}`,type:"sound",src:f.fileId,volume:qa(l,d),loop:a??!1,startDelayMs:u??null}),e},Ka=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,saveSlots:d=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:b}=e;if(t.layout){let N=Ke(y);if(!N)return e;let k=n.layouts[t.layout.resourceId];if(!k)return e;Array.isArray(k.transitions)&&!p&&!h&&jr({animations:b,transitions:k.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:k.elements||[]};N.children.push(xo({container:V,resources:n,templateData:de({variables:o,runtime:i,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:l,skipTransitionsAndAnimations:h}))}let w=r?.layout?.resourceId,E=t.layout?.resourceId,I=we({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 fe({animationInstances:I,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(...I),e},Ha=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,c=t?.screen?.animations;if(!c)return e;let a=r!=null,u=we({animationsDef:c,resources:n,previousResourceId:a?"story":void 0,currentResourceId:"story",previousTargetId:a?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return fe({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...u),e},Ja=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,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 k={id:`overlayStack-${I}`,type:"container",x:0,y:0,children:[vo({id:`overlayStack-${I}-blocker`,screen:h}),...N.elements||[]]},V=Eo(d,r.characters),M=de({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,historyDialogue:V,characters:r.characters||{},skipTransitionsAndAnimations:y}),R=ee(k,M,{functions:Se}),[D,...F]=R.children||[],L=_e(Oe({...R,children:F},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...L,children:D?[D,...L.children||[]]:L.children})}),e},Ga=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,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:[vo({id:"confirmDialog-blocker",screen:h}),...E.elements||[]]},N=Eo(p,r.characters),k=ee(I,de({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,confirmDialog:d,historyDialogue:N,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:Se}),[V,...M]=k.children||[],R=_e(Oe({...k,children:M},{isLineCompleted:g,skipMode:l,skipTransitionsAndAnimations:y}),r);return b.push({...R,children:V?[V,...R.children||[]]:R.children}),e},Co=e=>Ct(Pa,[Ba,Ta,Da,Na,ja,Ma,Fa,Ka,Ha,Ua,za,Ya,Ja,Ga])(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)?ke(e):e;return structuredClone(t)},P=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ft=e=>String(e),Lo=()=>({sections:[],resources:[]}),Xa=e=>P(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Lo(),Qa=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Za=({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}),ec=()=>({resourceId:void 0}),tc=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}},ko=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 l=r.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},Po=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},To=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},rc=(e,t={})=>{let r;try{r=To(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:Po(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},nc=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,rc(t,r)])),Do=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Kl(r));return t.length>0?t:void 0},oc=e=>{!P(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!P(t))return;let r=Do(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},So=(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}},ic=(e,t="viewedRegistry")=>{if(e===void 0)return Lo();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=So(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=So(o,"resources",i,t);return[s.resourceId,s]})))}},No=(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}},sc=(e,t,r)=>{if(!P(e)||!Array.isArray(e.timeline))return ct({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((l,c)=>{if(!P(l))return[];try{let a=No(l,r,`rollback.timeline[${c}]`),u=jt({sectionId:a.sectionId,lineId:a.lineId,rollbackPolicy:l.rollbackPolicy}),f=Do(T(l.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(n.length===0)return ct({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 l=n.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);l>=0?o=l:(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}},ac=(e,t,r)=>{if(!P(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=Kr(t),o=No(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?ze(T(e.variables),t.resources?.variables??{}):{},s=Ac({loadedContextRuntime:P(e.runtime)?T(e.runtime):{}}),l={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:sc(e.rollback,o,t)};return s&&(l.runtime=s),l},cc=(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)=>ac(r,t,n))}},lc=(e,t)=>{if(!P(e))throw new Error("Malformed save slot.");let r=To(e.formatVersion);return{...e,formatVersion:r,state:cc(e.state,t)}},_o=(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},uc=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:_o(e.confirmActions,"confirmActions",{required:!0}),cancelActions:_o(e.cancelActions,"cancelActions")}},Je=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},fc=e=>(P(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),Ge=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},Vo=e=>{if(!(!P(e)||!e.animations))return{animations:T(e.animations)}},dc=(e,t)=>{let r=Vo(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},pc=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},hc=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},Vt=e=>String(e??""),jo=(e,t)=>{let r=Vt(t);return e?.trim===!0?r.trim():r},mc=e=>P(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>P(t)).map(([t,r])=>[t,{id:t,...T(r)}])):{},gc=(e,t)=>{if(!t||!P(e.global.formDrafts))return;let r=e.global.formDrafts[t];return P(r)?r:void 0},Mo=(e,t)=>{let r=fc(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=jo(e,t);return e?.required===!0&&r.length===0?"required":null},yc=({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?{}:Te(n.slice(0,o+1).map(i=>i.actions||{}))},bc=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=pc(t),o=hc(r,n);if(!n||!o)return null;let i=gc(e,o),s=mc(t),l=Qr({state:e}),c={},a=[],u={},f=!0;return Object.entries(s).forEach(([d,p])=>{let h=Vt(l?.[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,a.push(I),u[d]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:f,submitted:i?.submitted===!0,fields:c,fieldList:a,values:u,submitActions:{submitForm:{formId:n,formKey:o,actions:T(t.submitActions??{})}},cancelActions:{cancelForm:{formId:n,formKey:o,actions:T(t.cancelActions??{})}}}},Ne=[],Oo="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)},Fo=()=>({...T(it)}),Bo=({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]=Uo(s,T(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Ic=({loadedGlobalRuntime:e={}})=>Bo({loadedRuntime:e,runtimeIds:Ir,defaults:De,path:"global.runtime"}).runtimeState,Ac=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=Bo({loadedRuntime:e,runtimeIds:Ar,defaults:Fo(),path:"context.runtime"});return r?t:void 0},Hr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},wc=e=>e.runtime?(Ar.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=T(it[t]))}),e.runtime):(e.runtime=Fo(),e.runtime),vc=e=>Qn(e.global),Ec=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:vc(e)}})},xc=e=>Xn[e],Cc=(e,t)=>{let r=xc(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}"`)},Uo=(e,t)=>(Cc(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),zo=(e,t,r)=>{let n=Uo(t,r);if(t in it){let o=Hr(e);if(!o)return n;let i=wc(o);return i[t]=n,n}return e.global[t]=n,n},Wo=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:T(e)},configuration:{},views:[],bgm:ec(),variables:Kr(t),rollback:ct({pointer:e})}),Xe=e=>e?(e.currentPointerMode="read",P(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Sc=(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=Wo({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,_c(e,{queueRender:t}),o},_c=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,Je(e),Ge(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"})},qo=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},ct=({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})]:[]}},je=(e,t={})=>{if(e?.rollback)return qo(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=ct({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=je(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},Oc=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=Ne[Ne.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)},Rc=({state:e},t={})=>{let r=t?.source===Oo?Oo: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?(Ne.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Ne.push({checkpointIndex:o.currentIndex,source:r}),e)},$c=({state:e})=>(Ne.pop(),e),be=(e,t,r)=>{let o=Ne[Ne.length-1]?.source??Yr;if(!Hl(t,o))return;let i=Oc(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:T(r)}))},Ro=(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:l}of n){let c=e.projectData.resources?.variables?.[o],a=c?.scope,u=c?.type;if(Ce(c))throw new Error(`Cannot update computed variable: ${o}`);if(c?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);_t(a,o),Ot(u,i,o),mr(u,i,s,o,{roundTo:l}),a==="context"&&(r.variables[o]=Rt(r.variables[o],i,s,{roundTo:l}))}},Lc=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{Jl(e,r,n)})},kc=(e,t)=>{let{sectionId:r,lineId:n}=t,s=X({state:e},{sectionId:r})?.lines?.find(l=>l.id===n)?.actions;s&&Object.entries(s).forEach(([l,c])=>{ci(e,l,c)})},Yo=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=je(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&ut({state:e}),e.global.skipMode&&Ve({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=[],Je(e),Ge(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let l=i;l<=t;l++)l>i&&zr(e),kc(e,n.timeline[l]),Lc(e,n.timeline[l]);let s=Xe(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},Pc=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;ko(t);let l=t.story.initialSceneId,c=t.story.scenes[l],a=c.initialSectionId,u=c.sections[a],f={sceneId:l,sectionId:a,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:d}=hr(t),p={...d,...ze(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:ic(s,"accountViewedRegistry"),nextLineConfig:Mt(),saveSlots:nc(n),overlayStack:[],variables:p,...Ic({loadedGlobalRuntime:i})},contexts:[Wo({pointer:f,projectData:t})]}},Tc=({state:e})=>e.global.overlayStack||[],Dc=({state:e})=>e.global.pendingEffects,Ko=({state:e})=>e.global.skipMode,Nc=({state:e})=>e.global.autoMode,Ho=({state:e})=>e.global.dialogueUIHidden,Jo=({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),l=i.lines.slice(0,s+1),c=[],a={};for(let u of l){let f=u.actions||{};if(a=Te([a,f]),!f.dialogue)continue;let d=a.dialogue||{},p="";d.character?.name!==void 0?p=d.character.name:d.characterId&&(p=e.projectData.resources?.characters?.[d.characterId]?.name||"");let h=Za({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},Vc=({state:e})=>e.global.confirmDialog??null,lt=({state:e},{pointer:t}={})=>{let r=t??pe({state:e})?.pointer,n=yc({state:e,pointer:r});return bc({state:e,form:n.form,pointer:r})},jc=({state:e},{pointer:t}={})=>!!lt({state:e},{pointer:t}),Ie=({state:e},{pointer:t}={})=>{let r=lt({state:e},{pointer:t});if(r)return{source:Nt,formId:r.id,formKey:r.key};let n=Go({state:e,pointer:t});return n?{source:Ur,resourceId:n}:null},Mc=({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 l=X({state:e},{sectionId:n});if(!l||!l.lines||!Array.isArray(l.lines))return s.lastLineId===o;let c=l.lines.findIndex(u=>u.id===s.lastLineId),a=l.lines.findIndex(u=>u.id===o);return c===-1||a===-1?s.lastLineId===o:a<=c},Fc=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},Gr=({state:e},t)=>Mc({state:e,registry:e.global.accountViewedRegistry},t),Bc=({state:e},t)=>Fc({registry:e.global.accountViewedRegistry},t),Uc=({state:e})=>e.global.nextLineConfig,Go=({state:e,pointer:t}={})=>{let r=t??pe({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=X({state:e},{sectionId:n})?.lines||[],l=s.findIndex(a=>a.id===o);if(l<0)return;let c;for(let a of s.slice(0,l+1)){let u=a?.actions;if(u?.cleanAll&&(c=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){c=void 0;continue}let f=u.choice;if(f?.resourceId){c=f.resourceId;continue}f?.animations||(c=void 0)}return c},Xo=({state:e})=>!!Go({state:e}),zc=({state:e})=>structuredClone(e),Qo=({state:e})=>e.global.saveSlots,Wc=({state:e},t)=>{let r=t?.slotId,n=Ft(r);return e.global.saveSlots[n]},Xr=({state:e})=>We(e),qc=({state:e},t)=>Ae(e,t?.runtimeId),Qr=({state:e})=>{let t={...e.global?.variables??{},...Hr(e)?.variables??{}};return St({variables:t,runtime:We(e),variableConfigs:e.projectData.resources?.variables??{}})},pe=({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=pe({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)},Zo=({state:e})=>{let{sectionId:t,lineId:r}=pe({state:e}).pointer,o=X({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===r),l=o.slice(0,i+1).map(a=>{let u=a.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return Te(l)},Yc=({state:e})=>{let t=ei({state:e}),n=Zr({state:e})?.actions??{},o=Te([t??{},n]);return gr(t??{},o??{})},Kc=({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||{},l=Te([o,s]),c=gr(o,l);n.push({id:i.id,changes:c,presentationState:l}),o=yr(l)}return n},Hc=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=Kc({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},ei=({state:e})=>{let{sectionId:t,lineId:r}=pe({state:e}).pointer,o=X({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===r);if(i<=0)return null;let l=o.slice(0,i).map(c=>{let a=c.actions||{},u={};return Object.keys(a).forEach(f=>{u[f]=a[f]}),u});return yr(Te(l))},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 l=o+s,c=e.global.saveSlots&&e.global.saveSlots[Ft(l)]||{};i.push({...c,slotId:l})}return{saveSlots:i}},Jc=Qo,Gc=en,Xc=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=Zo({state:e}),n=ei({state:e}),o=Zr({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:T(i)}:o,l=i?.animations&&n===null?{}:n,{sectionId:c}=pe({state:e}).pointer,{sceneId:a}=Wr(e.projectData,c),u=Xr({state:e}),f=t?.activePersistentAnimations??[],d=t?.restoredPersistentAnimations??[],p=lt({state:e}),h=Xo({state:e}),g=Qr({state:e}),{saveSlots:y}=en({state:e}),b=Xc(e);return Co({presentationState:r,previousPresentationState:l,currentLineActions:s,resources:e.projectData.resources,currentSceneId:a,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:ui({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:Jo({state:e}),saveSlots:y,variables:g,runtime:u,activePersistentAnimations:f,restoredPersistentAnimations:d})},Zc=({state:e},t)=>(e.global.confirmDialog=uc(t),e.global.pendingEffects.push({name:"render"}),e),el=({state:e})=>(e.global.confirmDialog&&(Je(e),e.global.pendingEffects.push({name:"render"})),e),tl=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),be(e,"pushOverlay",t),e),rl=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),be(e,"popOverlay",void 0),e),nl=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),be(e,"replaceLastOverlay",t),e),ol=({state:e})=>(e.global.overlayStack=[],Je(e),Ge(e),e.global.pendingEffects.push({name:"render"}),be(e,"clearOverlays",void 0),e),il=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,dc(e,r),Ge(e);let n=Ie({state:e},{pointer:t}),o=n?.source===Ur,i=n?.source===Nt;return n&&il(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},ti=({state:e})=>(Ie({state:e})||(e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.autoMode=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.isLineCompleted&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ae(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),ut=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),sl=({state:e})=>{let t=e.global.autoMode;return Ie({state:e})&&!t||(t?ut({state:e}):ti({state:e})),e},ri=({state:e})=>(Ie({state:e})||(e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode=!0,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"startSkipNextTimer"}),e.global.pendingEffects.push({name:"render"})),e),Ve=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),al=({state:e})=>{let t=Ko({state:e});return Ie({state:e})&&!t||(t?Ve({state:e}):ri({state:e})),e},Ut=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),be(e,"showDialogueUI",void 0),e),ni=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),be(e,"hideDialogueUI",void 0),e),cl=({state:e})=>(Ho({state:e})?Ut({state:e}):ni({state:e}),e),Me=(e,t,r)=>(zo(e,t,r),Ec(e),e.global.pendingEffects.push({name:"render"}),e),ft=(e,t,r,n)=>{let o=zo(e,t,r);return e.global.pendingEffects.push({name:"render"}),be(e,n,{value:o}),e},ll=({state:e},t)=>Me(e,"dialogueTextSpeed",t?.value),ul=({state:e},t)=>Me(e,"autoForwardDelay",t?.value),fl=({state:e},t)=>Me(e,"skipUnseenText",t?.value),dl=({state:e},t)=>Me(e,"skipTransitionsAndAnimations",t?.value),pl=({state:e},t)=>Me(e,"soundVolume",t?.value),hl=({state:e},t)=>Me(e,"musicVolume",t?.value),ml=({state:e},t)=>Me(e,"muteAll",t?.value),gl=({state:e},t)=>ft(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),yl=({state:e})=>{let t=Ae(e,"saveLoadPagination")+1;return ft(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},bl=({state:e})=>{let t=Ae(e,"saveLoadPagination")-1;return ft(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},Il=({state:e},t)=>ft(e,"menuPage",t?.value,"setMenuPage"),Al=({state:e},t)=>ft(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),wl=({state:e})=>(e.global.pendingEffects=[],e),vl=({state:e},t)=>(e.global.pendingEffects.push(t),e),oi=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!Vo(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&&!Sc(e,{queueRender:!o}))return e;e.global.autoMode&&ut({state:e}),r&&e.global.skipMode&&Ve({state:e});let l=e.contexts?.[e.contexts.length-1];if(l){let c=Xe(l),a=c.read;r||He(e,{sectionId:a?.sectionId,lineId:a?.lineId}),l.rollback||je(l,{compatibilityAnchor:!0}),c.read={sectionId:t,lineId:s.id},r?l.rollback=ct({pointer:c.read}):Jr(e,{sectionId:t,lineId:s.id})}return Bt(e,l?.pointers?.read,{screenTransition:n}),e},El=({state:e},t)=>oi(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),ii=e=>(e.global.accountViewedRegistry=Xa(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)}))}})},si=(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:[]}}])},xl=(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 l=s.lines.findIndex(a=>a.id===i.lastLineId),c=s.lines.findIndex(a=>a.id===n);if(l===-1||c>l)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},He=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;xl(e,ii(e),t)&&si(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},Cl=({state:e},t)=>(He(e,t),e.global.pendingEffects.push({name:"render"}),e),Sl=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=ii(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),si(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},ai=({state:e},t)=>{let r=tc(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=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,a=Ie({state:e});return!l&&!a&&c===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!l&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),be(e,"setNextLineConfig",t),e},_l=({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(a=>{Xe(a),qo(a.rollback),oc(a.rollback)});let l={contexts:s},c={formatVersion:$o,slotId:Po(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:l};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Ol=({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=lc(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,Je(e),Ge(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},Rl=({state:e},t)=>{let{projectData:r}=t;ko(r),e.projectData=r;let n=r?.resources?.variables??{};return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables=ze(e.global.variables,n)),e.contexts?.forEach(o=>{Object.prototype.hasOwnProperty.call(o??{},"variables")&&(o.variables=ze(o.variables,n))}),Je(e),Ge(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(a=>a.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let c=Xe(o);return c.read={sectionId:i,lineId:n},Bt(e,c.read),e},Ll=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return Ut({state:e}),e;let r=Ie({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=pe({state:e})?.pointer,f=u?.sectionId,d=u?.lineId;f&&d&&He(e,{sectionId:f,lineId:d}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ae(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=pe({state:e})?.pointer,o=n?.sectionId,i=X({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],l=i?.lines||[],a=l.findIndex(u=>u.id===n?.lineId)+1;if(a<l.length){let u=l[a],f=!Ae(e,"skipUnseenText");if(e.global.skipMode&&f&&!Gr({state:e},{sectionId:o,lineId:u.id}))return Ve({state:e}),e;if(s&&!s.rollback&&je(s,{compatibilityAnchor:!0}),s){let h=Xe(s),g=h.read?.lineId;g&&o&&He(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&&ut({state:e}),e.global.skipMode&&Ve({state:e});return e},kl=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ie({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ae(e,"autoForwardDelay")}});let r=pe({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&He(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},Pl=({state:e},t)=>oi(e,{sectionId:t?.sectionId,screen:t?.screen}),Tl=({state:e})=>{if(e.global.dialogueUIHidden)return Ut({state:e}),e;if(Ie({state:e}))return e;let t=pe({state:e})?.pointer,r=t?.sectionId,n=X({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],l=i.findIndex(c=>c.id===t?.lineId)+1;if(l<i.length){let c=i[l],a=!Ae(e,"skipUnseenText");if(e.global.skipMode&&a&&!Gr({state:e},{sectionId:r,lineId:c.id}))return Ve({state:e}),e;if(o&&!o.rollback&&je(o,{compatibilityAnchor:!0}),o){let f=Xe(o),d=f.read?.lineId;d&&r&&He(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=lt({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},Dl=(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(Ce(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return _t(n,t.variableId),Ot(o,"set",t.variableId),{variableConfig:r,scope:n}},Nl=(e,t)=>({id:e.id,key:e.key,valid:!0,values:T(t),fields:T(e.fields),fieldList:T(e.fieldList)}),Vl=({state:e},t={})=>{let r=rn(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=Mo(e,r.key),i=Vt(t.value),s=r.fields[n],l=qr(s,i);return o.values[n]=i,o.touched[n]=!0,l?o.errors[n]=l:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},jl=({state:e},t={})=>{let r=rn(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=Mo(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]=jo(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 l=!1,c=[],a=[];Object.entries(r.fields).forEach(([f,d])=>{let{scope:p}=Dl(e,d),h=p==="context"?s.variables:e.global.variables,g=o[f];h[d.variableId]=Rt(h[d.variableId],"set",g),p==="context"&&(l=!0,a.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])})}),l&&be(e,"updateVariable",{id:"submitForm",operations:a}),tn(e,c);let u=Nl(r,o);return delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},Ml=({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"}},Fl=({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=[],l=[];return n.forEach(({variableId:c,op:a,value:u,roundTo:f})=>{let d=e.projectData.resources?.variables?.[c],p=d?.scope,h=d?.type;if(Ce(d))throw new Error(`Cannot update computed variable: ${c}`);if(d?.readonly===!0)throw new Error(`Cannot update readonly variable: ${c}`);_t(p,c),Ot(h,a,c),mr(h,a,u,c,{roundTo:f});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:c,op:a,value:u};f!==void 0&&(y.roundTo=f),l.push(y)}g[c]=Rt(g[c],a,u,{roundTo:f}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${c}`,op:"set",value:T(g[c])})}),i&&be(e,"updateVariable",{id:r,operations:l}),tn(e,s),e.global.pendingEffects.push({name:"render"}),e},Bl=e=>(t,r)=>e({state:t},r),Ul=e=>({variables:St({variables:{...e.global?.variables??{},...Hr(e)?.variables??{}},runtime:We(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:We(e)}),zl=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")},Wl=(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")},ql=(e,t)=>{zl(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(Wl(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!nt(n.when,Ul(e)))){Object.entries(n.actions).forEach(([i,s])=>{ci(e,i,s)});return}}},Yl={conditional:{replayLine:ql},updateVariable:{recordSources:[Yr],replayLine:Ro,replayRecorded:Ro,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Bl(ai)}},zt=e=>Yl[e]??null,Kl=e=>zt(e)?.persistInSaveSlot===!0,Hl=(e,t)=>{let r=zt(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},Jl=(e,t,r)=>{zt(t)?.replayRecorded?.(e,r)},ci=(e,t,r)=>{zt(t)?.replayLine?.(e,r)},li=({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}},ui=({state:e})=>li({state:e},{offset:-1})!==null,Gl=({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=je(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:Yo(e,i)},Xl=({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=je(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===r&&c.lineId===n);if(l===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return l===i.currentIndex?e:Yo(e,l)},fi=e=>{let t=Pc(e);return Un(t,{selectPendingEffects:Dc,selectSkipMode:Ko,selectAutoMode:Nc,selectIsChoiceVisible:Xo,selectIsFormVisible:jc,selectActiveInteraction:Ie,selectActiveForm:lt,selectDialogueUIHidden:Ho,selectDialogueHistory:Jo,selectConfirmDialog:Vc,selectIsLineAccountViewed:Gr,selectIsResourceAccountViewed:Bc,selectNextLineConfig:Uc,selectSystemState:zc,selectSaveSlotMap:Qo,selectSaveSlots:Jc,selectSaveSlot:Wc,selectRuntime:Xr,selectRuntimeValue:qc,selectAllVariables:Qr,selectCurrentPointer:pe,selectSection:X,selectCurrentLine:Zr,selectPresentationState:Zo,selectPresentationChanges:Yc,selectSectionLineChanges:Hc,selectSaveSlotPage:en,selectCurrentPageSlots:Gc,selectRenderState:Qc,selectOverlayStack:Tc,selectLineIdByOffset:li,selectCanRollback:ui,startAutoMode:ti,stopAutoMode:ut,toggleAutoMode:sl,startSkipMode:ri,stopSkipMode:Ve,toggleSkipMode:al,showDialogueUI:Ut,hideDialogueUI:ni,toggleDialogueUI:cl,setDialogueTextSpeed:ll,setAutoForwardDelay:ul,setSkipUnseenText:fl,setSkipTransitionsAndAnimations:dl,setSoundVolume:pl,setMusicVolume:hl,setMuteAll:ml,setSaveLoadPagination:gl,incrementSaveLoadPagination:yl,decrementSaveLoadPagination:bl,setMenuPage:Il,setMenuEntryPoint:Al,showConfirmDialog:Zc,hideConfirmDialog:el,resetStoryAtSection:El,clearPendingEffects:wl,appendPendingEffect:vl,beginRollbackActionBatch:Rc,endRollbackActionBatch:$c,addViewedLine:Cl,addViewedResource:Sl,setNextLineConfig:ai,saveSlot:_l,loadSlot:Ol,updateProjectData:Rl,sectionTransition:Pl,jumpToLine:$l,nextLine:Ll,markLineCompleted:kl,rollbackToLine:Xl,rollbackByOffset:Gl,pushOverlay:tl,popOverlay:rl,replaceLastOverlay:nl,clearOverlays:ol,updateFormField:Vl,submitForm:jl,cancelForm:Ml,updateVariable:Fl,nextLineFromSystem:Tl},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var Ql="route-engine",Zl="projectPersistence";var pi=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),J=e=>Object.prototype.toString.call(e)==="[object Object]",di="variables.",eu=(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)}},tu=(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)}},ru=(e,t)=>{let r=tu(e),n=eu(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let l=o.find(c=>c.sectionId===s.sectionId);if(!l){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(l.lastLineId!==void 0){if(s.lineId===void 0){delete l.lastLineId;return}l.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(c=>c.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},hi=(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:{}}},nu=(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(di)?t.path.slice(di.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}].`)})},ou=(e,t)=>{let r={};return nu(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=ru(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},iu=e=>{let t=nn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},su=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},au=({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}".`))}}),cu=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.`))}})},dt=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),c=l.objectStore(t),a=c.get(r),u=!1,f=p=>{u||(u=!0,s(p))},d=()=>{u||(u=!0,i())};a.onerror=()=>{f(a.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},a.onsuccess=()=>{let p=hi(a.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...pi(),...p,...h},y=c.put(g);y.onerror=()=>{f(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},l.oncomplete=()=>{d()},l.onerror=()=>{f(l.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},l.onabort=()=>{f(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},lu=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),a=!1,u=d=>{a||(a=!0,i(d))},f=()=>{a||(a=!0,o())};c.onerror=()=>{u(c.error??new Error(`Failed to clear persisted namespace "${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=Zl,namespace:o}=e,i=su(t),s=iu(o),l=au({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let c=await cu({databasePromise:l,objectStoreName:n,namespace:s});return{...pi(),...hi(c)}},clear:async()=>lu({databasePromise:l,objectStoreName:n,namespace:s}),saveSlots:async c=>dt({databasePromise:l,objectStoreName:n,namespace:s,patch:{saveSlots:J(c)?c:{}}}),saveGlobalDeviceVariables:async c=>dt({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:J(c)?c:{}}}),saveGlobalAccountVariables:async c=>dt({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalAccountVariables:J(c)?c:{}}}),saveGlobalRuntime:async c=>dt({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalRuntime:J(c)?c:{}}}),applyScopedDataUpdates:async c=>dt({databasePromise:l,objectStoreName:n,namespace:s,patch:a=>ou(a,c)})}},uu=on;var fu=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),du=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),mi="conditional",sn="form",pu=new Set(["submitForm","cancelForm"]),pt=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:l}=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}])),a=(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{l(A)}catch(C){throw t.clearPendingEffects(),A.forEach(_=>{t.appendPendingEffect(_)}),C}}},d=({initialState:A,namespace:C})=>{t=fi(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,me={...t.selectRenderState({activePersistentAnimations:a(U),restoredPersistentAnimations:a(z)}),id:`render-${r}`};return s.set(me.id,{builtAt:C,persistentAnimationSessions:new Map([...z.entries(),...U.entries()]),usedRestoredPersistentAnimationSessions:_}),me},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;ho(A?.animations).forEach(z=>{let ie=kt(z);if(!ie)return;let me=_?.persistentAnimationSessions?.get(ie)??o.get(ie),ht=Math.max(0,go(z)),un=me?.startedAt??_?.builtAt??Date.now();U.set(ie,{animation:structuredClone(z),startedAt:un,expiresAt:un+ht})}),o=U,_?.usedRestoredPersistentAnimationSessions&&(i=new Map)},N=()=>t.selectSystemState(),k=()=>t.selectSaveSlotMap(),V=A=>t.selectSaveSlot(A),M=A=>t.selectSaveSlotPage(A),R=()=>t.selectSkipMode(),D=()=>t.selectAutoMode(),F=()=>t.selectRuntime(),L=()=>t.selectIsChoiceVisible(),W=()=>t.selectIsFormVisible(),x=()=>t.selectActiveInteraction(),S=(A,C,_={})=>A!=="nextLine"||!pt(C)?C:_.bypassChoice===!0?{...C,bypassChoice:!0}:_.interactionSource===sn?{...C,_interactionSource:sn}:C,B=(A,C)=>{if(!t[A])return;fu.has(A)&&(du.has(A)?i=c(o):i=new Map,o=new Map);let _=t[A](C);return f(),_},K=(A,C,_,U={})=>{if(A===mi){let z=j(_),ie=br({[A]:C},z);Fe(ie[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():{}}},he=A=>{if(!pt(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(!pt(A))throw new Error(`conditional branch at index ${C} must be an object`);if(!pt(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")},Fe=(A,C,_)=>{he(A);for(let U=0;U<A.branches.length;U+=1){let z=A.branches[U];Z(z,U,A.branches.length);let ie=j(C);if(!(Object.prototype.hasOwnProperty.call(z,"when")&&!nt(z.when,ie))){qt(z.actions,C,_);return}}},bi=(A,C)=>({...A??{},_form:C}),Ii=(A,C,_,U)=>{let z=B(A,C),ie=z?.submitted===!0&&z.valid===!0,me=z?.cancelled===!0;!ie&&!me||pt(C.actions)&&qt(C.actions,bi(_,z.form),{...U,interactionSource:sn})},Ai=(A,C,_,U)=>{let z=j(_),me=br({[A]:C},z)[A];if(A===mi){Fe(me,_,U);return}let ht=S(A,me,U);if(pu.has(A)){Ii(A,ht,_,U);return}B(A,ht)},qt=(A,C,_)=>{Object.entries(A).forEach(([U,z])=>{Ai(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:k,selectSaveSlot:V,selectSaveSlotPage:M,selectSaveSlots:k,selectRuntime:F,selectIsChoiceVisible:L,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}}},hu=80,yi=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},mu=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&yi({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},gu=({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 l=n.delay??1e3;r.getElapsed()>=l&&(t.remove(i),r.setCallback(null),r.setElapsed(0),Wt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},yu=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},bu=({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 l=n?.delay??hu;r.getElapsed()>=l&&(r.setElapsed(0),Wt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},Iu=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Au=({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 l=n.delay??1e3;r.getElapsed()>=l&&(r.setElapsed(0),Wt(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},wu=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},vu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},Eu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},xu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},Cu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},Su=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},gi={render:yi,saveSlots:vu,saveGlobalDeviceVariables:Eu,saveGlobalAccountVariables:xu,saveGlobalRuntime:Cu,applyScopedDataUpdates:Su,handleLineActions:mu,startAutoNextTimer:gu,clearAutoNextTimer:yu,startSkipNextTimer:bu,clearSkipNextTimer:Iu,nextLineConfigTimer:Au,clearNextLineConfigTimer:wu},_u=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)},Ou=(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(!_u.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},Ru=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let c=cn(),a=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:l??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,k=(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"||!k(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,R=(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(R(x,S))return!0;let B=x?.actions;return!B||typeof B!="object"||Array.isArray(B)?!1:Object.values(B).some(K=>R(K,S))},F=(x,S={})=>{if(!S?.actions)return!1;let B=M(x);return!B||B.source==="choice"?!1:!D(S,B)},L=({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 he=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,he,Z):q.handleActions(j.actions,he)}return S?.(B,j)},W=x=>{let S=e(),B=Ou(x);B.forEach(q=>{if(!gi[q.name]&&!n)throw new Error(`Unhandled pending effect "${q.name}".`)});let K={engine:S,routeGraphics:t,ticker:r,autoTimer:c,skipTimer:a,nextLineConfigTimerState:u,trackRenderDispatch:I,getRenderDispatchCount:N,enqueuePersistenceWrite:E};for(let q of B){let j=gi[q.name];if(j){j(K,q.payload);continue}n(q,K)}};return W.handleRouteGraphicsEvent=V,W.createRouteGraphicsEventHandler=L,W},$u=Ru;var Lu=(e,t={})=>{let{resources:r={}}=t;return Br(e,r)};var Jf=an;export{$u as createEffectsHandler,uu as createIndexedDbPersistence,Jf as default,_s as resolveComputedVariables,Lu as resolveLayoutReferences};
|
|
1
|
+
var _i=Object.defineProperty;var Ri=(e,t)=>{for(var r in t)_i(e,r,{get:t[r],enumerable:!0})};var wn=Symbol.for("immer-nothing"),gn=Symbol.for("immer-draftable"),te=Symbol.for("immer-state");function ae(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Be=Object.getPrototypeOf;function re(e){return!!e&&!!e[te]}function $e(e){return e?En(e)||Array.isArray(e)||!!e[gn]||!!e.constructor?.[gn]||wt(e)||Et(e):!1}var Oi=Object.prototype.constructor.toString();function En(e){if(!e||typeof e!="object")return!1;let t=Be(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)===Oi}function yt(e,t){At(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function At(e){let t=e[te];return t?t.type_:Array.isArray(e)?1:wt(e)?2:Et(e)?3:0}function Xt(e,t){return At(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function vn(e,t,r){let n=At(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function Li(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function wt(e){return e instanceof Map}function Et(e){return e instanceof Set}function Le(e){return e.copy_||e.base_}function Qt(e,t){if(wt(e))return new Map(e);if(Et(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=En(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],l=n[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(n[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(Be(e),n)}else{let n=Be(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function nr(e,t=!1){return vt(e)||re(e)||!$e(e)||(At(e)>1&&(e.set=e.add=e.clear=e.delete=$i),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>nr(n,!0))),e}function $i(){ae(2)}function vt(e){return Object.isFrozen(e)}var ki={};function ke(e){let t=ki[e];return t||ae(0,e),t}var Ze;function xn(){return Ze}function Di(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function yn(e,t){t&&(ke("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Zt(e){er(e),e.drafts_.forEach(Pi),e.drafts_=null}function er(e){e===Ze&&(Ze=e.parent_)}function bn(e){return Ze=Di(Ze,e)}function Pi(e){let t=e[te];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function In(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[te].modified_&&(Zt(t),ae(4)),$e(e)&&(e=bt(t,e),t.parent_||It(t,e)),t.patches_&&ke("Patches").generateReplacementPatches_(r[te].base_,e,t.patches_,t.inversePatches_)):e=bt(t,r,[]),Zt(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==wn?e:void 0}function bt(e,t,r){if(vt(t))return t;let n=t[te];if(!n)return yt(t,(o,i)=>An(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return It(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),yt(i,(l,c)=>An(e,n,o,l,c,r,s)),It(e,o,!1),r&&e.patches_&&ke("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function An(e,t,r,n,o,i,s){if(re(o)){let l=i&&t&&t.type_!==3&&!Xt(t.assigned_,n)?i.concat(n):void 0,c=bt(e,o,l);if(vn(r,n,c),re(c))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if($e(o)&&!vt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;bt(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&It(e,o)}}function It(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&nr(t,r)}function Ti(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:xn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=or;r&&(o=[n],i=et);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return n.draft_=l,n.revoke_=s,l}var or={get(e,t){if(t===te)return e;let r=Le(e);if(!Xt(r,t))return Ni(e,r,t);let n=r[t];return e.finalized_||!$e(n)?n:n===Gt(e.base_,t)?(Jt(e),e.copy_[t]=rr(n,e)):n},has(e,t){return t in Le(e)},ownKeys(e){return Reflect.ownKeys(Le(e))},set(e,t,r){let n=Cn(Le(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=Gt(Le(e),t),i=o?.[te];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(Li(r,o)&&(r!==void 0||Xt(e.base_,t)))return!0;Jt(e),tr(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 Gt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Jt(e),tr(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Le(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){ae(11)},getPrototypeOf(e){return Be(e.base_)},setPrototypeOf(){ae(12)}},et={};yt(or,(e,t)=>{et[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});et.deleteProperty=function(e,t){return et.set.call(this,e,t,void 0)};et.set=function(e,t,r){return or.set.call(this,e[0],t,r,e[0])};function Gt(e,t){let r=e[te];return(r?Le(r):e)[t]}function Ni(e,t,r){let n=Cn(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function Cn(e,t){if(!(t in e))return;let r=Be(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=Be(r)}}function tr(e){e.modified_||(e.modified_=!0,e.parent_&&tr(e.parent_))}function Jt(e){e.copy_||(e.copy_=Qt(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Vi=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,...a){return s.produce(c,u=>r.call(this,u,...a))}}typeof r!="function"&&ae(6),n!==void 0&&typeof n!="function"&&ae(7);let o;if($e(t)){let i=bn(this),s=rr(t,void 0),l=!0;try{o=r(s),l=!1}finally{l?Zt(i):er(i)}return yn(i,n),In(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===wn&&(o=void 0),this.autoFreeze_&&nr(o,!0),n){let i=[],s=[];ke("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else ae(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,c=>t(c,...l));let n,o;return[this.produce(t,r,(s,l)=>{n=s,o=l}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){$e(e)||ae(8),re(e)&&(e=De(e));let t=bn(this),r=rr(e,void 0);return r[te].isManual_=!0,er(t),r}finishDraft(e,t){let r=e&&e[te];(!r||!r.isManual_)&&ae(9);let{scope_:n}=r;return yn(n,t),In(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=ke("Patches").applyPatches_;return re(e)?n(e,t):this.produce(e,o=>n(o,t))}};function rr(e,t){let r=wt(e)?ke("MapSet").proxyMap_(e,t):Et(e)?ke("MapSet").proxySet_(e,t):Ti(e,t);return(t?t.scope_:xn()).drafts_.push(r),r}function De(e){return re(e)||ae(10,e),Sn(e)}function Sn(e){if(!$e(e)||vt(e))return e;let t=e[te],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=Qt(e,t.scope_.immer_.useStrictShallowCopy_)}else r=Qt(e,!0);return yt(r,(n,o)=>{vn(r,n,Sn(o))}),t&&(t.finalized_=!1),r}var ne=new Vi,ir=ne.produce,qu=ne.produceWithPatches.bind(ne),Yu=ne.setAutoFreeze.bind(ne),Hu=ne.setUseStrictShallowCopy.bind(ne),Ku=ne.applyPatches.bind(ne),Gu=ne.createDraft.bind(ne),Ju=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},L={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},ze={NOT:0};var w=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 sr=e=>{if(!e||e.trim()==="")throw new w("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new w(`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 w(`Incomplete comparison expression - missing right operand (got: '${e}')`)},_n=e=>{if(e.trim().endsWith(" in"))throw new w(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new w(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new w(`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 w(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new w(`Invalid loop syntax (got: '$for ${e}')`)}};var Rn=(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}'`)},On=(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 ji=(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 H(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return H(e.path,r,n);if(e.type===m.INTERPOLATION)return Fi(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return $n(e,t,r,n);case m.BINARY:return kn(e,t,r,n);case m.UNARY:return Dn(e,t,r,n);case m.CONDITIONAL:return Bi(e,t,r,n);case m.LOOP:return Hi(e,t,r,n);case m.OBJECT:return Gi(e,t,r,n);case m.ARRAY:return Ji(e,t,r,n);case m.PARTIAL:return Xi(e,t,r,n);case m.PATH_REFERENCE:return Qi(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Ln=new Map,Mi=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 l=s.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},H=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=Ln.get(e);if(!n){let i=[],s="",l=0;for(let c=0;c<e.length;c++){let a=e[c];a==="["?(l++,s+=a):a==="]"?(l--,s+=a):a==="."&&l===0?s&&(i.push(s),s=""):s+=a}s&&i.push(s),n=[];for(let c of i){let a=Mi(c.trim());n.push(...a)}Ln.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},Fi=(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("")},$n=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw On(e.name,o);let s=e.args.map(l=>$(l,t,r,n));return i(...s)},Ee=(e,t,r,n)=>{if(e.var&&!e.type)return H(e.var,r,n);switch(e.type){case m.VARIABLE:return H(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return kn(e,t,r,n);case m.UNARY:return Dn(e,t,r,n);case m.FUNCTION:return $n(e,t,r,n);default:return $(e,t,r,n)}},kn=(e,t,r,n)=>{if(e.op===L.AND||e.op===L.OR){let s=Ee(e.left,t,r,n),l=Ee(e.right,t,r,n);switch(e.op){case L.AND:return s&&l;case L.OR:return s||l}}let o=$(e.left,t,r,n),i=$(e.right,t,r,n);switch(e.op){case L.EQ:return o==i;case L.NEQ:return o!=i;case L.GT:return o>i;case L.LT:return o<i;case L.GTE:return o>=i;case L.LTE:return o<=i;case L.IN:return Array.isArray(i)?i.includes(o):!1;case L.ADD:if(typeof o!="number"||typeof i!="number")throw new Q(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case L.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}`)}},Dn=(e,t,r,n)=>{let o=e.op===ze.NOT?Ee(e.operand,t,r,n):$(e.operand,t,r,n);if(e.op===ze.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Ui=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(H(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let c of s.properties){let a=c.parsedKey?$(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)l[a]=u.value;else if(u.type===m.VARIABLE)l[a]=H(u.path,r,n);else if(u.type===m.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===m.VARIABLE){let p=H(f.path,r,n);d.push(p!=null?String(p):"")}else{let p=$(f,t,r,n);d.push(p!=null?String(p):"")}l[a]=d.join("")}else l[a]=$(u,t,r,n)}return l}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let c of s.properties){let a=c.parsedKey?$(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)l[a]=u.value;else if(u.type===m.VARIABLE)l[a]=H(u.path,r,n);else if(u.type===m.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===m.VARIABLE){let p=H(f.path,r,n);d.push(p!=null?String(p):"")}else{let p=$(f,t,r,n);d.push(p!=null?String(p):"")}l[a]=d.join("")}else l[a]=$(u,t,r,n)}return l}}}return null},Bi=(e,t,r,n)=>{let o=Ui(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||Ee(s,t,r,n))return $(e.bodies[i],t,r,n)}return Pn},zi=(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 l=[];for(let c=0;c<t.length;c++){let a=t[c];if(a[s]){let u={};for(let d of i.properties){let f=d.key,p=d.value;if(p.type===m.LITERAL)u[f]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)u[f]=a;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);u[f]=a[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(a!=null?String(a):"");else if(b.startsWith(n+".")){let A=b.substring(n.length+1),x=a[A];h.push(x!=null?String(x):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[f]=h.join("")}else return null}l.push(u)}}return l}}}return null},Wi=(e,t)=>{let r=e.body,n=e.itemVar,o=zi(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let l of r.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of r.properties){let c=l.key,a=l.value;if(a.type===m.LITERAL)i.push({key:c,type:"literal",value:a.value});else if(a.type===m.VARIABLE){let u=a.path;if(u===n)i.push({key:c,type:"item"});else if(u.startsWith(n+".")){let d=u.substring(n.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,type:"prop",prop:d});else{s=!1;break}}else{s=!1;break}}else if(a.type===m.INTERPOLATION&&a.parts.length===1){let u=a.parts[0];if(u.type===m.VARIABLE){let d=u.path;if(d===n)i.push({key:c,type:"item_string"});else if(d.startsWith(n+".")){let f=d.substring(n.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop_string",prop:f});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let l=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let a=t[c];l[c]={id:a.id,title:a.title!=null?String(a.title):"",completed:a.completed}}else for(let c=0;c<t.length;c++){let a=t[c],u={};for(let d of i)if(d.type==="literal")u[d.key]=d.value;else if(d.type==="item")u[d.key]=a;else if(d.type==="prop")u[d.key]=a[d.prop];else if(d.type==="item_string")u[d.key]=a!=null?String(a):"";else if(d.type==="prop_string"){let f=a[d.prop];u[d.key]=f!=null?String(f):""}l[c]=u}return l}}return null},qi=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let l=e.itemVar,c=e.indexVar;for(let a=0;a<o.length;a++){let u=o[a],d={},f={...n,[l]:u,...c&&{[c]:a}};f.__paths__||(f.__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(".")))}f.__paths__={...f.__paths__,[l]:`${p}[${a}]`,...c&&{[c]:a}};for(let h of s.properties){let g=h.parsedKey?$(h.parsedKey,t,r,f):h.key,y=h.value;if(y.type===m.LITERAL)d[g]=y.value;else if(y.type===m.VARIABLE){let b=y.path;if(b===l)d[g]=u;else if(b===c)d[g]=a;else if(b.startsWith(l+".")){let A=b.substring(l.length+1);!A.includes(".")&&!A.includes("[")?d[g]=u[A]:d[g]=H(b,r,{...n,[l]:u,...c&&{[c]:a}})}else d[g]=H(b,r,{...n,[l]:u,...c&&{[c]:a}})}else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let x=A.path,S;if(x===l)S=u;else if(x===c)S=a;else if(x.startsWith(l+".")){let T=x.substring(l.length+1);!T.includes(".")&&!T.includes("[")?S=u[T]:S=H(x,r,{...n,[l]:u,...c&&{[c]:a}})}else S=H(x,r,{...n,[l]:u,...c&&{[c]:a}});b.push(S!=null?String(S):"")}else{let x={...n,[l]:u,...c&&{[c]:a}},S=$(A,t,r,x);b.push(S!=null?String(S):"")}d[g]=b.join("")}else{let b={...n,[l]:u,...c&&{[c]:a}};d[g]=$(y,t,r,b)}}i.push(d)}return i}return null},Yi=(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 l=s.properties[0],c=s.properties[1];if(l.key==="id"&&l.value.type===m.VARIABLE&&l.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===m.CONDITIONAL){let a=[];for(let u=0;u<t.length;u++){let d=t[u];if(d.visible){let f={id:d.id};d.highlighted?(f.highlight=!0,f.message=`This item is highlighted: ${d.name}`):(f.highlight=!1,f.message=d.name),a.push(f)}}return a}}}}return null},Hi=(e,t,r,n)=>{let o=$(e.iterable,t,r,n);if(!Array.isArray(o)){let a,u=!1;if(e.iterable.type===m.FUNCTION){u=!0;let f=e.iterable.args.map(p=>p.type===m.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===m.VARIABLE?p.path:p.type===m.FUNCTION?`${p.name}(...)`:"?").join(", ");a=`${e.iterable.name}(${f})`}else a=e.iterable.path||"undefined";let d=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${a}`;throw Rn(d,o,u)}if(!e.indexVar){let a=Yi(e,o,e.itemVar);if(a!==null)return a}if(!e.indexVar){let a=Wi(e,o);if(a!==null)return a}let i=qi(e,t,r,n,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(n&&n.__paths__&&l){let a=l.split("."),u=a[0];u in n.__paths__&&(l=n.__paths__[u],a.length>1&&(l+="."+a.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(a=>a.type===m.OBJECT&&a.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let a=0;a<o.length;a++){let u=e.indexVar?{...n,[e.itemVar]:o[a],[e.indexVar]:a}:{...n,[e.itemVar]:o[a]};u.__paths__||(u.__paths__=n.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${a}]`},e.indexVar&&(u.__paths__[e.indexVar]=a);let d=$(e.body,t,r,u);if(Array.isArray(d)&&d.length===1&&!c){let f=d[0];s.push(f===void 0?{}:f)}else s.push(d===void 0?{}:d)}return s},Ki=(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 l={},c={},a=!0;for(let u of s.properties){let d=u.parsedKey?$(u.parsedKey,t,r,n):u.key,f=u.value;if(f.type===m.LITERAL)c[d]=f.value;else if(f.type===m.VARIABLE)c[d]=H(f.path,r,n);else if(f.type===m.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=H(h.path,r,n);p.push(g!=null?String(g):"")}else{a=!1;break}if(!a)break;c[d]=p.join("")}else if(f.type===m.OBJECT&&f.properties.length<=5){let p={};for(let h of f.properties){let g=h.key,y=h.value;if(y.type===m.LITERAL)p[g]=y.value;else if(y.type===m.VARIABLE)p[g]=H(y.path,r,n);else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let x=H(A.path,r,n);b.push(x!=null?String(x):"")}else{a=!1;break}if(!a)break;p[g]=b.join("")}else{a=!1;break}}if(!a)break;c[d]=p}else{a=!1;break}}if(a)return l[i]=c,l}}return null},Gi=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!Ee(e.whenCondition,o,r,n))return;let i=Ki(e,t,r,n);if(i!==null)return i;if(e.fast){let a={};for(let u of e.properties){let d=u.parsedKey?$(u.parsedKey,t,r,n):u.key,f=u.value;if(f.type===m.LITERAL)a[d]=f.value;else if(f.type===m.VARIABLE)a[d]=H(f.path,r,n);else if(f.type===m.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=H(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=$(h,t,r,n);p.push(g!=null?String(g):"")}a[d]=p.join("")}else a[d]=$(f,t,r,n)}return a}let s={},l=null,c=!1;for(let a of e.properties)if(!a.key.startsWith("$if ")&&!a.key.match(/^\$if\s+\w+.*:?$/)&&!a.key.startsWith("$elif")&&!a.key.startsWith("$else")&&!a.key.startsWith("$for ")){c=!0;break}for(let a of e.properties)if(a.key.startsWith("$if ")||a.key.match(/^\$if\s+\w+.*:?$/)){let u=$(a.value,t,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(a.key.startsWith("$for ")){if(e.properties.length===1)return $(a.value,t,r,n)}else{let u=a.value;if(u&&u.type===m.OBJECT&&u.properties){let d=u.properties.find(f=>f.key.startsWith("$for "));if(d){let f=$(d.value,t,r,n);f!==void 0&&(s[a.key]=f)}else{let f=$(a.value,t,r,n);f!==void 0&&(s[a.key]=f)}}else{let d=a.parsedKey?$(a.parsedKey,t,r,n):a.key,f=$(a.value,t,r,n);f!==void 0&&(s[d]=f)}}return s},Pn={},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!==Pn&&s!==void 0&&o.push(s)}return o},Xi=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},c=t.functions||t;if(s&&!Ee(s,c,r,n))return;if(!l[o])throw new Q(`Partial '${o}' is not defined`);let a=n._partialStack||[];if(a.includes(o))throw new Q(`Circular partial reference detected: ${o}`);let u=l[o],d=r,f={...n,_partialStack:[...a,o]};if(n){d={...r};for(let p of Object.keys(n))p.startsWith("_")||(d[p]=n[p])}if(i){let p=$(i,t,r,n);d={...d,...p}}return $(u,t,d,f)},Qi=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],l=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(l.length>0)throw new Q(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return l.length>0&&(c+="."+l.join(".")),c};var ar=ji;var Zi=/\$\{([^}]*)\}/g,es=/#\{([^}]*)\}/g,Nn=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=ts(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},ts=(e,t={})=>e.trim()?rs(e).map(n=>ns(n.trim(),t)):[],rs=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],c=s>0?e[s-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,r+=l):o&&l===i&&c!=="\\"?(o=!1,i="",r+=l):!o&&l==="("?(n++,r+=l):!o&&l===")"?(n--,r+=l):!o&&l===","&&n===0?(t.push(r),r=""):r+=l}return r&&t.push(r),t},ns=(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=Nn(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:l,type:c}of o){let a=0;for(;a<n.length;){let u=Pe(n.substring(a),l);if(u===-1)break;let d=a+u;d>i&&(i=d,s={op:l,type:c}),a=d+l.length}}if(i!==-1)try{return K(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},Vn=/^\w+\(.*\)$/,os=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,is=e=>{if(!(!e||e.trim()===""||Vn.test(e))&&os.test(e))throw e.includes("?")&&e.includes(":")?new w(`Complex expressions not supported in variable replacements - consider calculating the value in your data instead. Offending expression: "${e}"`):e.includes("||")||e.includes("&&")||e.includes("??")?new w(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new w(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Tn=e=>{let t=e.trim();if(Vn.test(t))throw new w(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new w(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new w(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new w(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("?")&&t.includes(":"))throw new w(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:m.PATH_REFERENCE,path:t}},tt=(e,t={})=>{let r=e.trim();is(r);let n=Nn(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}},cr=(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,(a,u)=>{let d=`__ESCAPED_${n.length}__`;return n.push(u),d}),r=r.replace(/\\(#\{[^}]*\})/g,(a,u)=>{let d=`__ESCAPED_${n.length}__`;return n.push(u),d}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(Zi)],i=[...r.matchAll(es)],s=[...o.map(a=>({match:a,type:"variable"})),...i.map(a=>({match:a,type:"pathref"}))].sort((a,u)=>a.match.index-u.match.index);if(s.length===0){let a=r;for(let u=0;u<n.length;u++)a=a.replace(`__ESCAPED_${u}__`,n[u]);return{type:m.LITERAL,value:a}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:a,type:u}=s[0];try{return u==="variable"?tt(a[1],t):Tn(a[1])}catch(d){if(d.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw d}}let l=[],c=0;for(let{match:a,type:u}of s){let[d,f]=a,p=a.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&&l.push(h)}try{let h;u==="variable"?h=tt(f.trim(),t):h=Tn(f.trim()),l.push(h)}catch(h){if(h.message==="Invalid array index syntax")l.push(d);else throw h}c=p+d.length}if(c<r.length){let a=r.substring(c);for(let u=0;u<n.length;u++)a=a.replace(`__ESCAPED_${u}__`,n[u]);a&&l.push(a)}return{type:m.INTERPOLATION,parts:l}};var dr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Fn=e=>Object.keys(e),J=e=>e.join("."),ve=(e,t,r)=>{let n=Fn(e).filter(o=>!t.has(o));if(n.length>0)throw new w(`Unexpected key '${n[0]}' in condition JSON at '${J(r)}'`)},xe=(e,t)=>typeof e=="string"?cr(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?as(e,t):cs(e,t):{type:m.LITERAL,value:e},ss=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new w("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new w("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new w("Empty $each body not allowed");if(r.$partial!==void 0)throw new w("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${n}`]:r}},as=(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=ss(i),a=Object.keys(c);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let u=Mn(a[0],c[a[0]],t,!0);r.push(u),n=!0;continue}}catch(c){throw c instanceof w?c:new w(c.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let c=Mn(l[0],i[l[0]],t);r.push(c),n=!0;continue}}let s=xe(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}},cs=(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 w("$partial value must be a string");if(e.$partial.trim()==="")throw new w("$partial value cannot be an empty string");let c=["$if","$elif","$else","$for"],a=[];for(let[b]of i)for(let A of c)if(b===A||b.startsWith(A+" ")||b.startsWith(A+"#")){a.push(A);break}if(a.length>0)throw new w(`Cannot use $partial with ${a.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:d,...f}=e,p={},h=!1;for(let[b,A]of Object.entries(f)){let x=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(x=b.slice(1)),p[x]=A,h=!0}let g=null;if(h&&(g=xe(p,t),g.type===m.OBJECT)){let b=!1;for(let A of g.properties)if(A.value.type===m.VARIABLE||A.value.type===m.INTERPOLATION||A.value.type===m.FUNCTION||A.value.type===m.CONDITIONAL||A.value.type===m.OBJECT&&!A.value.fast||A.value.type===m.ARRAY&&!A.value.fast){b=!0;break}b&&(g.fast=!1)}let y={type:m.PARTIAL,name:u,data:g};return d!==void 0&&(y.whenCondition=jn(d,t)),y}for(let[c,a]of i)if(c==="$when"){if(o!==null)throw new w("Multiple '$when' directives on the same object are not allowed");if(a==null)throw new w("Missing condition expression after '$when'");o=jn(a,t),n=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new w("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[c,a]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new w("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=ls(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]||"",d=u?`:${u}`:"";throw new w(`$for loops must be inside arrays - use '- $for${d} item in items:' instead of '$for${d} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(c.startsWith("$elif ")||c.startsWith("$else"))throw new w(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new w("Missing condition expression after '$if'");{let u=xe(a,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 d=cr(c,t),f={key:c,value:u};(d.type!==m.LITERAL||d.value!==c)&&(f.parsedKey=d),r.push(f),s++}}}let l={type:m.OBJECT,properties:r,fast:!n};return o&&(l.whenCondition=o),l},ls=(e,t,r={})=>{let n=[],o=[],i=t,[s,l]=e[i],c=null,a;if(s.startsWith("$if#")){let d=s.match(/^\$if#(\w+)\s+(.+)$/);if(d)c=d[1],a=d[2];else throw new w(`Invalid conditional syntax: ${s}`)}else a=s.substring(4),a.endsWith(":")&&(a=a.slice(0,-1).trim());sr(a);let u=K(a,r);for(n.push(u),o.push(xe(l,r)),i++;i<e.length;){let[d,f]=e[i],p=!1,h;if(c?d.startsWith(`$elif#${c} `)?(h=d.substring(`$elif#${c} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(d===`$else#${c}`||d===`$else#${c}:`)&&(p=!0,h=null):d.startsWith("$elif ")?(h=d.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(d==="$else"||d==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{sr(h);let g=K(h,r);n.push(g)}if(o.push(xe(f,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:c},nextIndex:i}},lr={eq:L.EQ,neq:L.NEQ,gt:L.GT,gte:L.GTE,lt:L.LT,lte:L.LTE,in:L.IN,add:L.ADD,sub:L.SUBTRACT},ur={all:L.AND,any:L.OR},us=new Set(["var","literal","call","not",...Object.keys(lr),...Object.keys(ur)]),ds=(e,t,r)=>{if(!Array.isArray(e))throw new w(`Condition JSON operator '${t}' at '${J(r)}' requires an array`);if(e.length!==2)throw new w(`Condition JSON operator '${t}' at '${J(r)}' requires exactly 2 operands`);return e},fs=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new w(`Condition JSON operator '${t}' at '${J(o)}' requires an array`);if(e.length===0)throw new w(`Condition JSON operator '${t}' at '${J(o)}' requires at least 1 condition`);return e.map((s,l)=>ge(s,n,[...o,l])).reduce((s,l)=>({type:m.BINARY,op:r,left:s,right:l}))},ps=(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(dr(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 w(`Condition JSON call at '${J(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new w(`Condition JSON call at '${J(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new w(`Invalid condition JSON function name '${n}' at '${J(r)}'`);if(!Array.isArray(o))throw new w(`Condition JSON call '${n}' at '${J(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>ge(i,t,[...r,"args",s]))}},ge=(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 w(`Condition JSON array at '${J(r)}' must be wrapped in an operator or { literal: [...] }`);if(!dr(e))throw new w(`Invalid condition JSON value at '${J(r)}'`);let n=Fn(e);if(n.length===0)throw new w(`Condition JSON object at '${J(r)}' must contain an operator`);let o=n.filter(s=>us.has(s));if(o.length===0)throw new w(`Unknown condition JSON operator '${n[0]}' at '${J(r)}'`);if(o.length>1)throw new w(`Condition JSON at '${J(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 w(`Condition JSON var at '${J(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 ps(e,t,r);if(i==="not")return ve(e,new Set(["not"]),r),{type:m.UNARY,op:ze.NOT,operand:ge(e.not,t,[...r,"not"])};if(i in ur)return ve(e,new Set([i]),r),fs(e[i],i,ur[i],t,[...r,i]);if(i in lr){ve(e,new Set([i]),r);let s=ds(e[i],i,[...r,i]);return{type:m.BINARY,op:lr[i],left:ge(s[0],t,[...r,i,0]),right:ge(s[1],t,[...r,i,1])}}throw new w(`Unknown condition JSON operator '${i}' at '${J(r)}'`)},jn=(e,t={})=>{if(e==null)throw new w("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new w("Empty condition expression after '$when'");return K(e,t)}return dr(e)||Array.isArray(e)?ge(e,t):{type:m.LITERAL,value:e}},K=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let a=e.slice(1,-1),u=0,d=!0;for(let f=0;f<a.length;f++)if(a[f]==="("?u++:a[f]===")"&&u--,u<0){d=!1;break}if(d&&u===0)return K(a,t)}let r=Pe(e,"||");if(r!==-1)return{type:m.BINARY,op:L.OR,left:K(e.substring(0,r).trim(),t),right:K(e.substring(r+2).trim(),t)};let n=Pe(e,"&&");if(n!==-1)return{type:m.BINARY,op:L.AND,left:K(e.substring(0,n).trim(),t),right:K(e.substring(n+2).trim(),t)};let o=[{op:">=",type:L.GTE},{op:"<=",type:L.LTE},{op:"==",type:L.EQ},{op:"!=",type:L.NEQ},{op:">",type:L.GT},{op:"<",type:L.LT},{op:" in ",type:L.IN}];for(let{op:a,type:u}of o){let d=Pe(e,a);if(d!==-1)return{type:m.BINARY,op:u,left:K(e.substring(0,d).trim(),t),right:K(e.substring(d+a.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:L.ADD},{op:" - ",type:L.SUBTRACT}];for(let{op:a,type:u}of l){let d=0;for(;d<e.length;){let f=Pe(e.substring(d),a);if(f===-1)break;let p=d+f;p>i&&(i=p,s={op:a,type:u}),d=p+a.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:K(e.substring(0,i).trim(),t),right:K(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let a of c)if(Pe(e,a)!==-1)throw new w(`Arithmetic operations are not allowed in conditionals: "${a}"`);return e.startsWith("!")?{type:m.UNARY,op:ze.NOT,operand:K(e.substring(1).trim(),t)}:Un(e,t)},Pe=(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},hs=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}},Un=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return tt(r,t);let o=hs(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return tt(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},ms=(e,t=!1)=>{let r=t?"$each":"$for";try{_n(e)}catch(n){if(n instanceof w&&t){let o=n.message.replace(/\$for/g,"$each");throw new w(o.replace("Parse Error: ",""))}throw n}},Mn=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new w(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],l=i[2].trim();ms(l,n);let c=l.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let y=n?"$each":"$for";throw new w(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${l}')`)}let a=c[1].trim(),u=c[2].trim(),d,f=null;if(a.includes(",")){let y=a.split(",").map(b=>b.trim());if(y.length!==2)throw new w(`Invalid loop variables: ${a}. Expected format: "item" or "item, index"`);d=y[0],f=y[1]}else d=a;let p=["this","undefined","null","true","false"];if(p.includes(d))throw new w(`Reserved variable name: ${d}`);if(f&&p.includes(f))throw new w(`Reserved variable name: ${f}`);let h=Un(u,r),g=xe(t,r);return{type:m.LOOP,itemVar:d,indexVar:f,iterable:h,body:g,flatten:s!=="nested"}};var gs=(e,t={})=>{let{functions:r={}}=t;return xe(e,r)},xt=gs;var rt={};Ri(rt,{now:()=>ys});var ys=()=>Date.now();var bs=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...rt,...n},s=xt(e,{functions:i}),l={};for(let[c,a]of Object.entries(o))l[c]=xt(a,{functions:i});return ar(s,t,{functions:i,partials:l})},ee=bs;var Is=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",As=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,ws=(e,t)=>{if(Is(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new w("Empty condition expression");return K(e,t)}return ge(e,t)},Es=(e,t={},r={})=>{let n=As(r),o={...rt,...n},i=ws(e,o);return!!Ee(i,{functions:o,partials:{}},t,{})},fr=Es;var ot=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return fr(e,t)},Hn=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:l=c=>c}=r;for(let[c,a]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>a(s(n),...u):i[c]=(...u)=>{let d;return n=ir(n,p=>{let h=a(l(p),...u);d=h!==void 0&&!re(h)?h:void 0}),d});return{...o,...i}},_t=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return ir(n,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var vs=(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{}}},le=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),nt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Kn=e=>{let t=re(e)?De(e):e;return structuredClone(t)},Ce=e=>le(e,"computed"),We=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Ce(t[r]))),xs=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),pr=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},Cs=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=xs(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 pr(s,i)}return n==="runtime"?pr(t.runtime,r.slice(1)):pr(t,r)},Ss=(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)`)},Bn=(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`)},_s=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},ce=(e,t,r,n)=>(Ss(e,t,n),t.map(o=>St(o,r))),se=(e,t,r,n)=>{let o=ce(e,t,r,n);return o.forEach(i=>_s(e,i)),o},Rs=(e,t,r)=>{switch(e){case"var":return Cs(t,r);case"add":{let[n,o]=se(e,t,r,2);return n+o}case"sub":{let[n,o]=se(e,t,r,2);return n-o}case"mul":{let[n,o]=se(e,t,r,2);return n*o}case"div":{let[n,o]=se(e,t,r,2);return n/o}case"mod":{let[n,o]=se(e,t,r,2);return n%o}case"neg":{let[n]=se(e,t,r,1);return-n}case"round":{let[n]=se(e,t,r,1);return Math.round(n)}case"floor":{let[n]=se(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=se(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=se(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=se(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=se(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=ce(e,t,r,2);return n==o}case"neq":{let[n,o]=ce(e,t,r,2);return n!=o}case"gt":{let[n,o]=ce(e,t,r,2);return n>o}case"gte":{let[n,o]=ce(e,t,r,2);return n>=o}case"lt":{let[n,o]=ce(e,t,r,2);return n<o}case"lte":{let[n,o]=ce(e,t,r,2);return n<=o}case"in":{let[n,o]=ce(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return Bn(e,t),t.every(n=>!!St(n,r));case"or":case"any":return Bn(e,t),t.some(n=>!!St(n,r));case"not":{let[n]=ce(e,t,r,1);return!n}case"length":{let[n]=ce(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:nt(n)?Object.keys(n).length:0}case"includes":{let[n,o]=ce(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return Kn(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},St=(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 Rs(n,o,t)},Os=(e,t={})=>ot(e,{variables:t.variables,runtime:t.runtime}),Ls=(e,t)=>{if(!nt(e))throw new Error(`${t} must be an object`);let r=le(e,"expr"),n=le(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},hr=(e,t,r)=>(Ls(e,t),le(e,"value")?Kn(e.value):St(e.expr,r)),$s=(e,t={},r="unknown")=>{if(!nt(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=le(e,"expr"),o=le(e,"value");if(le(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(!nt(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let l=e.branches[s];if(!nt(l))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!le(l,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(Os(l.when,t))return hr(l,`Computed variable "${r}" branch ${s}`,t)}return hr(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 hr(e,`Computed variable "${r}"`,t)},ks=(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}`)}},Rt=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=We(e,r),i=Object.entries(r).filter(([,d])=>Ce(d)).map(([d])=>d),s={},l=[],c=d=>{if(le(s,d))return s[d];let f=r[d];if(!Ce(f))return o[d];let p=l.indexOf(d);if(p>=0){let h=[...l.slice(p),d].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}l.push(d);try{let h=$s(f.computed,u,d);return ks(d,f.type,h),s[d]=h,h}finally{l.pop()}},a=new Proxy({},{get:(d,f)=>{if(typeof f=="string")return c(f)},has:(d,f)=>typeof f=="string"&&(le(o,f)||i.includes(f)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(d,f)=>{if(!(typeof f!="string"||!le(o,f)&&!i.includes(f)))return{enumerable:!0,configurable:!0}}}),u={variables:a,runtime:t,resolveVariable:c};return n?(i.forEach(d=>{c(d)}),{...o,...s}):a},Ds=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>Rt({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),yr=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(Ce(o))return;let i=vs(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},Ot=(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(", ")}`)},Lt=(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(", ")}`)},Ps=2,zn=12,Gn=(e=Ps)=>{if(!Number.isInteger(e)||e<0||e>zn)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${zn}.`);return e},Ts=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},Ct=e=>typeof e=="number"&&Number.isFinite(e),br=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!Ct(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!Ct(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!Ct(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}".`);Gn(o.roundTo)}}},$t=(e,t,r,n={})=>{let o=(s,l,c)=>{let a=s??l;if(!Ct(a))throw new Error(`Operation "${t}" requires ${c} to be a number.`);return a},i=s=>{let l=o(s,void 0,"value");if(l===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return l};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return Ts(o(e,0,"current value")/i(r),Gn(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 Jn=(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()))},Ns=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let l=i.character?.sprite;return l&&Object.keys(l).length>0&&(s.sprite=l),Object.keys(s).length>0?s:void 0},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},Wn=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},qn=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},Yn=(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,Vs=(e,t)=>{let r={},n=Yn(Wn(e),Wn(t)),o=Yn(qn(e),qn(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},Ir=(e={},t={})=>{let r={},n=["sfx","voice"],o=l=>{let c=e[l],a=t[l];a&&!c?r[l]={changeType:"add",data:a}:c&&!a?n.includes(l)||(r[l]={changeType:"delete",data:c}):c&&a&&JSON.stringify(c)!==JSON.stringify(a)&&(r[l]={changeType:"update",data:a})},i=Vs(e.background,t.background);i&&(r.background=i),o("bgm"),o("voice");let s=Ns(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},Ar=(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(l=>{let c={...l};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},js=(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},Ms=(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=js(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},Fs={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"])},Xn=(e,t)=>{let r=e[e.length-1];return r?Fs[r]?.has(t)===!0:!1},mr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>mr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Xn(r,n)?o:mr(o,t,[...r,n])])):Ms(e,t),gr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>gr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Xn(r,n)?o:gr(o,t,[...r,n])])):typeof e=="string"?ee(e,t):e,wr=(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=mr(e,t._event);return gr(r,t)};var ue=e=>structuredClone(re(e)?De(e):e),it=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:ue(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},eo=(e,t)=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let r=e.map(n=>ue(n)).filter(n=>t(n)||n.animations);return{hasValidItems:r.length>0,processedItems:r}},oe=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Qn=e=>e?.animations?.playback?.continuity==="persistent",ye=(e,t)=>oe(e??{},t)&&e[t]!==void 0,Us=e=>{if(e){if(e.character&&oe(e.character,"name"))return e.character.name;if(oe(e,"characterName"))return e.characterName}},to=e=>!!e?.character&&oe(e.character,"sprite"),Bs=e=>{let t={},r=!1,n=Us(e);return n!==void 0&&(t.name=n,r=!0),to(e)&&(t.sprite=ue(e.character.sprite),r=!0),r?t:void 0},Zn=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},zs=({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=>ue(o)):delete e.initialRevealedContent,e.content=[...n,...t]},Ws=()=>({}),qs=(e,t)=>{if(t.background){let r=ye(t.background,"resourceId"),n=ye(t.background,"colorId"),o=ye(t.background,"opacity"),i=ye(t.background,"blur"),{animationsOnly:s,state:l}=it(t.background,u=>ye(u,"resourceId")||ye(u,"colorId")||ye(u,"opacity")||ye(u,"blur"));if(s){e.background=e.background?{...ue(e.background),...l}:l;return}if(!r&&!n&&!o&&!i){delete e.background;return}let c=e.background,a=ue(t.background);if(!r&&c?.resourceId&&(a.resourceId=c.resourceId,!oe(a,"transformId")&&c.transformId&&(a.transformId=c.transformId)),!n&&c?.colorId&&(a.colorId=c.colorId),!o&&ye(c,"opacity")&&(a.opacity=c.opacity),!i&&ye(c,"blur")&&(a.blur=ue(c.blur)),oe(a,"resourceId")&&a.resourceId===void 0&&delete a.resourceId,oe(a,"colorId")&&a.colorId===void 0&&delete a.colorId,oe(a,"animations")&&a.animations===void 0&&delete a.animations,oe(a,"opacity")&&a.opacity===void 0&&delete a.opacity,oe(a,"blur")&&a.blur===void 0&&delete a.blur,!a.resourceId&&!a.colorId){delete e.background;return}c?.resourceId===a.resourceId&&c?.transformId===a.transformId&&!oe(a,"animations")&&Qn(c)&&(a.animations=ue(c.animations)),e.background=a}else e.background?.animations&&!Qn(e.background)&&(e.background.animations={})},Ys=(e,t)=>{if(!t.dialogue){e.dialogue&&(Zn(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:a,state:u}=it(t.dialogue.ui,d=>!!d.resourceId);a?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&&zs({dialogueState:e.dialogue,content:t.dialogue.content,append:n});let o=oe(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=oe(t.dialogue,"characterId"),s=Bs(t.dialogue),l=s!==void 0,c=to(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,l?e.dialogue.character=!i&&o&&e.dialogue.character?{...ue(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,c||Zn(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let a={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(a.character=ue(e.dialogue.character)),e.dialogue.lines.push(a)}},Hs=(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},Ks=(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}}},Gs=(e,t)=>{if(t.visual){let{hasValidItems:r,processedItems:n}=eo(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))},Js=(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}=eo(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);r?e.character={items:n}:delete e.character},Xs=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Qs=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=it(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},Zs=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=it(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},ea=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=it(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=ue(t.form)}else e.form&&delete e.form},ta=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},ra=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},na=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},Te=e=>_t(Ws,[na,qs,Hs,Ks,Gs,Ys,Js,Xs,Qs,Zs,ea,ta,ra])(e);var oa=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"}}),Ne=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),st=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),ro=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"}),Er=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),vr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),ia=(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]}},qe=e=>Object.fromEntries(Object.entries(oa).map(([t,r])=>{let n=ia(e,r.source),o=n!==void 0?n:Ne[t]??st[t];return[t,o]})),Ae=(e,t)=>qe(e)[t],no=(e={})=>Object.fromEntries(Er.map(t=>[t,e[t]??Ne[t]]));var at=Object.freeze({VISUAL_BEHIND_BACKGROUND:10,BACKGROUND:20,VISUAL_BEHIND_CHARACTER:30,CHARACTER:40,VISUAL_BEHIND_DIALOGUE:50,DIALOGUE:60,VISUAL_FOREGROUND:70}),Se=Object.freeze({BEHIND_BACKGROUND:at.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:at.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:at.VISUAL_BEHIND_DIALOGUE,FOREGROUND:at.VISUAL_FOREGROUND}),xr=Se.BEHIND_DIALOGUE,Cr=Object.freeze(Object.values(Se).sort((e,t)=>e-t));var _e={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:Jn},sa=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,aa=(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},Dt=(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),l=sa.exec(s);if(l){let[,c,a,u]=l,d=aa(t,u);if(!Array.isArray(d))continue;let f=Array.isArray(i[s])?i[s]:[];d.forEach((p,h)=>{let g={...t,[c]:p};a&&(g[a]=h),f.forEach(y=>{let b=Dt(y,g,r),A=ee(b,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(Dt(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=Dt(i,t,r)}),n},Br=({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".`)},ca=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);return Br({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},la=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Br({animationType:e.type,animationId:t,animationPath:r}),e.type},ua=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},da=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},yo=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),bo=e=>e?.playback?.continuity==="persistent",$r=e=>Array.isArray(e)?e.map($r):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=$r(e[r]),t),{}),Pt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify($r(t))},Io=(e=[])=>e.filter(t=>bo(t)).map(t=>structuredClone(t)),Ao=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,Sr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,Ao(r)),0),wo=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(Sr(e.tween),Sr(e.prev?.tween),Sr(e.next?.tween),Ao(e.mask?.progress)),oo=({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(Pt).filter(Boolean));return e.some(n=>{if(!bo(n))return!1;let o=Pt(n);return o?r.has(o):!1})},de=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||oo({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:oo({animationInstances:e,activePersistentAnimations:o}),fa=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),pa=(e,t)=>{if(fa(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},ha=({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?ca({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},ma=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Br({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},zr=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(ma(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},kr=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=ee(e,t);return r&&typeof r=="object"?e:r},Dr=(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},ga=({content:e,path:t,variables:r})=>Dr(e,t).reduce((n,o)=>{let i=kr(o.text,{variables:r});return n+`${i??""}`.length},0),io=(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))},kt=(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("-")}`},_r=(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},ya=(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},ba=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},Pr=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Ia=(e={})=>e.textStyles||{},Aa=(e={})=>e.images||{},wa=(e={})=>e.colors||{},Ea=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,ct=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,He=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},so=(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},Wr=(e,t)=>{if(typeof e!="string"||!Ea.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},ao=(e,t,r)=>{let n=Wr(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})`},va=(e={},t)=>{let r=Ia(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=so(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:ao(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 l=e.colors?.[r.strokeColorId];if(!l)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let c=so(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=ao(l.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},Tr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Tr(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]=Tr(i,t,ct(r,o)));return e.textStyleId!==void 0&&(He(e.textStyleId,r,"textStyleId"),n.textStyle=va(t,e.textStyleId)),n},qr=(e={},t)=>{let r=wa(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return Wr(r.hex,`Color "${t}"`)},Eo=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Rr=(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 ${Eo(`${t}.fill`)} instead`)},xa=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>lt(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]=lt(i,t,ct(r,o)));return e.colorId!==void 0&&(He(e.colorId,r,"colorId"),n.fill=qr(t,e.colorId)),n},lt=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>lt(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 ${Eo("fill")} instead`);Rr(e,"hover",r),Rr(e,"click",r),Rr(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]=xa(i,t,ct(r,o));continue}n[o]=lt(i,t,ct(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(He(e.colorId,r,"colorId"),n.fill=qr(t,e.colorId)),n},Or=(e={},t)=>{let r=Aa(e)?.[t];return r||null},vo=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",co=(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 ${vo(`${t}.${n}`)} instead`)},lo=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},Nr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Nr(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 ${vo(o)} instead`);co(e,"hover",r,"src"),co(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]=Nr(i,t,ct(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){He(e.imageId,r,"imageId");let o=Or(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&&(He(e.hoverImageId,r,"hoverImageId"),lo(n,"hover",Or(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(He(e.clickImageId,r,"clickImageId"),lo(n,"click",Or(t,e.clickImageId)?.fileId??e.clickImageId)),n},Yr=(e,t={},r="root")=>Nr(lt(Tr(e,t,r),t,r),t,r),Re=Yr,Ke=(e=[])=>e.find(t=>t.id==="story"),Ca="#000000",Vr="bg-cg-background-color",Sa=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?Wr(r?.backgroundColor??Ca,"screen.backgroundColor"):qr(e,t.colorId),xo=(e={})=>{if(yo(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},_a=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},uo=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=xo(e),n=_a(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},Ra=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:Vr,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:Sa({resources:e,background:t,screen:r})};if(n){let i=xo(t);i!==void 0&&(o.alpha=i)}return o},Oa=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.layouts?.[t]):!1,fo=({resources:e={},resourceId:t,colorId:r})=>{let n=ba(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:Pr({resourceId:t,kind:n})}:r!==void 0?{resourceId:Vr,targetId:Vr}:{resourceId:void 0,targetId:void 0}},Co=100,Nt=Co,So=(e,t)=>e*t/Co,La=(e={},t=Nt)=>e?.muteAll?0:So(t,e?.soundVolume??Ne.soundVolume),$a=(e={},t=Nt)=>e?.muteAll?0:So(t,e?.musicVolume??Ne.musicVolume),ka=({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:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,confirmDialog:d,form:f,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:b}={})=>{let A={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??l??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},x=Va({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e}),S={variables:e,runtime:A,saveSlots:r,isChoiceVisible:c,isFormVisible:a,canRollback:u,confirmDialog:d,form:f,historyDialogue:p,characters:h};return x&&(S.dialogue=x,S.dialogueLines=x.lines),S},po=100,Tt=(e,t)=>{if(Array.isArray(e))return e.map(n=>Tt(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=Tt(r[n],t)}),r.type==="text-revealing"?t(r):r},Da=e=>Tt(e,t=>({...t,revealEffect:"none"})),Pa=e=>Tt(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,po):po;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),Oe=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?Da(e):r?Pa(e):e,_o=({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:{}}}}),jr=e=>{if(Array.isArray(e))return e.map(jr);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=jr(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}}:{}}}}},Ta=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),ho=(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}}}},Mr=(e,t)=>{if(Array.isArray(e))return e.map(i=>Mr(i,t));if(!e||typeof e!="object")return e;let r={};for(let[i,s]of Object.entries(e))r[i]=Mr(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:ho(r.change,o),submit:ho(r.submit,t.submitActions)}},Fr=(e,t)=>{if(Array.isArray(e))return e.map(n=>Fr(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Fr(o,t);for(let n of Ta){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},Ur=({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}},Ro=(e=[],t={})=>e.map(r=>{let n=Ur({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}}),Na=e=>!(!e||e.mode==="adv"&&e.content===void 0),Va=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n}={})=>{if(!t&&!Na(e))return;let o=e.content===void 0?[{text:""}]:Dr(e.content,"dialogue.content"),i=e.content===void 0?0:ga({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),s=(e.lines||[]).map((c,a)=>{let u=Dr(c.content,`dialogue.lines[${a}].content`),d=Ur({characterId:c.characterId,character:c.character,characterName:c.characterName,characters:r});return{...c,content:u.map(f=>({...f,text:kr(f.text,{variables:n})})),character:d,characterName:d.name}}),l=Ur({characterId:e.characterId,character:e.character,characters:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:l,content:o.map(c=>({...c,text:kr(c.text,{variables:n})})),initialRevealedCharacters:i,lines:s}},Oo=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=ee(e,r,{functions:_e});return Re(Oe(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},Lr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),mo=({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:Lr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:Lr(o.keyup)});return}e[n]={...i,[r]:{payload:Lr(o)}}})},ja=(e={},t={})=>{let r={};return mo({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),mo({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},we=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l})=>{if(!e)return[];let c=[],a=({instanceId:b,targetId:A})=>{let x=ha({resources:t,animationId:p,playback:h,instanceId:b,targetId:A,animationPath:s});x&&c.push(x)},u=r!=null&&r!==!1,d=n!=null&&n!==!1,f=o&&i&&o===i;pa(e,s);let p=ua(e),h=da(e),g=t?.animations?.[p],y=la(g,{animationId:p,animationPath:s});if(y==="update")return d&&i?a({instanceId:`${l}-animation-update`,targetId:i}):u&&o&&a({instanceId:`${l}-animation-update`,targetId:o}),c;if(y==="transition"){let b=`${l}-animation-transition`,A=h?.continuity==="persistent"?b:`${l}-animation-in`;if(u&&d&&f)return a({instanceId:b,targetId:i}),c;u&&a({instanceId:`${l}-animation-out`,targetId:o}),d&&a({instanceId:A,targetId:i})}return c},Ma=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Fa=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:c,runtime:a,activePersistentAnimations:u,restoredPersistentAnimations:d,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,saveSlots:A=[]})=>{let{elements:x,animations:S}=e;if(t.background){let T=n===void 0?!0:yo(n?.background??{},"animations"),E=x.find(z=>z.id==="story");if(!E)return e;let N=ya(o,t.background),B=r?.background?.resourceId,k=r?.background?.colorId,j=t.background.resourceId??(t.background.animations?B:void 0),F=t.background.colorId??(t.background.animations?k:void 0),M=Oa(o,j),q={...t.background,colorId:F};if((F!==void 0||M)&&E.children.push(Ra({resources:o,background:q,screen:i,includeOpacity:!M})),j){let{images:z={},videos:Y={}}=o,V=z[j]||Y[j];if(V){let he=Y[j]!==void 0,Z={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...N},Ue={id:Pr({resourceId:j,kind:he?"video":"sprite"}),type:he?"video":"sprite",x:Z.x,y:Z.y,src:V.fileId,width:V.width,height:V.height,...uo(t.background,{includeDefaultAlpha:!0}),anchorX:Z.anchorX,anchorY:Z.anchorY,rotation:Z.rotation,scaleX:Z.scaleX,scaleY:Z.scaleY};he&&(Ue.loop=t.background.loop??!1,Ue.volume=V.volume??50),E.children.push(Ue)}}if(j){let{layouts:z={}}=o,Y=z[j];if(Y){let V={id:Pr({resourceId:j,kind:"container"}),type:"container",children:Y.elements,...uo(t.background)};N&&Object.assign(V,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...N});let he=ee(V,fe({variables:c,runtime:a,saveSlots:A,dialogueState:t.dialogue,isLineCompleted:s,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,characters:o.characters||{},skipTransitionsAndAnimations:l}),{functions:_e});E.children.push(Re(Oe(he,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:l}),o))}}let v=fo({resources:o,resourceId:B,colorId:k}),_=fo({resources:o,resourceId:j,colorId:F}),R=we({animationsDef:t.background.animations,resources:o,previousResourceId:v.resourceId,currentResourceId:_.resourceId,previousTargetId:v.targetId,currentTargetId:_.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});de({animationInstances:R,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:u,restoredPersistentAnimations:d,isAuthoredOnCurrentLine:T})&&S.push(...R)}return e},Ua=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:c}=e;if(t.character&&n){let a=l.find(h=>h.id==="story");if(!a)return e;let u=t.character.items||[],d=r?.character?.items||[],f=io(u),p=io(d);for(let h=0;h<u.length;h++){let g=u[h],{transformId:y,sprites:b}=g,A=d.find(F=>F.id===g.id),x=d.findIndex(F=>F.id===g.id),S=A?.sprites&&A.sprites.length>0,T=b&&b.length>0,E=x>=0?kt(A,x,p):void 0,N=we({animationsDef:g.animations,resources:n,previousResourceId:E,currentResourceId:T?kt(g,h,f):void 0,previousTargetId:E,currentTargetId:T?kt(g,h,f):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&S&&de({animationInstances:N,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){c.push(...N);continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let B=kt(g,h,f),k=n.transforms[y];if(!k){console.warn("Transform not found:",y);continue}let j={type:"container",id:B,x:g.x??k.x,y:g.y??k.y,anchorX:k.anchorX,anchorY:k.anchorY,rotation:k.rotation,scaleX:k.scaleX,scaleY:k.scaleY,children:[]};for(let F of b){let M=n.images[F.resourceId];if(!M){console.warn(`Image resource not found: ${F.resourceId}`);continue}j.children.push({type:"sprite",id:`${B}-${F.id}`,src:M.fileId,width:M.width,height:M.height,x:0,y:0})}a.children.push(j),de({animationInstances:N,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...N)}}return e},Lo=(e,t)=>{if(!Cr.includes(e))throw new Error(`${t} must be one of: ${Cr.join(", ")}.`)},Ba=(e,t)=>{let r=e.layer??(e.resourceId?void 0:t?.layer)??xr;return Lo(r,`Visual item "${e.id}" layer`),r},za=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:l,activePersistentAnimations:c,autoMode:a,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,saveSlots:g=[],visualLayer:y})=>{let{elements:b,animations:A}=e;if(t.visual&&n){let x=b.find(E=>E.id==="story");if(!x)return e;let S=t.visual.items,T=r?.visual?.items||[];y!==void 0&&Lo(y,"visualLayer");for(let E of S){let N=T.find(j=>j.id===E.id),B=Ba(E,N);if(y!==void 0&&B!==y)continue;if(E.resourceId){let{images:j={},videos:F={},spritesheets:M={}}=n,q=M[E.resourceId];if(q){let v=_r(n,E),_=E.animationName;if(_){let R=q.animations?.[_];if(!R)throw new Error(`Animation '${_}' not found in spritesheet resource '${E.resourceId}'`);let z={id:`visual-${E.id}`,type:"animated-sprite",x:E.x??v.x,y:E.y??v.y,width:E.width??q.width,height:E.height??q.height,alpha:E.alpha??1,anchorX:v.anchorX,anchorY:v.anchorY,rotation:v.rotation,scaleX:v.scaleX,scaleY:v.scaleY,spritesheetSrc:q.fileId,spritesheetData:q.jsonData,animation:{frames:R.frames,animationSpeed:E.animationSpeed??R.animationSpeed??.5,loop:E.loop??R.loop??!0}};x.children.push(structuredClone(z))}}else{let v=j[E.resourceId]||F[E.resourceId];if(v){let _=F[E.resourceId]!==void 0,R=_r(n,E),z={id:`visual-${E.id}`,type:_?"video":"sprite",src:v.fileId,width:v.width,height:v.height,x:R.x,y:R.y,anchorX:R.anchorX,anchorY:R.anchorY,rotation:R.rotation,scaleX:R.scaleX,scaleY:R.scaleY};_&&(z.loop=v.loop??!1,z.volume=v.volume??50),x.children.push(z)}}}if(E.resourceId){let{layouts:j={}}=n,F=j[E.resourceId];if(F){let M=_r(n,E),q={id:`visual-${E.id}`,type:"container",children:structuredClone(F.elements),x:M.x,y:M.y,anchorX:M.anchorX,anchorY:M.anchorY,rotation:M.rotation,scaleX:M.scaleX,scaleY:M.scaleY},v=ee(q,fe({variables:s,runtime:l,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:a,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i}),{functions:_e});x.children.push(Re(Oe(v,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),n))}}let k=we({animationsDef:E.animations,resources:n,previousResourceId:N?.resourceId,currentResourceId:E.resourceId,previousTargetId:N?.resourceId?`visual-${E.id}`:void 0,currentTargetId:E.resourceId?`visual-${E.id}`:void 0,animationPath:`visual.items[${E.id}].animations`,idPrefix:E.id});de({animationInstances:k,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:c})&&A.push(...k)}}return e},Ye="dialogue-character-sprite",go=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,Wa=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,c=Ke(e.elements);if(!c)return e;let a=t.dialogue?.character?.sprite,u=r?.dialogue?.character?.sprite,d=go(a),f=go(u),p=we({animationsDef:a?.animations,resources:n,previousResourceId:f?Ye:void 0,currentResourceId:d?Ye:void 0,previousTargetId:f?Ye:void 0,currentTargetId:d?Ye:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!d)return a?.animations&&f&&de({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e;let h=n.transforms?.[a.transformId];if(!h)return console.warn("Transform not found:",a.transformId),e;let g={type:"container",id:Ye,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 a.items){let b=n.images?.[y.resourceId];if(!b){console.warn(`Image resource not found: ${y.resourceId}`);continue}g.children.push({type:"sprite",id:`${Ye}-${y.id}`,src:b.fileId,width:b.width,height:b.height,x:0,y:0})}return c.children.push(g),de({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e},qa=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,skipOnlyViewedLines:d,isLineCompleted:f,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:y,saveSlots:b=[]})=>{let{elements:A,animations:x}=e;if(!t.dialogue||o)return e;let S=A.find(E=>E.id==="story");if(!S)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:E={}}=n,N=E[t.dialogue.ui.resourceId];if(N){let B={elements:N.elements},k=fe({variables:h,runtime:g,saveSlots:b,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:f,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:d,skipTransitionsAndAnimations:p}),j={functions:_e},F=Dt(B,k,j),M=ee(F,k,j),q=Re(Oe(M?.elements,{isLineCompleted:f,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(q))for(let v of q)S.children.push(v);else q&&S.children.push(q)}}Wa(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let T=we({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 de({animationInstances:T,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&x.push(...T),e},Ya=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:c,autoMode:a,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:b,animations:A}=e;if(t.choice&&n){let x=Ke(b);if(!x)return e;let S=n?.layouts[t.choice.resourceId];if(S&&S.elements){let E={elements:S.elements},N=ee(E,{...fe({variables:l,runtime:c,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:a,skipMode:u,isChoiceVisible:d??!!t.choice,isFormVisible:f,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:_e}),B=jr(Re(Oe(N?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n));if(Array.isArray(B))for(let k of B)x.children.push(k);else B&&x.children.push(B)}let T=we({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"});de({animationInstances:T,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&A.push(...T)}return e},Ha=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:c,autoMode:a,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:b,animations:A}=e;if(!y?.resourceId||!n)return e;let x=Ke(b);if(!x)return e;let S=n?.layouts?.[y.resourceId];if(!S)return console.warn(`Form layout not found: ${y.resourceId}`),e;let T={id:"form-container",type:"container",x:0,y:0,children:S.elements||[]},E={...fe({variables:l,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:a,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},N=ee(T,E,{functions:_e}),B=Fr(Re(Oe(Mr(N,y),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n),y);B&&x.children.push(B);let k=we({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 de({animationInstances:k,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(...k),e},Ka=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:d,saveSlots:f=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=ja(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=Ke(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(Oo({container:b,resources:r,templateData:fe({variables:n,runtime:o,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:d,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:l,skipTransitionsAndAnimations:p})),e},Ga=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Ke(i))return e;let c=r.sounds[t.bgm.resourceId];if(!c)return e;let a=fe({variables:o,runtime:n}).runtime;s.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:$a(a,t.bgm.volume??c.volume??Nt),startDelayMs:t.bgm.startDelayMs??null})}return e},Ja=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx.items;for(let[s,l]of i.entries()){let c=r.sounds?.[l.resourceId];c&&o.push({id:ka({item:l,index:s}),type:"sound",src:c.fileId,loop:l.loop??c.loop??!1,volume:La(n,l.volume??c.volume??Nt),startDelayMs:l.startDelayMs??c.startDelayMs??null})}}return e},Xa=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},Qa=(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 l=t.voice,{resourceId:c,loop:a,startDelayMs:u}=l,d=Xa(r,n,c);if(!d)return e;let f=fe({variables:i,runtime:o}).runtime;return s.push({id:`voice-${n}-${c}`,type:"sound",src:d.fileId,volume:Qa(l,f),loop:a??!1,startDelayMs:u??null}),e},ec=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:d,saveSlots:f=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:b}=e;if(t.layout){let T=Ke(y);if(!T)return e;let E=n.layouts[t.layout.resourceId];if(!E)return e;Array.isArray(E.transitions)&&!p&&!h&&zr({animations:b,transitions:E.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let N={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:E.elements||[]};T.children.push(Oo({container:N,resources:n,templateData:fe({variables:o,runtime:i,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:d,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:l,skipTransitionsAndAnimations:h}))}let A=r?.layout?.resourceId,x=t.layout?.resourceId,S=we({animationsDef:t.layout?.animations,resources:n,previousResourceId:A,currentResourceId:x,previousTargetId:A?`layout-${A}`:void 0,currentTargetId:x?`layout-${x}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return de({animationInstances:S,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(...S),e},tc=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,c=t?.screen?.animations;if(!c)return e;let a=r!=null,u=we({animationsDef:c,resources:n,previousResourceId:a?"story":void 0,currentResourceId:"story",previousTargetId:a?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return de({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...u),e},rc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,overlayStack:d=[],dialogueHistory:f=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;return d&&d.length>0&&d.forEach((x,S)=>{let T=r.layouts[x.resourceId];if(!T){console.warn(`Overlay layout not found: ${x.resourceId}`);return}Array.isArray(T.transitions)&&(y||zr({animations:A,transitions:T.transitions,defaultTargetId:`overlayStack-${S}`,idPrefix:`overlayStack-${S}`,animationPathPrefix:`overlayStack[${S}]`}));let E={id:`overlayStack-${S}`,type:"container",x:0,y:0,children:[_o({id:`overlayStack-${S}-blocker`,screen:h}),...T.elements||[]]},N=Ro(f,r.characters),B=fe({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,historyDialogue:N,characters:r.characters||{},skipTransitionsAndAnimations:y}),k=ee(E,B,{functions:_e}),[j,...F]=k.children||[],M=Re(Oe({...k,children:F},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...M,children:j?[j,...M.children||[]]:M.children})}),e},nc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:d,confirmDialog:f,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;if(!f?.resourceId)return e;let x=r.layouts?.[f.resourceId];if(!x)return console.warn(`ConfirmDialog layout not found: ${f.resourceId}`),e;Array.isArray(x.transitions)&&!y&&zr({animations:A,transitions:x.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let S={id:"confirmDialog",type:"container",x:0,y:0,children:[_o({id:"confirmDialog-blocker",screen:h}),...x.elements||[]]},T=Ro(p,r.characters),E=ee(S,fe({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:d,confirmDialog:f,historyDialogue:T,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:_e}),[N,...B]=E.children||[],k=Re(Oe({...E,children:B},{isLineCompleted:g,skipMode:l,skipTransitionsAndAnimations:y}),r);return b.push({...k,children:N?[N,...k.children||[]]:k.children}),e},Vt=e=>(t,r)=>za(t,{...r,visualLayer:e}),oc=Vt(Se.BEHIND_BACKGROUND),ic=Vt(Se.BEHIND_CHARACTER),sc=Vt(Se.BEHIND_DIALOGUE),ac=Vt(Se.FOREGROUND),$o=e=>_t(Ma,[Ka,oc,Fa,ic,Ua,sc,qa,Ya,Ha,ec,ac,tc,Ga,Ja,Za,rc,nc])(e);var jt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},No=1,Hr="choice",Mt="form",Bt=()=>({manual:{...jt.manual},auto:{...jt.auto},applyMode:jt.applyMode}),Kr=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...Bt()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},P=e=>{let t=re(e)?De(e):e;return structuredClone(t)},D=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),zt=e=>String(e),Vo=()=>({sections:[],resources:[]}),cc=e=>D(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Vo(),lc=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",uc=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:lc(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),dc=()=>({resourceId:void 0}),fc=e=>{if(!D(e))return e;let t={...e};return Object.prototype.hasOwnProperty.call(t,"requireComplete")&&!Object.prototype.hasOwnProperty.call(t,"requireLineCompleted")&&(t.requireLineCompleted=t.requireComplete),delete t.requireComplete,t},Gr=(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}},jo=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 l=r.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},Mo=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Fo=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==No)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},pc=(e,t={})=>{let r;try{r=Fo(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:Mo(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},hc=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,pc(t,r)])),Uo=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>ou(r));return t.length>0?t:void 0},mc=e=>{!D(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!D(t))return;let r=Uo(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},ko=(e,t,r,n="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!D(e))throw new Error(`Malformed ${n}.${t}[${r}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${n}.${t}[${r}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${n}.sections[${r}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},gc=(e,t="viewedRegistry")=>{if(e===void 0)return Vo();if(!D(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let r=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(r.map((o,i)=>{let s=ko(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=ko(o,"resources",i,t);return[s.resourceId,s]})))}},Bo=(e,t,r)=>{if(!D(e))throw new Error(`Malformed save slot ${r}.`);let{sectionId:n,lineId:o}=e;if(typeof n!="string"||n.length===0)throw new Error(`Malformed save slot ${r}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${r}: missing lineId.`);let{sceneId:i,section:s}=Gr(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}},yc=(e,t,r)=>{if(!D(e)||!Array.isArray(e.timeline))return ut({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((l,c)=>{if(!D(l))return[];try{let a=Bo(l,r,`rollback.timeline[${c}]`),u=Ut({sectionId:a.sectionId,lineId:a.lineId,rollbackPolicy:l.rollbackPolicy}),d=Uo(P(l.executedActions));return d&&(u.executedActions=d),[u]}catch{return[]}});if(n.length===0)return ut({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 l=n.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);l>=0?o=l:(n.push(Ut({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}},bc=(e,t,r)=>{if(!D(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=Qr(t),o=Bo(e.pointers?.read,t,`contexts[${r}].pointers.read`);if(e.variables!==void 0&&!D(e.variables))throw new Error(`Malformed save slot contexts[${r}].variables entry.`);if(e.runtime!==void 0&&!D(e.runtime))throw new Error(`Malformed save slot contexts[${r}].runtime entry.`);let i=e.variables?We(P(e.variables),t.resources?.variables??{}):{},s=$c({loadedContextRuntime:D(e.runtime)?P(e.runtime):{}}),l={currentPointerMode:"read",pointers:{read:o},configuration:D(e.configuration)?P(e.configuration):{},views:Array.isArray(e.views)?P(e.views):[],bgm:D(e.bgm)?P(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:yc(e.rollback,o,t)};return s&&(l.runtime=s),l},Ic=(e,t)=>{if(!D(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((r,n)=>bc(r,t,n))}},Ac=(e,t)=>{if(!D(e))throw new Error("Malformed save slot.");let r=Fo(e.formatVersion);return{...e,formatVersion:r,state:Ic(e.state,t)}},Do=(e,t,{required:r=!1}={})=>{if(e===void 0){if(r)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let n=P(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},wc=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Do(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Do(e.cancelActions,"cancelActions")}},Je=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Ec=e=>(D(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),Xe=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},zo=e=>{if(!(!D(e)||!e.animations))return{animations:P(e.animations)}},vc=(e,t)=>{let r=zo(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},xc=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},Cc=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},Ft=e=>String(e??""),Wo=(e,t)=>{let r=Ft(t);return e?.trim===!0?r.trim():r},Sc=e=>D(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>D(t)).map(([t,r])=>[t,{id:t,...P(r)}])):{},_c=(e,t)=>{if(!t||!D(e.global.formDrafts))return;let r=e.global.formDrafts[t];return D(r)?r:void 0},qo=(e,t)=>{let r=Ec(e);D(r[t])||(r[t]={values:{},touched:{},errors:{},submitted:!1});let n=r[t];return D(n.values)||(n.values={}),D(n.touched)||(n.touched={}),D(n.errors)||(n.errors={}),typeof n.submitted!="boolean"&&(n.submitted=!1),n},Jr=(e,t)=>{let r=Wo(e,t);return e?.required===!0&&r.length===0?"required":null},Rc=({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?{}:Te(n.slice(0,o+1).map(i=>i.actions||{}))},Oc=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=xc(t),o=Cc(r,n);if(!n||!o)return null;let i=_c(e,o),s=Sc(t),l=nn({state:e}),c={},a=[],u={},d=!0;return Object.entries(s).forEach(([f,p])=>{let h=Ft(l?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},f)?Ft(i.values[f]):h,y=i?.touched?.[f]===!0,b=Jr(p,g),A=i?.submitted||y?b:null,x=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,S={id:f,variableId:p.variableId,value:g,initialValue:h,valid:!b,error:A,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...x!==void 0?{maxLength:x}:{}};b&&(d=!1),c[f]=S,a.push(S),u[f]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:d,submitted:i?.submitted===!0,fields:c,fieldList:a,values:u,submitActions:{submitForm:{formId:n,formKey:o,actions:P(t.submitActions??{})}},cancelActions:{cancelForm:{formId:n,formKey:o,actions:P(t.cancelActions??{})}}}},Ve=[],Po="line",Xr="interaction",Ut=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),Qr=e=>{let{contextVariableDefaultValues:t}=yr(e??{});return P(t)},Yo=()=>({...P(st)}),Ho=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:P(r),hasLoadedValues:!1};if(!D(e))throw new Error(`Malformed ${n}.`);let o=P(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Ko(s,P(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Lc=({loadedGlobalRuntime:e={}})=>Ho({loadedRuntime:e,runtimeIds:Er,defaults:Ne,path:"global.runtime"}).runtimeState,$c=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=Ho({loadedRuntime:e,runtimeIds:vr,defaults:Yo(),path:"context.runtime"});return r?t:void 0},Zr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},kc=e=>e.runtime?(vr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=P(st[t]))}),e.runtime):(e.runtime=Yo(),e.runtime),Dc=e=>no(e.global),Pc=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Dc(e)}})},Tc=e=>ro[e],Nc=(e,t)=>{let r=Tc(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}"`)},Ko=(e,t)=>(Nc(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),Go=(e,t,r)=>{let n=Ko(t,r);if(t in st){let o=Zr(e);if(!o)return n;let i=kc(o);return i[t]=n,n}return e.global[t]=n,n},Jo=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:P(e)},configuration:{},views:[],bgm:dc(),variables:Qr(t),rollback:ut({pointer:e})}),Qe=e=>e?(e.currentPointerMode="read",D(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Vc=(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,jc(e,{queueRender:t}),o},jc=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,Je(e),Xe(e),e.global.nextLineConfig=Bt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},Xo=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},ut=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[Ut({sectionId:e.sectionId,lineId:e.lineId})]:[]}},Me=(e,t={})=>{if(e?.rollback)return Xo(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=ut({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},en=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=Me(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(Ut(t)),n.currentIndex=n.timeline.length-1},Mc=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=Ve[Ve.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)},Fc=({state:e},t={})=>{let r=t?.source===Po?Po:Xr,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?(Ve.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Ve.push({checkpointIndex:o.currentIndex,source:r}),e)},Uc=({state:e})=>(Ve.pop(),e),be=(e,t,r)=>{let o=Ve[Ve.length-1]?.source??Xr;if(!iu(t,o))return;let i=Mc(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:P(r)}))},To=(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:l}of n){let c=e.projectData.resources?.variables?.[o],a=c?.scope,u=c?.type;if(Ce(c))throw new Error(`Cannot update computed variable: ${o}`);if(c?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Ot(a,o),Lt(u,i,o),br(u,i,s,o,{roundTo:l}),a==="context"&&(r.variables[o]=$t(r.variables[o],i,s,{roundTo:l}))}},Bc=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{su(e,r,n)})},zc=(e,t)=>{let{sectionId:r,lineId:n}=t,s=X({state:e},{sectionId:r})?.lines?.find(l=>l.id===n)?.actions;s&&Object.entries(s).forEach(([l,c])=>{hi(e,l,c)})},Qo=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=Me(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&ft({state:e}),e.global.skipMode&&je({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=Qr(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=P(jt),e.global.overlayStack=[],Je(e),Xe(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let l=i;l<=t;l++)l>i&&Kr(e),zc(e,n.timeline[l]),Bc(e,n.timeline[l]);let s=Qe(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},Wc=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;jo(t);let l=t.story.initialSceneId,c=t.story.scenes[l],a=c.initialSectionId,u=c.sections[a],d={sceneId:l,sectionId:a,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:f}=yr(t),p={...f,...We(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:gc(s,"accountViewedRegistry"),nextLineConfig:Bt(),saveSlots:hc(n),overlayStack:[],variables:p,...Lc({loadedGlobalRuntime:i})},contexts:[Jo({pointer:d,projectData:t})]}},qc=({state:e})=>e.global.overlayStack||[],Yc=({state:e})=>e.global.pendingEffects,Zo=({state:e})=>e.global.skipMode,Hc=({state:e})=>e.global.autoMode,ei=({state:e})=>e.global.dialogueUIHidden,ti=({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),l=i.lines.slice(0,s+1),c=[],a={};for(let u of l){let d=u.actions||{};if(a=Te([a,d]),!d.dialogue)continue;let f=a.dialogue||{},p="";f.character?.name!==void 0?p=f.character.name:f.characterId&&(p=e.projectData.resources?.characters?.[f.characterId]?.name||"");let h=uc({sectionId:n,lineId:u.id,content:d.dialogue.append===!0?f.content:d.dialogue.content,dialogueState:f,characterName:p});if(d.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},Kc=({state:e})=>e.global.confirmDialog??null,dt=({state:e},{pointer:t}={})=>{let r=t??pe({state:e})?.pointer,n=Rc({state:e,pointer:r});return Oc({state:e,form:n.form,pointer:r})},Gc=({state:e},{pointer:t}={})=>!!dt({state:e},{pointer:t}),Ie=({state:e},{pointer:t}={})=>{let r=dt({state:e},{pointer:t});if(r)return{source:Mt,formId:r.id,formKey:r.key};let n=ri({state:e,pointer:t});return n?{source:Hr,resourceId:n}:null},Jc=({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 l=X({state:e},{sectionId:n});if(!l||!l.lines||!Array.isArray(l.lines))return s.lastLineId===o;let c=l.lines.findIndex(u=>u.id===s.lastLineId),a=l.lines.findIndex(u=>u.id===o);return c===-1||a===-1?s.lastLineId===o:a<=c},Xc=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},tn=({state:e},t)=>Jc({state:e,registry:e.global.accountViewedRegistry},t),Qc=({state:e},t)=>Xc({registry:e.global.accountViewedRegistry},t),Zc=({state:e})=>e.global.nextLineConfig,ri=({state:e,pointer:t}={})=>{let r=t??pe({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=X({state:e},{sectionId:n})?.lines||[],l=s.findIndex(a=>a.id===o);if(l<0)return;let c;for(let a of s.slice(0,l+1)){let u=a?.actions;if(u?.cleanAll&&(c=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){c=void 0;continue}let d=u.choice;if(d?.resourceId){c=d.resourceId;continue}d?.animations||(c=void 0)}return c},ni=({state:e})=>!!ri({state:e}),el=({state:e})=>structuredClone(e),oi=({state:e})=>e.global.saveSlots,tl=({state:e},t)=>{let r=t?.slotId,n=zt(r);return e.global.saveSlots[n]},rn=({state:e})=>qe(e),rl=({state:e},t)=>Ae(e,t?.runtimeId),nn=({state:e})=>{let t={...e.global?.variables??{},...Zr(e)?.variables??{}};return Rt({variables:t,runtime:qe(e),variableConfigs:e.projectData.resources?.variables??{}})},pe=({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 Gr(e.projectData,r).section},on=({state:e})=>{let t=pe({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)},ii=({state:e})=>{let{sectionId:t,lineId:r}=pe({state:e}).pointer,o=X({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===r),l=o.slice(0,i+1).map(a=>{let u=a.actions||{},d={};return Object.keys(u).forEach(f=>{d[f]=u[f]}),d});return Te(l)},nl=({state:e})=>{let t=si({state:e}),n=on({state:e})?.actions??{},o=Te([t??{},n]);return Ir(t??{},o??{})},ol=({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||{},l=Te([o,s]),c=Ir(o,l);n.push({id:i.id,changes:c,presentationState:l}),o=Ar(l)}return n},il=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=ol({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},si=({state:e})=>{let{sectionId:t,lineId:r}=pe({state:e}).pointer,o=X({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===r);if(i<=0)return null;let l=o.slice(0,i).map(c=>{let a=c.actions||{},u={};return Object.keys(a).forEach(d=>{u[d]=a[d]}),u});return Ar(Te(l))},sn=({state:e},{slotsPerPage:t=6}={})=>{let o=((rn({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let l=o+s,c=e.global.saveSlots&&e.global.saveSlots[zt(l)]||{};i.push({...c,slotId:l})}return{saveSlots:i}},sl=oi,al=sn,cl=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},ll=({state:e},t={})=>{let r=ii({state:e}),n=si({state:e}),o=on({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:P(i)}:o,l=i?.animations&&n===null?{}:n,{sectionId:c}=pe({state:e}).pointer,{sceneId:a}=Gr(e.projectData,c),u=rn({state:e}),d=t?.activePersistentAnimations??[],f=t?.restoredPersistentAnimations??[],p=dt({state:e}),h=ni({state:e}),g=nn({state:e}),{saveSlots:y}=sn({state:e}),b=cl(e);return $o({presentationState:r,previousPresentationState:l,currentLineActions:s,resources:e.projectData.resources,currentSceneId:a,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:gi({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:ti({state:e}),saveSlots:y,variables:g,runtime:u,activePersistentAnimations:d,restoredPersistentAnimations:f})},ul=({state:e},t)=>(e.global.confirmDialog=wc(t),e.global.pendingEffects.push({name:"render"}),e),dl=({state:e})=>(e.global.confirmDialog&&(Je(e),e.global.pendingEffects.push({name:"render"})),e),fl=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),be(e,"pushOverlay",t),e),pl=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),be(e,"popOverlay",void 0),e),hl=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),be(e,"replaceLastOverlay",t),e),ml=({state:e})=>(e.global.overlayStack=[],Je(e),Xe(e),e.global.pendingEffects.push({name:"render"}),be(e,"clearOverlays",void 0),e),gl=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"})},Wt=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,vc(e,r),Xe(e);let n=Ie({state:e},{pointer:t}),o=n?.source===Hr,i=n?.source===Mt;return n&&gl(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},ai=({state:e})=>(Ie({state:e})||(e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.autoMode=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.isLineCompleted&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ae(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),ft=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),yl=({state:e})=>{let t=e.global.autoMode;return Ie({state:e})&&!t||(t?ft({state:e}):ai({state:e})),e},ci=({state:e})=>(Ie({state:e})||(e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode=!0,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"startSkipNextTimer"}),e.global.pendingEffects.push({name:"render"})),e),je=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),bl=({state:e})=>{let t=Zo({state:e});return Ie({state:e})&&!t||(t?je({state:e}):ci({state:e})),e},qt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),be(e,"showDialogueUI",void 0),e),li=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),be(e,"hideDialogueUI",void 0),e),Il=({state:e})=>(ei({state:e})?qt({state:e}):li({state:e}),e),Fe=(e,t,r)=>(Go(e,t,r),Pc(e),e.global.pendingEffects.push({name:"render"}),e),pt=(e,t,r,n)=>{let o=Go(e,t,r);return e.global.pendingEffects.push({name:"render"}),be(e,n,{value:o}),e},Al=({state:e},t)=>Fe(e,"dialogueTextSpeed",t?.value),wl=({state:e},t)=>Fe(e,"autoForwardDelay",t?.value),El=({state:e},t)=>Fe(e,"skipUnseenText",t?.value),vl=({state:e},t)=>Fe(e,"skipTransitionsAndAnimations",t?.value),xl=({state:e},t)=>Fe(e,"soundVolume",t?.value),Cl=({state:e},t)=>Fe(e,"musicVolume",t?.value),Sl=({state:e},t)=>Fe(e,"muteAll",t?.value),_l=({state:e},t)=>pt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),Rl=({state:e})=>{let t=Ae(e,"saveLoadPagination")+1;return pt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},Ol=({state:e})=>{let t=Ae(e,"saveLoadPagination")-1;return pt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},Ll=({state:e},t)=>pt(e,"menuPage",t?.value,"setMenuPage"),$l=({state:e},t)=>pt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),kl=({state:e})=>(e.global.pendingEffects=[],e),Dl=({state:e},t)=>(e.global.pendingEffects.push(t),e),ui=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!zo(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&&!Vc(e,{queueRender:!o}))return e;e.global.autoMode&&ft({state:e}),r&&e.global.skipMode&&je({state:e});let l=e.contexts?.[e.contexts.length-1];if(l){let c=Qe(l),a=c.read;r||Ge(e,{sectionId:a?.sectionId,lineId:a?.lineId}),l.rollback||Me(l,{compatibilityAnchor:!0}),c.read={sectionId:t,lineId:s.id},r?l.rollback=ut({pointer:c.read}):en(e,{sectionId:t,lineId:s.id})}return Wt(e,l?.pointers?.read,{screenTransition:n}),e},Pl=({state:e},t)=>ui(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),di=e=>(e.global.accountViewedRegistry=cc(e.global.accountViewedRegistry),e.global.accountViewedRegistry),an=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(r=>({scope:r.scope,path:r.path,op:r.op,value:P(r.value)}))}})},fi=(e,t)=>{an(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:[]}}])},Tl=(e,t,{sectionId:r,lineId:n})=>{if(!r||!n)return!1;let o=D(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===r);if(i){if(i.lastLineId===void 0)return!1;let s=X({state:e},{sectionId:r});if(s?.lines){let l=s.lines.findIndex(a=>a.id===i.lastLineId),c=s.lines.findIndex(a=>a.id===n);if(l===-1||c>l)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},Ge=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;Tl(e,di(e),t)&&fi(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},Nl=({state:e},t)=>(Ge(e,t),e.global.pendingEffects.push({name:"render"}),e),Vl=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=di(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),fi(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},pi=({state:e},t)=>{let r=fc(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=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,a=Ie({state:e});return!l&&!a&&c===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!l&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),be(e,"setNextLineConfig",t),e},jl=({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=zt(r),s=P(e.contexts);s?.forEach(a=>{Qe(a),Xo(a.rollback),mc(a.rollback)});let l={contexts:s},c={formatVersion:No,slotId:Mo(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:l};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Ml=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=zt(r),o=e.global.saveSlots[n];if(o){let i=Ac(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=Bt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,Je(e),Xe(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},Fl=({state:e},t)=>{let{projectData:r}=t;jo(r),e.projectData=r;let n=r?.resources?.variables??{};return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables=We(e.global.variables,n)),e.contexts?.forEach(o=>{Object.prototype.hasOwnProperty.call(o??{},"variables")&&(o.variables=We(o.variables,n))}),Je(e),Xe(e),e.global.pendingEffects.push({name:"render"}),e},Ul=({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(a=>a.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let c=Qe(o);return c.read={sectionId:i,lineId:n},Wt(e,c.read),e},Bl=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return qt({state:e}),e;let r=Ie({state:e});if(r?.source===Hr&&t?.bypassChoice!==!0||r?.source===Mt&&t?._interactionSource!==Mt)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=pe({state:e})?.pointer,d=u?.sectionId,f=u?.lineId;d&&f&&Ge(e,{sectionId:d,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ae(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=pe({state:e})?.pointer,o=n?.sectionId,i=X({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],l=i?.lines||[],a=l.findIndex(u=>u.id===n?.lineId)+1;if(a<l.length){let u=l[a],d=!Ae(e,"skipUnseenText");if(e.global.skipMode&&d&&!tn({state:e},{sectionId:o,lineId:u.id}))return je({state:e}),e;if(s&&!s.rollback&&Me(s,{compatibilityAnchor:!0}),s){let h=Qe(s),g=h.read?.lineId;g&&o&&Ge(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:u.id}}en(e,{sectionId:o,lineId:u.id}),Kr(e);let{activeInteraction:f}=Wt(e,{sectionId:o,lineId:u.id}),p=e.global.nextLineConfig;p?.auto?.enabled&&!f&&p.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}})}else e.global.autoMode&&ft({state:e}),e.global.skipMode&&je({state:e});return e},zl=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ie({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ae(e,"autoForwardDelay")}});let r=pe({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&Ge(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},Wl=({state:e},t)=>ui(e,{sectionId:t?.sectionId,screen:t?.screen}),ql=({state:e})=>{if(e.global.dialogueUIHidden)return qt({state:e}),e;if(Ie({state:e}))return e;let t=pe({state:e})?.pointer,r=t?.sectionId,n=X({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],l=i.findIndex(c=>c.id===t?.lineId)+1;if(l<i.length){let c=i[l],a=!Ae(e,"skipUnseenText");if(e.global.skipMode&&a&&!tn({state:e},{sectionId:r,lineId:c.id}))return je({state:e}),e;if(o&&!o.rollback&&Me(o,{compatibilityAnchor:!0}),o){let d=Qe(o),f=d.read?.lineId;f&&r&&Ge(e,{sectionId:r,lineId:f}),d.read={sectionId:r,lineId:c.id}}en(e,{sectionId:r,lineId:c.id}),Kr(e);let{activeInteraction:u}=Wt(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},cn=(e,t={})=>{let r=dt({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},Yl=(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(Ce(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return Ot(n,t.variableId),Lt(o,"set",t.variableId),{variableConfig:r,scope:n}},Hl=(e,t)=>({id:e.id,key:e.key,valid:!0,values:P(t),fields:P(e.fields),fieldList:P(e.fieldList)}),Kl=({state:e},t={})=>{let r=cn(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=qo(e,r.key),i=Ft(t.value),s=r.fields[n],l=Jr(s,i);return o.values[n]=i,o.touched[n]=!0,l?o.errors[n]=l:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},Gl=({state:e},t={})=>{let r=cn(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=qo(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([d,f])=>{let p=Object.prototype.hasOwnProperty.call(n.values,d)?n.values[d]:f.value,h=Jr(f,p);n.touched[d]=!0,h&&(i[d]=h),o[d]=Wo(f,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:P(i),form:{id:r.id,key:r.key,values:P(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let l=!1,c=[],a=[];Object.entries(r.fields).forEach(([d,f])=>{let{scope:p}=Yl(e,f),h=p==="context"?s.variables:e.global.variables,g=o[d];h[f.variableId]=$t(h[f.variableId],"set",g),p==="context"&&(l=!0,a.push({variableId:f.variableId,op:"set",value:g})),(p==="device"||p==="account")&&c.push({scope:p,path:`variables.${f.variableId}`,op:"set",value:P(h[f.variableId])})}),l&&be(e,"updateVariable",{id:"submitForm",operations:a}),an(e,c);let u=Hl(r,o);return delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},Jl=({state:e},t={})=>{let r=cn(e,t);return r?(delete e.global.formDrafts?.[r.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:r.id,key:r.key,values:P(r.values),fields:P(r.fields),fieldList:P(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},Xl=({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=[],l=[];return n.forEach(({variableId:c,op:a,value:u,roundTo:d})=>{let f=e.projectData.resources?.variables?.[c],p=f?.scope,h=f?.type;if(Ce(f))throw new Error(`Cannot update computed variable: ${c}`);if(f?.readonly===!0)throw new Error(`Cannot update readonly variable: ${c}`);Ot(p,c),Lt(h,a,c),br(h,a,u,c,{roundTo:d});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:c,op:a,value:u};d!==void 0&&(y.roundTo=d),l.push(y)}g[c]=$t(g[c],a,u,{roundTo:d}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${c}`,op:"set",value:P(g[c])})}),i&&be(e,"updateVariable",{id:r,operations:l}),an(e,s),e.global.pendingEffects.push({name:"render"}),e},Ql=e=>(t,r)=>e({state:t},r),Zl=e=>({variables:Rt({variables:{...e.global?.variables??{},...Zr(e)?.variables??{}},runtime:qe(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:qe(e)}),eu=e=>{if(!D(e))throw new Error("conditional action payload must be an object");if(!Array.isArray(e.branches))throw new Error("conditional action requires branches array");if(e.branches.length===0)throw new Error("conditional action requires at least one branch")},tu=(e,t,r)=>{if(!D(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!D(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==r-1)throw new Error("conditional else branch must be the last branch")},ru=(e,t)=>{eu(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(tu(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!ot(n.when,Zl(e)))){Object.entries(n.actions).forEach(([i,s])=>{hi(e,i,s)});return}}},nu={conditional:{replayLine:ru},updateVariable:{recordSources:[Xr],replayLine:To,replayRecorded:To,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Ql(pi)}},Yt=e=>nu[e]??null,ou=e=>Yt(e)?.persistInSaveSlot===!0,iu=(e,t)=>{let r=Yt(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},su=(e,t,r)=>{Yt(t)?.replayRecorded?.(e,r)},hi=(e,t,r)=>{Yt(t)?.replayLine?.(e,r)},mi=({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}},gi=({state:e})=>mi({state:e},{offset:-1})!==null,au=({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=Me(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:Qo(e,i)},cu=({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=Me(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===r&&c.lineId===n);if(l===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return l===i.currentIndex?e:Qo(e,l)},yi=e=>{let t=Wc(e);return Hn(t,{selectPendingEffects:Yc,selectSkipMode:Zo,selectAutoMode:Hc,selectIsChoiceVisible:ni,selectIsFormVisible:Gc,selectActiveInteraction:Ie,selectActiveForm:dt,selectDialogueUIHidden:ei,selectDialogueHistory:ti,selectConfirmDialog:Kc,selectIsLineAccountViewed:tn,selectIsResourceAccountViewed:Qc,selectNextLineConfig:Zc,selectSystemState:el,selectSaveSlotMap:oi,selectSaveSlots:sl,selectSaveSlot:tl,selectRuntime:rn,selectRuntimeValue:rl,selectAllVariables:nn,selectCurrentPointer:pe,selectSection:X,selectCurrentLine:on,selectPresentationState:ii,selectPresentationChanges:nl,selectSectionLineChanges:il,selectSaveSlotPage:sn,selectCurrentPageSlots:al,selectRenderState:ll,selectOverlayStack:qc,selectLineIdByOffset:mi,selectCanRollback:gi,startAutoMode:ai,stopAutoMode:ft,toggleAutoMode:yl,startSkipMode:ci,stopSkipMode:je,toggleSkipMode:bl,showDialogueUI:qt,hideDialogueUI:li,toggleDialogueUI:Il,setDialogueTextSpeed:Al,setAutoForwardDelay:wl,setSkipUnseenText:El,setSkipTransitionsAndAnimations:vl,setSoundVolume:xl,setMusicVolume:Cl,setMuteAll:Sl,setSaveLoadPagination:_l,incrementSaveLoadPagination:Rl,decrementSaveLoadPagination:Ol,setMenuPage:Ll,setMenuEntryPoint:$l,showConfirmDialog:ul,hideConfirmDialog:dl,resetStoryAtSection:Pl,clearPendingEffects:kl,appendPendingEffect:Dl,beginRollbackActionBatch:Fc,endRollbackActionBatch:Uc,addViewedLine:Nl,addViewedResource:Vl,setNextLineConfig:pi,saveSlot:jl,loadSlot:Ml,updateProjectData:Fl,sectionTransition:Wl,jumpToLine:Ul,nextLine:Bl,markLineCompleted:zl,rollbackToLine:cu,rollbackByOffset:au,pushOverlay:fl,popOverlay:pl,replaceLastOverlay:hl,clearOverlays:ml,updateFormField:Kl,submitForm:Gl,cancelForm:Jl,updateVariable:Xl,nextLineFromSystem:ql},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var lu="route-engine",uu="projectPersistence";var Ii=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),G=e=>Object.prototype.toString.call(e)==="[object Object]",bi="variables.",du=(e={})=>{let t=G(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!G(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)}:!G(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},fu=(e={})=>{let t=G(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!G(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)}:!G(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},pu=(e,t)=>{let r=fu(e),n=du(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let l=o.find(c=>c.sectionId===s.sectionId);if(!l){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(l.lastLineId!==void 0){if(s.lineId===void 0){delete l.lastLineId;return}l.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(c=>c.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},Ai=(e={})=>{let t=G(e)?e:{};return{saveSlots:G(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:G(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:G(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:G(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:G(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},hu=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!G(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(bi)?t.path.slice(bi.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}].`)})},mu=(e,t)=>{let r={};return hu(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=pu(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},ln=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},gu=e=>{let t=ln(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},yu=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},bu=({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.`))}})},ht=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),c=l.objectStore(t),a=c.get(r),u=!1,d=p=>{u||(u=!0,s(p))},f=()=>{u||(u=!0,i())};a.onerror=()=>{d(a.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},a.onsuccess=()=>{let p=Ai(a.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...Ii(),...p,...h},y=c.put(g);y.onerror=()=>{d(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},l.oncomplete=()=>{f()},l.onerror=()=>{d(l.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},l.onabort=()=>{d(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},Au=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),a=!1,u=f=>{a||(a=!0,i(f))},d=()=>{a||(a=!0,o())};c.onerror=()=>{u(c.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{d()},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}".`))}})},un=(e={})=>{let{indexedDB:t,databaseName:r=lu,objectStoreName:n=uu,namespace:o}=e,i=yu(t),s=gu(o),l=bu({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let c=await Iu({databasePromise:l,objectStoreName:n,namespace:s});return{...Ii(),...Ai(c)}},clear:async()=>Au({databasePromise:l,objectStoreName:n,namespace:s}),saveSlots:async c=>ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{saveSlots:G(c)?c:{}}}),saveGlobalDeviceVariables:async c=>ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:G(c)?c:{}}}),saveGlobalAccountVariables:async c=>ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalAccountVariables:G(c)?c:{}}}),saveGlobalRuntime:async c=>ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalRuntime:G(c)?c:{}}}),applyScopedDataUpdates:async c=>ht({databasePromise:l,objectStoreName:n,namespace:s,patch:a=>mu(a,c)})}},wu=un;var Eu=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),vu=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),wi="conditional",dn="form",xu=new Set(["submitForm","cancelForm"]),mt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function fn(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:l}=e,c=(I=new Map,C=Date.now())=>new Map(Array.from(I.entries()).filter(([,O])=>C<O.expiresAt).map(([O,U])=>[O,{animation:structuredClone(U.animation),startedAt:U.startedAt,expiresAt:U.expiresAt}])),a=(I=new Map)=>Array.from(I.values()).map(C=>structuredClone(C.animation)),u=(I=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,C])=>I<C.expiresAt))},d=()=>{for(;t.selectPendingEffects().length>0;){let I=[...t.selectPendingEffects()];t.clearPendingEffects();try{l(I)}catch(C){throw t.clearPendingEffects(),I.forEach(O=>{t.appendPendingEffect(O)}),C}}},f=({initialState:I,namespace:C})=>{t=yi(I),r=0,n=ln(C),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),d()},p=()=>n,h=()=>t.selectPresentationState(),g=()=>t.selectPresentationChanges(),y=I=>t.selectSectionLineChanges(I),b=(I={})=>{r+=1;let C=Date.now();u(C);let O=i.size>0,U=c(o,C),W=O?c(i,C):new Map,me={...t.selectRenderState({activePersistentAnimations:a(U),restoredPersistentAnimations:a(W)}),id:`render-${r}`};return s.set(me.id,{builtAt:C,persistentAnimationSessions:new Map([...W.entries(),...U.entries()]),usedRestoredPersistentAnimationSessions:O}),me},A=(I={})=>b(I),x=(I={})=>b(I),S=I=>{let C=typeof I?.id=="string"&&I.id.length>0?I.id:null,O=C?s.get(C):null;C&&s.delete(C);let U=new Map;Io(I?.animations).forEach(W=>{let ie=Pt(W);if(!ie)return;let me=O?.persistentAnimationSessions?.get(ie)??o.get(ie),gt=Math.max(0,wo(W)),mn=me?.startedAt??O?.builtAt??Date.now();U.set(ie,{animation:structuredClone(W),startedAt:mn,expiresAt:mn+gt})}),o=U,O?.usedRestoredPersistentAnimationSessions&&(i=new Map)},T=()=>t.selectSystemState(),E=()=>t.selectSaveSlotMap(),N=I=>t.selectSaveSlot(I),B=I=>t.selectSaveSlotPage(I),k=()=>t.selectSkipMode(),j=()=>t.selectAutoMode(),F=()=>t.selectRuntime(),M=()=>t.selectIsChoiceVisible(),q=()=>t.selectIsFormVisible(),v=()=>t.selectActiveInteraction(),_=(I,C,O={})=>I!=="nextLine"||!mt(C)?C:O.bypassChoice===!0?{...C,bypassChoice:!0}:O.interactionSource===dn?{...C,_interactionSource:dn}:C,R=(I,C)=>{if(!t[I])return;Eu.has(I)&&(vu.has(I)?i=c(o):i=new Map,o=new Map);let O=t[I](C);return d(),O},z=(I,C,O,U={})=>{if(I===wi){let W=V(O),ie=wr({[I]:C},W);Ue(ie[I],O,U);return}R(I,C)},Y=(I,C)=>{z(I,C)},V=I=>{if(!I)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(I,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:C,...O}=I,U=t.selectAllVariables?t.selectAllVariables():void 0;return{...O,_event:C,variables:U,runtime:t.selectRuntime?t.selectRuntime():{}}},he=I=>{if(!mt(I))throw new Error("conditional action payload must be an object");if(!Array.isArray(I.branches))throw new Error("conditional action requires branches array");if(I.branches.length===0)throw new Error("conditional action requires at least one branch")},Z=(I,C,O)=>{if(!mt(I))throw new Error(`conditional branch at index ${C} must be an object`);if(!mt(I.actions))throw new Error(`conditional branch at index ${C} requires actions object`);if(!Object.prototype.hasOwnProperty.call(I,"when")&&C!==O-1)throw new Error("conditional else branch must be the last branch")},Ue=(I,C,O)=>{he(I);for(let U=0;U<I.branches.length;U+=1){let W=I.branches[U];Z(W,U,I.branches.length);let ie=V(C);if(!(Object.prototype.hasOwnProperty.call(W,"when")&&!ot(W.when,ie))){Kt(W.actions,C,O);return}}},xi=(I,C)=>({...I??{},_form:C}),Ci=(I,C,O,U)=>{let W=R(I,C),ie=W?.submitted===!0&&W.valid===!0,me=W?.cancelled===!0;!ie&&!me||mt(C.actions)&&Kt(C.actions,xi(O,W.form),{...U,interactionSource:dn})},Si=(I,C,O,U)=>{let W=V(O),me=wr({[I]:C},W)[I];if(I===wi){Ue(me,O,U);return}let gt=_(I,me,U);if(xu.has(I)){Ci(I,gt,O,U);return}R(I,gt)},Kt=(I,C,O)=>{Object.entries(I).forEach(([U,W])=>{Si(U,W,C,O)})},hn=(I,C,O={})=>{t.beginRollbackActionBatch({source:O.rollbackSource});try{Kt(I,C,O)}finally{t.endRollbackActionBatch({})}};return{init:f,handleAction:z,handleInternalAction:Y,handleActions:hn,selectRenderState:A,prepareRenderState:x,commitRenderState:S,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:T,selectSaveSlotMap:E,selectSaveSlot:N,selectSaveSlotPage:B,selectSaveSlots:E,selectRuntime:F,selectIsChoiceVisible:M,selectIsFormVisible:q,selectActiveInteraction:v,handleLineActions:()=>{let I=t.selectCurrentLine();return I?.actions?(hn(I.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var pn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},Cu=80,vi=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},Su=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&vi({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},_u=({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 l=n.delay??1e3;r.getElapsed()>=l&&(t.remove(i),r.setCallback(null),r.setElapsed(0),Ht(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},Ru=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Ou=({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 l=n?.delay??Cu;r.getElapsed()>=l&&(r.setElapsed(0),Ht(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},Lu=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},$u=({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 l=n.delay??1e3;r.getElapsed()>=l&&(r.setElapsed(0),Ht(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},ku=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Du=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},Pu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},Tu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},Nu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},Vu=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},Ei={render:vi,saveSlots:Du,saveGlobalDeviceVariables:Pu,saveGlobalAccountVariables:Tu,saveGlobalRuntime:Nu,applyScopedDataUpdates:Vu,handleLineActions:Su,startAutoNextTimer:_u,clearAutoNextTimer:Ru,startSkipNextTimer:Ou,clearSkipNextTimer:Lu,nextLineConfigTimer:$u,clearNextLineConfigTimer:ku},ju=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Ht=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},Mu=(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(!ju.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},Fu=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let c=pn(),a=pn(),u=pn(),d=s??null,f=Promise.resolve(),p=null,h=null,g=!1,y=0,b=v=>{if(o){o(v);return}console.error("RouteEngine persistence write failed.",v)},A=()=>{if(d)return d;let v=e();return d=un({indexedDB:i,namespace:l??v?.getNamespace?.()}),d},x=v=>{f=f.catch(()=>{}).then(()=>{let _=A();return v(_)}).catch(_=>{b(_)})},S=v=>{let _=typeof v?.id=="string"&&v.id.length>0?v.id:null;y+=1,p=_,g=!1},T=()=>y,E=(v={})=>{if(v?.aborted===!0)return!1;let _=typeof v?.id=="string"&&v.id.length>0?v.id:null;return _?_!==p||_===h?!1:(h=_,!0):p!==null||g?!1:(g=!0,!0)},N=(v,_={})=>{if(v!=="renderComplete"||!E(_))return!1;let R=e();return Ht(R,"markLineCompleted",{}),!0},B=v=>typeof v?.selectActiveInteraction=="function"?v.selectActiveInteraction():typeof v?.selectIsChoiceVisible=="function"&&v.selectIsChoiceVisible()?{source:"choice"}:null,k=(v,_)=>!(!v||typeof v!="object"||Array.isArray(v)||v._interactionSource!==_?.source||_.source==="form"&&v._formKey&&v._formKey!==_.formKey||_.source==="form"&&v.formKey&&v.formKey!==_.formKey),j=(v={},_)=>{if(k(v,_))return!0;let R=v?.actions;return!R||typeof R!="object"||Array.isArray(R)?!1:Object.values(R).some(z=>k(z,_))},F=(v,_={})=>{if(!_?.actions)return!1;let R=B(v);return!R||R.source==="choice"?!1:!j(_,R)},M=({preprocessPayload:v,onEvent:_}={})=>async(R,z={})=>{let Y=e();if(F(Y,z))return _?.(R,z);let V=await v?.(R,z)??z;if(F(Y,V))return _?.(R,V);if(N(R,V),V?.actions){let he=V?._event?{_event:V._event}:V?.event?{_event:V.event}:void 0,Z;V?.bypassChoice===!0?Z={bypassChoice:!0}:V?._interactionSource&&(Z={interactionSource:V._interactionSource}),Z?Y.handleActions(V.actions,he,Z):Y.handleActions(V.actions,he)}return _?.(R,V)},q=v=>{let _=e(),R=Mu(v);R.forEach(Y=>{if(!Ei[Y.name]&&!n)throw new Error(`Unhandled pending effect "${Y.name}".`)});let z={engine:_,routeGraphics:t,ticker:r,autoTimer:c,skipTimer:a,nextLineConfigTimerState:u,trackRenderDispatch:S,getRenderDispatchCount:T,enqueuePersistenceWrite:x};for(let Y of R){let V=Ei[Y.name];if(V){V(z,Y.payload);continue}n(Y,z)}};return q.handleRouteGraphicsEvent=N,q.createRouteGraphicsEventHandler=M,q},Uu=Fu;var Bu=(e,t={})=>{let{resources:r={}}=t;return Yr(e,r)};var cf=fn;export{xr as DEFAULT_VISUAL_LAYER,at as RENDER_LAYER,Se as VISUAL_LAYER,Uu as createEffectsHandler,wu as createIndexedDbPersistence,cf as default,Ds as resolveComputedVariables,Bu as resolveLayoutReferences};
|
package/package.json
CHANGED