route-engine-js 1.31.5 → 1.33.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.
@@ -1,2 +1,2 @@
1
- var Oa=Object.defineProperty;var Ra=(e,t)=>{for(var n in t)Oa(e,n,{get:t[n],enumerable:!0})};var Ao=Symbol.for("immer-nothing"),mo=Symbol.for("immer-draftable"),ge=Symbol.for("immer-state");function Ie(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var lt=Object.getPrototypeOf;function ae(e){return!!e&&!!e[ge]}function Ye(e){return e?wo(e)||Array.isArray(e)||!!e[mo]||!!e.constructor?.[mo]||Kt(e)||Jt(e):!1}var _a=Object.prototype.constructor.toString();function wo(e){if(!e||typeof e!="object")return!1;let t=lt(e);if(t===null)return!0;let n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return n===Object?!0:typeof n=="function"&&Function.toString.call(n)===_a}function qn(e){return ae(e)||Ie(15,e),e[ge].base_}function Ht(e,t){Gt(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function Gt(e){let t=e[ge];return t?t.type_:Array.isArray(e)?1:Kt(e)?2:Jt(e)?3:0}function jn(e,t){return Gt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Eo(e,t,n){let r=Gt(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function ka(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Kt(e){return e instanceof Map}function Jt(e){return e instanceof Set}function We(e){return e.copy_||e.base_}function Fn(e,t){if(Kt(e))return new Map(e);if(Jt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=wo(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[ge];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let s=o[i],l=r[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(r[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(lt(e),r)}else{let r=lt(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function Hn(e,t=!1){return Xt(e)||ae(e)||!Ye(e)||(Gt(e)>1&&(e.set=e.add=e.clear=e.delete=$a),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>Hn(r,!0))),e}function $a(){Ie(2)}function Xt(e){return Object.isFrozen(e)}var La={};function Ge(e){let t=La[e];return t||Ie(0,e),t}var Et;function xo(){return Et}function Ta(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function go(e,t){t&&(Ge("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Mn(e){Un(e),e.drafts_.forEach(Na),e.drafts_=null}function Un(e){e===Et&&(Et=e.parent_)}function yo(e){return Et=Ta(Et,e)}function Na(e){let t=e[ge];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function bo(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[ge].modified_&&(Mn(t),Ie(4)),Ye(e)&&(e=Wt(t,e),t.parent_||Yt(t,e)),t.patches_&&Ge("Patches").generateReplacementPatches_(n[ge].base_,e,t.patches_,t.inversePatches_)):e=Wt(t,n,[]),Mn(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Ao?e:void 0}function Wt(e,t,n){if(Xt(t))return t;let r=t[ge];if(!r)return Ht(t,(o,i)=>Io(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Yt(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let o=r.copy_,i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Ht(i,(l,a)=>Io(e,r,o,l,a,n,s)),Yt(e,o,!1),n&&e.patches_&&Ge("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function Io(e,t,n,r,o,i,s){if(ae(o)){let l=i&&t&&t.type_!==3&&!jn(t.assigned_,r)?i.concat(r):void 0,a=Wt(e,o,l);if(Eo(n,r,a),ae(a))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(Ye(o)&&!Xt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Wt(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&Yt(e,o)}}function Yt(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Hn(t,n)}function Da(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:xo(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=Wn;n&&(o=[r],i=xt);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var Wn={get(e,t){if(t===ge)return e;let n=We(e);if(!jn(n,t))return Pa(e,n,t);let r=n[t];return e.finalized_||!Ye(r)?r:r===Pn(e.base_,t)?(Vn(e),e.copy_[t]=zn(r,e)):r},has(e,t){return t in We(e)},ownKeys(e){return Reflect.ownKeys(We(e))},set(e,t,n){let r=vo(We(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=Pn(We(e),t),i=o?.[ge];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(ka(n,o)&&(n!==void 0||jn(e.base_,t)))return!0;Vn(e),Bn(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return Pn(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Vn(e),Bn(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=We(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){Ie(11)},getPrototypeOf(e){return lt(e.base_)},setPrototypeOf(){Ie(12)}},xt={};Ht(Wn,(e,t)=>{xt[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});xt.deleteProperty=function(e,t){return xt.set.call(this,e,t,void 0)};xt.set=function(e,t,n){return Wn.set.call(this,e[0],t,n,e[0])};function Pn(e,t){let n=e[ge];return(n?We(n):e)[t]}function Pa(e,t,n){let r=vo(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function vo(e,t){if(!(t in e))return;let n=lt(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=lt(n)}}function Bn(e){e.modified_||(e.modified_=!0,e.parent_&&Bn(e.parent_))}function Vn(e){e.copy_||(e.copy_=Fn(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Va=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){let i=n;n=t;let s=this;return function(a=i,...c){return s.produce(a,u=>n.call(this,u,...c))}}typeof n!="function"&&Ie(6),r!==void 0&&typeof r!="function"&&Ie(7);let o;if(Ye(t)){let i=yo(this),s=zn(t,void 0),l=!0;try{o=n(s),l=!1}finally{l?Mn(i):Un(i)}return go(i,r),bo(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===Ao&&(o=void 0),this.autoFreeze_&&Hn(o,!0),r){let i=[],s=[];Ge("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else Ie(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,a=>t(a,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Ye(e)||Ie(8),ae(e)&&(e=Ke(e));let t=yo(this),n=zn(e,void 0);return n[ge].isManual_=!0,Un(t),n}finishDraft(e,t){let n=e&&e[ge];(!n||!n.isManual_)&&Ie(9);let{scope_:r}=n;return go(r,t),bo(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){let o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));let r=Ge("Patches").applyPatches_;return ae(e)?r(e,t):this.produce(e,o=>r(o,t))}};function zn(e,t){let n=Kt(e)?Ge("MapSet").proxyMap_(e,t):Jt(e)?Ge("MapSet").proxySet_(e,t):Da(e,t);return(t?t.scope_:xo()).drafts_.push(n),n}function Ke(e){return ae(e)||Ie(10,e),Co(e)}function Co(e){if(!Ye(e)||Xt(e))return e;let t=e[ge],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Fn(e,t.scope_.immer_.useStrictShallowCopy_)}else n=Fn(e,!0);return Ht(n,(r,o)=>{Eo(n,r,Co(o))}),t&&(t.finalized_=!1),n}var be=new Va,Yn=be.produce,Zp=be.produceWithPatches.bind(be),eh=be.setAutoFreeze.bind(be),th=be.setUseStrictShallowCopy.bind(be),nh=be.applyPatches.bind(be),rh=be.createDraft.bind(be),oh=be.finishDraft.bind(be);var g={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},k={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},ut={NOT:0};var C=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},me=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Gn=e=>{if(!e||e.trim()==="")throw new C("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new C(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${n}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let n of t)if(e.trim().endsWith(n))throw new C(`Incomplete comparison expression - missing right operand (got: '${e}')`)},So=e=>{if(e.trim().endsWith(" in"))throw new C(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new C(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new C(`Missing iterable expression after 'in' (got: '$for ${e}')`);let r=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of r){if(!o)throw new C(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new C(`Invalid loop syntax (got: '$for ${e}')`)}};var Oo=(e,t,n=!1)=>{if(t===null)return new me(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new me(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new me(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new me(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},Ro=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new me(`Unknown function '${e}' (${n})`)};var ja=(e,t,n={})=>{let r={},o={};n&&typeof n=="object"&&(n.functions!==void 0||n.partials!==void 0?(r=n.functions||{},o=n.partials||{}):typeof n=="object"&&(r=n));let s=L(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},L=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return J(e.var,n,r);if(e.type===g.LITERAL)return e.value;if(e.type===g.VARIABLE)return J(e.path,n,r);if(e.type===g.INTERPOLATION)return Ma(e.parts,t,n,r);switch(e.type){case g.FUNCTION:return ko(e,t,n,r);case g.BINARY:return $o(e,t,n,r);case g.UNARY:return Lo(e,t,n,r);case g.CONDITIONAL:return Ba(e,t,n,r);case g.LOOP:return Ya(e,t,n,r);case g.OBJECT:return Ka(e,t,n,r);case g.ARRAY:return Ja(e,t,n,r);case g.PARTIAL:return Xa(e,t,n,r);case g.PATH_REFERENCE:return Qa(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},_o=new Map,Fa=e=>{let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(i==="]"){if(r&&n){let s=n.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let l=s.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:s});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},J=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=_o.get(e);if(!r){let i=[],s="",l=0;for(let a=0;a<e.length;a++){let c=e[a];c==="["?(l++,s+=c):c==="]"?(l--,s+=c):c==="."&&l===0?s&&(i.push(s),s=""):s+=c}s&&i.push(s),r=[];for(let a of i){let c=Fa(a.trim());r.push(...c)}_o.set(e,r)}let o=t;for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="property"&&s.value in n){o=n[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},Ma=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},ko=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Ro(e.name,o);let s=e.args.map(l=>L(l,t,n,r));return i(...s)},Pe=(e,t,n,r)=>{if(e.var&&!e.type)return J(e.var,n,r);switch(e.type){case g.VARIABLE:return J(e.path,n,r);case g.LITERAL:return e.value;case g.BINARY:return $o(e,t,n,r);case g.UNARY:return Lo(e,t,n,r);case g.FUNCTION:return ko(e,t,n,r);default:return L(e,t,n,r)}},$o=(e,t,n,r)=>{if(e.op===k.AND||e.op===k.OR){let s=Pe(e.left,t,n,r),l=Pe(e.right,t,n,r);switch(e.op){case k.AND:return s&&l;case k.OR:return s||l}}let o=L(e.left,t,n,r),i=L(e.right,t,n,r);switch(e.op){case k.EQ:return o==i;case k.NEQ:return o!=i;case k.GT:return o>i;case k.LT:return o<i;case k.GTE:return o>=i;case k.LTE:return o<=i;case k.IN:return Array.isArray(i)?i.includes(o):!1;case k.ADD:if(typeof o!="number"||typeof i!="number")throw new me(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case k.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new me(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Lo=(e,t,n,r)=>{let o=e.op===ut.NOT?Pe(e.operand,t,n,r):L(e.operand,t,n,r);if(e.op===ut.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Ua=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===g.VARIABLE)if(J(o.path,n,r)){let s=e.bodies[0];if(s.type===g.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?L(a.parsedKey,t,n,r):a.key,u=a.value;if(u.type===g.LITERAL)l[c]=u.value;else if(u.type===g.VARIABLE)l[c]=J(u.path,n,r);else if(u.type===g.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===g.VARIABLE){let p=J(f.path,n,r);d.push(p!=null?String(p):"")}else{let p=L(f,t,n,r);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=L(u,t,n,r)}return l}}else{let s=e.bodies[1];if(s.type===g.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?L(a.parsedKey,t,n,r):a.key,u=a.value;if(u.type===g.LITERAL)l[c]=u.value;else if(u.type===g.VARIABLE)l[c]=J(u.path,n,r);else if(u.type===g.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===g.VARIABLE){let p=J(f.path,n,r);d.push(p!=null?String(p):"")}else{let p=L(f,t,n,r);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=L(u,t,n,r)}return l}}}return null},Ba=(e,t,n,r)=>{let o=Ua(e,t,n,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||Pe(s,t,n,r))return L(e.bodies[i],t,n,r)}return To},za=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===g.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===g.VARIABLE){let o=n.conditions[0].path,i=n.bodies[0];if(o.startsWith(r+".")){let s=o.substring(r.length+1);if(i.type===g.OBJECT&&i.properties.length<=5){for(let a of i.properties)if(a.parsedKey)return null;let l=[];for(let a=0;a<t.length;a++){let c=t[a];if(c[s]){let u={};for(let d of i.properties){let f=d.key,p=d.value;if(p.type===g.LITERAL)u[f]=p.value;else if(p.type===g.VARIABLE){let h=p.path;if(h===r)u[f]=c;else if(h.startsWith(r+".")){let m=h.substring(r.length+1);u[f]=c[m]}else return null}else if(p.type===g.INTERPOLATION){let h=[],m=!0;for(let y of p.parts)if(typeof y=="string")h.push(y);else if(y.type===g.VARIABLE){let I=y.path;if(I===r)h.push(c!=null?String(c):"");else if(I.startsWith(r+".")){let w=I.substring(r.length+1),E=c[w];h.push(E!=null?String(E):"")}else{m=!1;break}}else{m=!1;break}if(!m)return null;u[f]=h.join("")}else return null}l.push(u)}}return l}}}return null},qa=(e,t)=>{let n=e.body,r=e.itemVar,o=za(e,t);if(o!==null)return o;if(n.type===g.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let l of n.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of n.properties){let a=l.key,c=l.value;if(c.type===g.LITERAL)i.push({key:a,type:"literal",value:c.value});else if(c.type===g.VARIABLE){let u=c.path;if(u===r)i.push({key:a,type:"item"});else if(u.startsWith(r+".")){let d=u.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:a,type:"prop",prop:d});else{s=!1;break}}else{s=!1;break}}else if(c.type===g.INTERPOLATION&&c.parts.length===1){let u=c.parts[0];if(u.type===g.VARIABLE){let d=u.path;if(d===r)i.push({key:a,type:"item_string"});else if(d.startsWith(r+".")){let f=d.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:a,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 a=0;a<t.length;a++){let c=t[a];l[a]={id:c.id,title:c.title!=null?String(c.title):"",completed:c.completed}}else for(let a=0;a<t.length;a++){let c=t[a],u={};for(let d of i)if(d.type==="literal")u[d.key]=d.value;else if(d.type==="item")u[d.key]=c;else if(d.type==="prop")u[d.key]=c[d.prop];else if(d.type==="item_string")u[d.key]=c!=null?String(c):"";else if(d.type==="prop_string"){let f=c[d.prop];u[d.key]=f!=null?String(f):""}l[a]=u}return l}}return null},Ha=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===g.OBJECT&&s.fast!==!1){let l=e.itemVar,a=e.indexVar;for(let c=0;c<o.length;c++){let u=o[c],d={},f={...r,[l]:u,...a&&{[a]:c}};f.__paths__||(f.__paths__=r.__paths__||{});let p=e.iterable.path||"";if(r&&r.__paths__&&p){let h=p.split("."),m=h[0];m in r.__paths__&&(p=r.__paths__[m],h.length>1&&(p+="."+h.slice(1).join(".")))}f.__paths__={...f.__paths__,[l]:`${p}[${c}]`,...a&&{[a]:c}};for(let h of s.properties){let m=h.parsedKey?L(h.parsedKey,t,n,f):h.key,y=h.value;if(y.type===g.LITERAL)d[m]=y.value;else if(y.type===g.VARIABLE){let I=y.path;if(I===l)d[m]=u;else if(I===a)d[m]=c;else if(I.startsWith(l+".")){let w=I.substring(l.length+1);!w.includes(".")&&!w.includes("[")?d[m]=u[w]:d[m]=J(I,n,{...r,[l]:u,...a&&{[a]:c}})}else d[m]=J(I,n,{...r,[l]:u,...a&&{[a]:c}})}else if(y.type===g.INTERPOLATION){let I=[];for(let w of y.parts)if(typeof w=="string")I.push(w);else if(w.type===g.VARIABLE){let E=w.path,R;if(E===l)R=u;else if(E===a)R=c;else if(E.startsWith(l+".")){let j=E.substring(l.length+1);!j.includes(".")&&!j.includes("[")?R=u[j]:R=J(E,n,{...r,[l]:u,...a&&{[a]:c}})}else R=J(E,n,{...r,[l]:u,...a&&{[a]:c}});I.push(R!=null?String(R):"")}else{let E={...r,[l]:u,...a&&{[a]:c}},R=L(w,t,n,E);I.push(R!=null?String(R):"")}d[m]=I.join("")}else{let I={...r,[l]:u,...a&&{[a]:c}};d[m]=L(y,t,n,I)}}i.push(d)}return i}return null},Wa=(e,t,n)=>{let r=e.body;if(r.type===g.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===g.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===g.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===g.OBJECT&&s.properties.length===2){let l=s.properties[0],a=s.properties[1];if(l.key==="id"&&l.value.type===g.VARIABLE&&l.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===g.CONDITIONAL){let c=[];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),c.push(f)}}return c}}}}return null},Ya=(e,t,n,r)=>{let o=L(e.iterable,t,n,r);if(!Array.isArray(o)){let c,u=!1;if(e.iterable.type===g.FUNCTION){u=!0;let f=e.iterable.args.map(p=>p.type===g.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===g.VARIABLE?p.path:p.type===g.FUNCTION?`${p.name}(...)`:"?").join(", ");c=`${e.iterable.name}(${f})`}else c=e.iterable.path||"undefined";let d=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${c}`;throw Oo(d,o,u)}if(!e.indexVar){let c=Wa(e,o,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=qa(e,o);if(c!==null)return c}let i=Ha(e,t,n,r,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(r&&r.__paths__&&l){let c=l.split("."),u=c[0];u in r.__paths__&&(l=r.__paths__[u],c.length>1&&(l+="."+c.slice(1).join(".")))}let a=!1;e.body.type===g.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(c=>c.type===g.OBJECT&&c.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let c=0;c<o.length;c++){let u=e.indexVar?{...r,[e.itemVar]:o[c],[e.indexVar]:c}:{...r,[e.itemVar]:o[c]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${c}]`},e.indexVar&&(u.__paths__[e.indexVar]=c);let d=L(e.body,t,n,u);if(Array.isArray(d)&&d.length===1&&!a){let f=d[0];s.push(f===void 0?{}:f)}else s.push(d===void 0?{}:d)}return s},Ga=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===g.OBJECT&&s.properties.length<=10&&!s.whenCondition){let l={},a={},c=!0;for(let u of s.properties){let d=u.parsedKey?L(u.parsedKey,t,n,r):u.key,f=u.value;if(f.type===g.LITERAL)a[d]=f.value;else if(f.type===g.VARIABLE)a[d]=J(f.path,n,r);else if(f.type===g.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===g.VARIABLE){let m=J(h.path,n,r);p.push(m!=null?String(m):"")}else{c=!1;break}if(!c)break;a[d]=p.join("")}else if(f.type===g.OBJECT&&f.properties.length<=5){let p={};for(let h of f.properties){let m=h.key,y=h.value;if(y.type===g.LITERAL)p[m]=y.value;else if(y.type===g.VARIABLE)p[m]=J(y.path,n,r);else if(y.type===g.INTERPOLATION){let I=[];for(let w of y.parts)if(typeof w=="string")I.push(w);else if(w.type===g.VARIABLE){let E=J(w.path,n,r);I.push(E!=null?String(E):"")}else{c=!1;break}if(!c)break;p[m]=I.join("")}else{c=!1;break}}if(!c)break;a[d]=p}else{c=!1;break}}if(c)return l[i]=a,l}}return null},Ka=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!Pe(e.whenCondition,o,n,r))return;let i=Ga(e,t,n,r);if(i!==null)return i;if(e.fast){let c={};for(let u of e.properties){let d=u.parsedKey?L(u.parsedKey,t,n,r):u.key,f=u.value;if(f.type===g.LITERAL)c[d]=f.value;else if(f.type===g.VARIABLE)c[d]=J(f.path,n,r);else if(f.type===g.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===g.VARIABLE){let m=J(h.path,n,r);p.push(m!=null?String(m):"")}else{let m=L(h,t,n,r);p.push(m!=null?String(m):"")}c[d]=p.join("")}else c[d]=L(f,t,n,r)}return c}let s={},l=null,a=!1;for(let c of e.properties)if(!c.key.startsWith("$if ")&&!c.key.match(/^\$if\s+\w+.*:?$/)&&!c.key.startsWith("$elif")&&!c.key.startsWith("$else")&&!c.key.startsWith("$for ")){a=!0;break}for(let c of e.properties)if(c.key.startsWith("$if ")||c.key.match(/^\$if\s+\w+.*:?$/)){let u=L(c.value,t,n,r);if(!a&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(c.key.startsWith("$for ")){if(e.properties.length===1)return L(c.value,t,n,r)}else{let u=c.value;if(u&&u.type===g.OBJECT&&u.properties){let d=u.properties.find(f=>f.key.startsWith("$for "));if(d){let f=L(d.value,t,n,r);f!==void 0&&(s[c.key]=f)}else{let f=L(c.value,t,n,r);f!==void 0&&(s[c.key]=f)}}else{let d=c.parsedKey?L(c.parsedKey,t,n,r):c.key,f=L(c.value,t,n,r);f!==void 0&&(s[d]=f)}}return s},To={},Ja=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===g.LOOP){let s=L(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,n,r);s!==To&&s!==void 0&&o.push(s)}return o},Xa=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},a=t.functions||t;if(s&&!Pe(s,a,n,r))return;if(!l[o])throw new me(`Partial '${o}' is not defined`);let c=r._partialStack||[];if(c.includes(o))throw new me(`Circular partial reference detected: ${o}`);let u=l[o],d=n,f={...r,_partialStack:[...c,o]};if(r){d={...n};for(let p of Object.keys(r))p.startsWith("_")||(d[p]=r[p])}if(i){let p=L(i,t,n,r);d={...d,...p}}return L(u,t,d,f)},Qa=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),s=i[0],l=i.slice(1);if(!r||!(s in r))throw new me(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(s in r.__paths__))throw new me(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=r.__paths__[s];if(typeof a=="number"){if(l.length>0)throw new me(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return l.length>0&&(a+="."+l.join(".")),a};var Kn=ja;var Za=/\$\{([^}]*)\}/g,ec=/#\{([^}]*)\}/g,Do=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=tc(o,t);return{isFunction:!0,type:g.FUNCTION,name:r,args:i}},tc=(e,t={})=>e.trim()?nc(e).map(r=>rc(r.trim(),t)):[],nc=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],a=s>0?e[s-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,n+=l):o&&l===i&&a!=="\\"?(o=!1,i="",n+=l):!o&&l==="("?(r++,n+=l):!o&&l===")"?(r--,n+=l):!o&&l===","&&r===0?(t.push(n),n=""):n+=l}return n&&t.push(n),t},rc=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:g.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:g.LITERAL,value:parseFloat(e)};if(e==="true")return{type:g.LITERAL,value:!0};if(e==="false")return{type:g.LITERAL,value:!1};if(e==="null")return{type:g.LITERAL,value:null};let n=Do(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:l,type:a}of o){let c=0;for(;c<r.length;){let u=Je(r.substring(c),l);if(u===-1)break;let d=c+u;d>i&&(i=d,s={op:l,type:a}),c=d+l.length}}if(i!==-1)try{return ee(r,t)}catch{return{type:g.VARIABLE,path:r}}return{type:g.VARIABLE,path:r}},Po=/^\w+\(.*\)$/,oc=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,ic=e=>{if(!(!e||e.trim()===""||Po.test(e))&&oc.test(e))throw e.includes("?")&&e.includes(":")?new C(`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 C(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new C(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},No=e=>{let t=e.trim();if(Po.test(t))throw new C(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new C(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new C(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new C(`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 C(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:g.PATH_REFERENCE,path:t}},vt=(e,t={})=>{let n=e.trim();ic(n);let r=Do(n,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};if(n.includes("[")&&!/[\s+\-*/%|&?:]/.test(n)){let o=0;for(let i of n)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:g.VARIABLE,path:n}},Jn=(e,t={})=>{let n=e,r=[];(e.includes("\\${")||e.includes("\\#{"))&&(n=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),n=n.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),n=n.replace(/\\(\$\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${r.length}__`;return r.push(u),d}),n=n.replace(/\\(#\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${r.length}__`;return r.push(u),d}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...n.matchAll(Za)],i=[...n.matchAll(ec)],s=[...o.map(c=>({match:c,type:"variable"})),...i.map(c=>({match:c,type:"pathref"}))].sort((c,u)=>c.match.index-u.match.index);if(s.length===0){let c=n;for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);return{type:g.LITERAL,value:c}}if(s.length===1&&s[0].match[0]===n&&r.length===0){let{match:c,type:u}=s[0];try{return u==="variable"?vt(c[1],t):No(c[1])}catch(d){if(d.message==="Invalid array index syntax")return{type:g.LITERAL,value:n};throw d}}let l=[],a=0;for(let{match:c,type:u}of s){let[d,f]=c,p=c.index;if(p>a){let h=n.substring(a,p);for(let m=0;m<r.length;m++)h=h.replace(`__ESCAPED_${m}__`,r[m]);h&&l.push(h)}try{let h;u==="variable"?h=vt(f.trim(),t):h=No(f.trim()),l.push(h)}catch(h){if(h.message==="Invalid array index syntax")l.push(d);else throw h}a=p+d.length}if(a<n.length){let c=n.substring(a);for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);c&&l.push(c)}return{type:g.INTERPOLATION,parts:l}};var Zn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Fo=e=>Object.keys(e),ce=e=>e.join("."),Ve=(e,t,n)=>{let r=Fo(e).filter(o=>!t.has(o));if(r.length>0)throw new C(`Unexpected key '${r[0]}' in condition JSON at '${ce(n)}'`)},je=(e,t)=>typeof e=="string"?Jn(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?ac(e,t):cc(e,t):{type:g.LITERAL,value:e},sc=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new C("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new C("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new C("Empty $each body not allowed");if(n.$partial!==void 0)throw new C("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},ac=(e,t)=>{let n=[],r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let a=sc(i),c=Object.keys(a);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let u=jo(c[0],a[c[0]],t,!0);n.push(u),r=!0;continue}}catch(a){throw a instanceof C?a:new C(a.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let a=jo(l[0],i[l[0]],t);n.push(a),r=!0;continue}}let s=je(i,t);n.push(s),(s.type===g.FUNCTION||s.type===g.CONDITIONAL||s.type===g.LOOP||s.type===g.PARTIAL||s.type===g.OBJECT&&!s.fast||s.type===g.ARRAY&&!s.fast)&&(r=!0)}return{type:g.ARRAY,items:n,fast:!r}},cc=(e,t)=>{let n=[],r=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new C("$partial value must be a string");if(e.$partial.trim()==="")throw new C("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],c=[];for(let[I]of i)for(let w of a)if(I===w||I.startsWith(w+" ")||I.startsWith(w+"#")){c.push(w);break}if(c.length>0)throw new C(`Cannot use $partial with ${c.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[I,w]of Object.entries(f)){let E=I;(I.startsWith("\\$")||I.startsWith("$$"))&&(E=I.slice(1)),p[E]=w,h=!0}let m=null;if(h&&(m=je(p,t),m.type===g.OBJECT)){let I=!1;for(let w of m.properties)if(w.value.type===g.VARIABLE||w.value.type===g.INTERPOLATION||w.value.type===g.FUNCTION||w.value.type===g.CONDITIONAL||w.value.type===g.OBJECT&&!w.value.fast||w.value.type===g.ARRAY&&!w.value.fast){I=!0;break}I&&(m.fast=!1)}let y={type:g.PARTIAL,name:u,data:m};return d!==void 0&&(y.whenCondition=Vo(d,t)),y}for(let[a,c]of i)if(a==="$when"){if(o!==null)throw new C("Multiple '$when' directives on the same object are not allowed");if(c==null)throw new C("Missing condition expression after '$when'");o=Vo(c,t),r=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new C("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[a,c]=i[s];if(a==="$when"){s++;continue}if(a==="$each")throw new C("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let u=lc(i,s,t);n.push({key:a,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let u=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",d=u?`:${u}`:"";throw new C(`$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(a.startsWith("$elif ")||a.startsWith("$else"))throw new C(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new C("Missing condition expression after '$if'");{let u=je(c,t);(u.type===g.FUNCTION||u.type===g.CONDITIONAL||u.type===g.PARTIAL||u.type===g.OBJECT&&!u.fast||u.type===g.ARRAY&&!u.fast)&&(r=!0);let d=Jn(a,t),f={key:a,value:u};(d.type!==g.LITERAL||d.value!==a)&&(f.parsedKey=d),n.push(f),s++}}}let l={type:g.OBJECT,properties:n,fast:!r};return o&&(l.whenCondition=o),l},lc=(e,t,n={})=>{let r=[],o=[],i=t,[s,l]=e[i],a=null,c;if(s.startsWith("$if#")){let d=s.match(/^\$if#(\w+)\s+(.+)$/);if(d)a=d[1],c=d[2];else throw new C(`Invalid conditional syntax: ${s}`)}else c=s.substring(4),c.endsWith(":")&&(c=c.slice(0,-1).trim());Gn(c);let u=ee(c,n);for(r.push(u),o.push(je(l,n)),i++;i<e.length;){let[d,f]=e[i],p=!1,h;if(a?d.startsWith(`$elif#${a} `)?(h=d.substring(`$elif#${a} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(d===`$else#${a}`||d===`$else#${a}:`)&&(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)r.push(null);else{Gn(h);let m=ee(h,n);r.push(m)}if(o.push(je(f,n)),i++,h===null)break}else break}return{node:{type:g.CONDITIONAL,conditions:r,bodies:o,id:a},nextIndex:i}},Xn={eq:k.EQ,neq:k.NEQ,gt:k.GT,gte:k.GTE,lt:k.LT,lte:k.LTE,in:k.IN,add:k.ADD,sub:k.SUBTRACT},Qn={all:k.AND,any:k.OR},uc=new Set(["var","literal","call","not",...Object.keys(Xn),...Object.keys(Qn)]),dc=(e,t,n)=>{if(!Array.isArray(e))throw new C(`Condition JSON operator '${t}' at '${ce(n)}' requires an array`);if(e.length!==2)throw new C(`Condition JSON operator '${t}' at '${ce(n)}' requires exactly 2 operands`);return e},fc=(e,t,n,r,o)=>{if(!Array.isArray(e))throw new C(`Condition JSON operator '${t}' at '${ce(o)}' requires an array`);if(e.length===0)throw new C(`Condition JSON operator '${t}' at '${ce(o)}' requires at least 1 condition`);return e.map((s,l)=>ye(s,r,[...o,l])).reduce((s,l)=>({type:g.BINARY,op:n,left:s,right:l}))},pc=(e,t,n)=>{let r,o;if(typeof e.call=="string")r=e.call,o=e.args??[],Ve(e,new Set(["call","args"]),n);else if(Zn(e.call))r=e.call.name,o=e.call.args??[],Ve(e,new Set(["call"]),n),Ve(e.call,new Set(["name","args"]),[...n,"call"]);else throw new C(`Condition JSON call at '${ce(n)}' requires a function name`);if(typeof r!="string"||r.trim()==="")throw new C(`Condition JSON call at '${ce(n)}' requires a non-empty function name`);if(!/^\w+$/.test(r))throw new C(`Invalid condition JSON function name '${r}' at '${ce(n)}'`);if(!Array.isArray(o))throw new C(`Condition JSON call '${r}' at '${ce(n)}' requires args to be an array`);return{type:g.FUNCTION,name:r,args:o.map((i,s)=>ye(i,t,[...n,"args",s]))}},ye=(e,t={},n=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:g.LITERAL,value:e};if(Array.isArray(e))throw new C(`Condition JSON array at '${ce(n)}' must be wrapped in an operator or { literal: [...] }`);if(!Zn(e))throw new C(`Invalid condition JSON value at '${ce(n)}'`);let r=Fo(e);if(r.length===0)throw new C(`Condition JSON object at '${ce(n)}' must contain an operator`);let o=r.filter(s=>uc.has(s));if(o.length===0)throw new C(`Unknown condition JSON operator '${r[0]}' at '${ce(n)}'`);if(o.length>1)throw new C(`Condition JSON at '${ce(n)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(Ve(e,new Set(["var"]),n),typeof e.var!="string"||e.var.trim()==="")throw new C(`Condition JSON var at '${ce(n)}' requires a non-empty path`);return{type:g.VARIABLE,path:e.var}}if(i==="literal")return Ve(e,new Set(["literal"]),n),{type:g.LITERAL,value:e.literal};if(i==="call")return pc(e,t,n);if(i==="not")return Ve(e,new Set(["not"]),n),{type:g.UNARY,op:ut.NOT,operand:ye(e.not,t,[...n,"not"])};if(i in Qn)return Ve(e,new Set([i]),n),fc(e[i],i,Qn[i],t,[...n,i]);if(i in Xn){Ve(e,new Set([i]),n);let s=dc(e[i],i,[...n,i]);return{type:g.BINARY,op:Xn[i],left:ye(s[0],t,[...n,i,0]),right:ye(s[1],t,[...n,i,1])}}throw new C(`Unknown condition JSON operator '${i}' at '${ce(n)}'`)},Vo=(e,t={})=>{if(e==null)throw new C("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new C("Empty condition expression after '$when'");return ee(e,t)}return Zn(e)||Array.isArray(e)?ye(e,t):{type:g.LITERAL,value:e}},ee=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let c=e.slice(1,-1),u=0,d=!0;for(let f=0;f<c.length;f++)if(c[f]==="("?u++:c[f]===")"&&u--,u<0){d=!1;break}if(d&&u===0)return ee(c,t)}let n=Je(e,"||");if(n!==-1)return{type:g.BINARY,op:k.OR,left:ee(e.substring(0,n).trim(),t),right:ee(e.substring(n+2).trim(),t)};let r=Je(e,"&&");if(r!==-1)return{type:g.BINARY,op:k.AND,left:ee(e.substring(0,r).trim(),t),right:ee(e.substring(r+2).trim(),t)};let o=[{op:">=",type:k.GTE},{op:"<=",type:k.LTE},{op:"==",type:k.EQ},{op:"!=",type:k.NEQ},{op:">",type:k.GT},{op:"<",type:k.LT},{op:" in ",type:k.IN}];for(let{op:c,type:u}of o){let d=Je(e,c);if(d!==-1)return{type:g.BINARY,op:u,left:ee(e.substring(0,d).trim(),t),right:ee(e.substring(d+c.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:k.ADD},{op:" - ",type:k.SUBTRACT}];for(let{op:c,type:u}of l){let d=0;for(;d<e.length;){let f=Je(e.substring(d),c);if(f===-1)break;let p=d+f;p>i&&(i=p,s={op:c,type:u}),d=p+c.length}}if(i!==-1&&s)return{type:g.BINARY,op:s.type,left:ee(e.substring(0,i).trim(),t),right:ee(e.substring(i+s.op.length).trim(),t)};let a=[" * "," / "," % "];for(let c of a)if(Je(e,c)!==-1)throw new C(`Arithmetic operations are not allowed in conditionals: "${c}"`);return e.startsWith("!")?{type:g.UNARY,op:ut.NOT,operand:ee(e.substring(1).trim(),t)}:Mo(e,t)},Je=(e,t)=>{let n=0,r=0;for(;r<=e.length-t.length;){if(e[r]==="(")n++;else if(e[r]===")")n--;else if(n===0&&e.substring(r,r+t.length)===t)return r;r++}return-1},hc=e=>{if(e=e.trim(),e==="true")return{type:g.LITERAL,value:!0};if(e==="false")return{type:g.LITERAL,value:!1};if(e==="null")return{type:g.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:g.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:g.LITERAL,value:""};if(e==="{}")return{type:g.LITERAL,value:{}};if(e==="[]")return{type:g.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:g.LITERAL,value:t}:{type:g.VARIABLE,path:e}},Mo=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return vt(n,t);let o=hc(n);if(o.type===g.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:g.VARIABLE,path:n};try{return vt(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},mc=(e,t=!1)=>{let n=t?"$each":"$for";try{So(e)}catch(r){if(r instanceof C&&t){let o=r.message.replace(/\$for/g,"$each");throw new C(o.replace("Parse Error: ",""))}throw r}},jo=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=r?"$each":"$for";throw new C(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],l=i[2].trim();mc(l,r);let a=l.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let y=r?"$each":"$for";throw new C(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${l}')`)}let c=a[1].trim(),u=a[2].trim(),d,f=null;if(c.includes(",")){let y=c.split(",").map(I=>I.trim());if(y.length!==2)throw new C(`Invalid loop variables: ${c}. Expected format: "item" or "item, index"`);d=y[0],f=y[1]}else d=c;let p=["this","undefined","null","true","false"];if(p.includes(d))throw new C(`Reserved variable name: ${d}`);if(f&&p.includes(f))throw new C(`Reserved variable name: ${f}`);let h=Mo(u,n),m=je(t,n);return{type:g.LOOP,itemVar:d,indexVar:f,iterable:h,body:m,flatten:s!=="nested"}};var gc=(e,t={})=>{let{functions:n={}}=t;return je(e,n)},Qt=gc;var Ct={};Ra(Ct,{now:()=>yc});var yc=()=>Date.now();var bc=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...Ct,...r},s=Qt(e,{functions:i}),l={};for(let[a,c]of Object.entries(o))l[a]=Qt(c,{functions:i});return Kn(s,t,{functions:i,partials:l})},le=bc;var Ic=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Ac=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,wc=(e,t)=>{if(Ic(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new C("Empty condition expression");return ee(e,t)}return ye(e,t)},Ec=(e,t={},n={})=>{let r=Ac(n),o={...Ct,...r},i=wc(e,o);return!!Pe(i,{functions:o,partials:{}},t,{})},er=Ec;var ur=Symbol("runStoreTransaction"),or="__routeEngineConditionComparison",Zt=(e,t)=>typeof e=="number"&&typeof t=="number"&&Number.isFinite(e)&&Number.isFinite(t)||typeof e=="string"&&typeof t=="string",Fe=Object.freeze({eq:(e,t)=>e===t,neq:(e,t)=>e!==t,gt:(e,t)=>Zt(e,t)&&e>t,gte:(e,t)=>Zt(e,t)&&e>=t,lt:(e,t)=>Zt(e,t)&&e<t,lte:(e,t)=>Zt(e,t)&&e<=t}),Yo=Object.freeze(Object.fromEntries(Object.keys(Fe).map(e=>[e,`${or}${e}`]))),xc=Object.freeze(Object.fromEntries(Object.entries(Yo).map(([e,t])=>[t,Fe[e]]))),Uo=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),vc=e=>{if(typeof e?.call=="string")return e.call;if(e?.call!==null&&typeof e?.call=="object"&&!Array.isArray(e.call))return e.call.name},en=e=>{if(Array.isArray(e))return e.map(en);if(e===null||typeof e!="object"||Uo(e,"literal")||Uo(e,"var"))return e;if(vc(e)?.startsWith(or))throw new Error(`Condition function names beginning with "${or}" are reserved`);let n=Object.entries(e);if(n.length===1){let[[r,o]]=n,i=Yo[r];if(i)return{call:i,args:o.map(en)}}return Object.fromEntries(n.map(([r,o])=>[r,en(o)]))},Ot=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return ye(e),er(en(e),t,{functions:xc})},Cc=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Go=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:l=c=>c}=n;for(let[c,u]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...d)=>u(s(r),...d):i[c]=(...d)=>{let f;return r=Yn(r,h=>{let m=u(l(h),...d);f=m!==void 0&&!ae(m)?m:void 0}),f});let a=c=>{if(typeof c!="function")throw new Error("Store transaction requires a callback");let u=r;try{return c()}catch(d){throw r=u,d}};return{...o,...i,[ur]:a}},on=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return Yn(r,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var Sc=(e,t)=>{if(e.default!==void 0)return e.default;let n=["number","boolean","string","object"];if(!n.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${n.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},T=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),ir=(e,t,n)=>{Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})},_e=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ko=e=>{let t=ae(e)?Ke(e):e;return structuredClone(t)},Oc=({characterId:e,resourceCharacter:t,variables:n={}}={})=>{if(!T(t,"nameVariableId"))return;let r=t.nameVariableId,o=n?.[r];if(typeof o!="string")throw new Error(`Character "${e}" nameVariableId "${r}" must resolve to a string variable`);return o},sn=({characterId:e,character:t,characterName:n,characters:r={},variables:o={}}={})=>{let i=e?r?.[e]:void 0;if(t?.name!==void 0)return t.name;if(n!==void 0)return n;let s=Oc({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},Ce=e=>T(e,"computed"),dt=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([n])=>!Ce(t[n]))),we=(e,t)=>new Error(`${t} has invalid path: ${JSON.stringify(e)}`),Rc=(e,t,n)=>{if(e[0]==='"')try{return JSON.parse(e)}catch{throw we(t,n)}let o="";for(let i=1;i<e.length-1;i+=1){let s=e[i];if(s!=="\\"){if(s.charCodeAt(0)<32)throw we(t,n);o+=s;continue}if(i+=1,i>=e.length-1)throw we(t,n);let l=e[i];if(l==="u"){let c=e.slice(i+1,i+5);if(c.length!==4||!/^[0-9a-fA-F]{4}$/.test(c))throw we(t,n);o+=String.fromCharCode(Number.parseInt(c,16)),i+=4;continue}let a={"\\":"\\",'"':'"',"'":"'","/":"/",n:`
2
- `,r:"\r",t:" ",b:"\b",f:"\f"};if(!T(a,l))throw we(t,n);o+=a[l]}return o},Jo=(e,t="Computed expression var")=>{if(typeof e!="string"||e.length===0||e.trim()!==e)throw we(e,t);let n=[],r=0,o=()=>{let s=r;for(;r<e.length&&e[r]!=="."&&e[r]!=="["&&e[r]!=="]";)r+=1;let l=e.slice(s,r);if(l.length===0||l.trim()!==l||/\s/.test(l))throw we(e,t);n.push(l)},i=()=>{for(r+=1;r<e.length&&/\s/.test(e[r]);)r+=1;let s=e[r];if(/\d/.test(s??"")){let u=r;for(;r<e.length&&/\d/.test(e[r]);)r+=1;let d=e.slice(u,r);for(;r<e.length&&/\s/.test(e[r]);)r+=1;if(e[r]!=="]"||d.length>1&&d.startsWith("0"))throw we(e,t);r+=1,n.push(d);return}if(s!=='"'&&s!=="'")throw we(e,t);let l=s,a=r;r+=1;let c=!1;for(;r<e.length;){let u=e[r];if(c)c=!1;else if(u==="\\")c=!0;else if(u===l){let d=e.slice(a,r+1);for(r+=1;r<e.length&&/\s/.test(e[r]);)r+=1;if(e[r]!=="]")throw we(e,t);r+=1,n.push(Rc(d,e,t));return}r+=1}if(c||r>=e.length)throw we(e,t)};for(o();r<e.length;){if(e[r]==="."){r+=1,o();continue}if(e[r]==="["){i();continue}throw we(e,t)}return n},tr=(e,t)=>{let n=e;for(let r of t){if(n==null||!T(n,r))return;n=n[r]}return n},Xo=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let n=Jo(e),[r,o,...i]=n;if(r==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return tr(s,i)}return r==="runtime"?tr(t.runtime,n.slice(1)):tr(t,n)},Qo=(e,t,n)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(n!==void 0&&t.length!==n)throw new Error(`Computed expression operator "${e}" requires ${n} operand(s)`)},sr=(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`)},_c=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},ve=(e,t,n,r)=>(Qo(e,t,r),t.map(o=>rn(o,n))),Ae=(e,t,n,r)=>{let o=ve(e,t,n,r);return o.forEach(i=>_c(e,i)),o},kc=(e,t,n)=>{switch(e){case"var":return Xo(t,n);case"add":{let[r,o]=Ae(e,t,n,2);return r+o}case"sub":{let[r,o]=Ae(e,t,n,2);return r-o}case"mul":{let[r,o]=Ae(e,t,n,2);return r*o}case"div":{let[r,o]=Ae(e,t,n,2);return r/o}case"mod":{let[r,o]=Ae(e,t,n,2);return r%o}case"neg":{let[r]=Ae(e,t,n,1);return-r}case"round":{let[r]=Ae(e,t,n,1);return Math.round(r)}case"floor":{let[r]=Ae(e,t,n,1);return Math.floor(r)}case"ceil":{let[r]=Ae(e,t,n,1);return Math.ceil(r)}case"min":{let[r,o]=Ae(e,t,n,2);return Math.min(r,o)}case"max":{let[r,o]=Ae(e,t,n,2);return Math.max(r,o)}case"clamp":{let[r,o,i]=Ae(e,t,n,3);return Math.min(i,Math.max(o,r))}case"eq":{let[r,o]=ve(e,t,n,2);return Fe.eq(r,o)}case"neq":{let[r,o]=ve(e,t,n,2);return Fe.neq(r,o)}case"gt":{let[r,o]=ve(e,t,n,2);return Fe.gt(r,o)}case"gte":{let[r,o]=ve(e,t,n,2);return Fe.gte(r,o)}case"lt":{let[r,o]=ve(e,t,n,2);return Fe.lt(r,o)}case"lte":{let[r,o]=ve(e,t,n,2);return Fe.lte(r,o)}case"in":{let[r,o]=ve(e,t,n,2);return Array.isArray(o)?o.includes(r):!1}case"and":case"all":return sr(e,t),t.every(r=>!!rn(r,n));case"or":case"any":return sr(e,t),t.some(r=>!!rn(r,n));case"not":{let[r]=ve(e,t,n,1);return!r}case"length":{let[r]=ve(e,t,n,1);return typeof r=="string"||Array.isArray(r)?r.length:_e(r)?Object.keys(r).length:0}case"includes":{let[r,o]=ve(e,t,n,2);return typeof r=="string"?typeof o=="string"&&r.includes(o):Array.isArray(r)?r.includes(o):!1}case"literal":return Ko(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},rn=(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 n=Object.entries(e);if(n.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[r,o]]=n;return kc(r,o,t)},ar=(e,t)=>{if(e===null||typeof e!="object"||T(e,"literal"))return e;if(T(e,"var"))return{literal:Xo(e.var,t)};if(T(e,"call"))throw new Error("Function calls are not supported in computed-variable conditions");return Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Array.isArray(r)?r.map(o=>ar(o,t)):ar(r,t)]))},$c=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return ye(e),Ot(ar(e,t))},Zo=(e,t)=>{if(!_e(e))throw new Error(`${t} must be an object`);let n=T(e,"expr"),r=T(e,"value");if(n===r)throw new Error(`${t} must contain exactly one of expr or value`)},nr=(e,t,n)=>(Zo(e,t),T(e,"value")?Ko(e.value):rn(e.expr,n)),Lc=(e,t={},n="unknown")=>{if(!_e(e))throw new Error(`Computed variable "${n}" computed must be an object`);let r=T(e,"expr"),o=T(e,"value");if(T(e,"branches")){if(r||o)throw new Error(`Computed variable "${n}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${n}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${n}" branches must not be empty`);if(!_e(e.default))throw new Error(`Computed variable "${n}" requires default`);for(let s=0;s<e.branches.length;s+=1){let l=e.branches[s];if(!_e(l))throw new Error(`Computed variable "${n}" branch ${s} must be an object`);if(!T(l,"when"))throw new Error(`Computed variable "${n}" branch ${s} requires when`);if($c(l.when,t))return nr(l,`Computed variable "${n}" branch ${s}`,t)}return nr(e.default,`Computed variable "${n}" default`,t)}if(r===o)throw new Error(`Computed variable "${n}" must contain exactly one of expr, value, or branches`);return nr(e,`Computed variable "${n}"`,t)},ei=(e,t,n)=>{switch(t){case"number":if(typeof n!="number"||!Number.isFinite(n))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(n)?"array":typeof n}`);return;case"boolean":if(typeof n!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(n)?"array":typeof n}`);return;case"string":if(typeof n!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(n)?"array":typeof n}`);return;case"object":if(n===null||typeof n!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof n}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},Tc=Object.freeze({add:2,sub:2,mul:2,div:2,mod:2,neg:1,round:1,floor:1,ceil:1,min:2,max:2,clamp:3,eq:2,neq:2,gt:2,gte:2,lt:2,lte:2,in:2,not:1,length:1,includes:2}),Nc=new Set(["and","or","all","any"]),Dc=new Set(["add","sub","mul","div","mod","neg","round","floor","ceil","min","max","clamp","length"]),Pc=new Set(["add","sub","mul","div","mod","neg","round","floor","ceil","min","max","clamp"]),Vc=new Set(["eq","neq","gt","gte","lt","lte","in","and","or","all","any","not","includes"]),jc=new Set(["all","any","eq","neq","gt","gte","lt","lte","in","add","sub"]),ti=new WeakMap,Bo=e=>e===null?"null":Array.isArray(e)?"object":typeof e,tn=(e,t,n)=>{for(let r of Object.keys(e))if(!t.has(r))throw new Error(`${n} contains unsupported property "${r}"`)},Fc=(e,t,n,r)=>{if(n!==void 0&&n!==t)throw new Error(`Computed variable "${e}" ${r} expected type ${t}, got ${n}`)},ni=(e,{variableId:t,variableConfigs:n,dependencies:r,path:o})=>{let i=`Computed variable "${t}" ${o} var`,[s,l,...a]=Jo(e,i);if(s!=="variables"&&s!=="runtime")throw new Error(`${i} must reference variables.* or runtime.*, got ${JSON.stringify(e)}`);if(!l)throw new Error(`${i} must reference a concrete ${s} member, got ${JSON.stringify(e)}`);if(s==="runtime")return;if(!T(n,l))throw new Error(`Computed variable "${t}" ${o} references unknown variable "${l}"`);let c=n[l];return Ce(c)&&r.add(l),a.length===0?c?.type:void 0},ri=(e,{variableId:t,variableConfigs:n,dependencies:r,path:o})=>{if(e===null||typeof e!="object"){if(typeof e=="number"&&!Number.isFinite(e))throw new Error(`Computed variable "${t}" ${o} must use finite numeric literals`);return Bo(e)}if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let i=Object.entries(e);if(i.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[s,l]]=i;if(s==="var"){if(typeof l!="string"||l.trim()==="")throw new Error("Computed expression var requires a non-empty string path");return ni(l,{variableId:t,variableConfigs:n,dependencies:r,path:o})}if(s==="literal"){if(typeof l=="number"&&!Number.isFinite(l))throw new Error(`Computed variable "${t}" ${o} must use finite numeric literals`);return Bo(l)}let a=Tc[s];if(a===void 0&&!Nc.has(s))throw new Error(`Unknown computed expression operator: ${s}`);a===void 0?sr(s,l):Qo(s,l,a);let c=l.map((u,d)=>ri(u,{variableId:t,variableConfigs:n,dependencies:r,path:`${o}.${s}[${d}]`}));if(Pc.has(s)&&c.forEach(u=>{if(u!==void 0&&u!=="number")throw new Error(`Computed expression operator "${s}" requires numeric operands`)}),Dc.has(s))return"number";if(Vc.has(s))return"boolean"},Mc=(e,{variableId:t,variableConfigs:n,dependencies:r,path:o})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");try{ye(e)}catch(s){throw new Error(`Computed variable "${t}" ${o} is invalid: ${s.message}`,{cause:s})}let i=(s,l)=>{if(s===null||typeof s!="object"||T(s,"literal"))return;if(T(s,"var")){ni(s.var,{variableId:t,variableConfigs:n,dependencies:r,path:l});return}if(T(s,"call"))throw new Error(`Computed variable "${t}" ${l} function calls are not supported`);if(T(s,"not")){i(s.not,`${l}.not`);return}let a=Object.keys(s).find(c=>jc.has(c));s[a].forEach((c,u)=>{i(c,`${l}.${a}[${u}]`)})};i(e,o)},rr=(e,{variableId:t,variableConfig:n,variableConfigs:r,dependencies:o,path:i,allowedKeys:s=new Set(["expr","value"])})=>{if(Zo(e,`Computed variable "${t}" ${i}`),tn(e,s,i),T(e,"value")){ei(t,n.type,e.value);return}let l=ri(e.expr,{variableId:t,variableConfigs:r,dependencies:o,path:`${i}.expr`});Fc(t,n.type,l,`${i}.expr`)},Uc=(e,t,n)=>{let r=t.computed;if(!_e(r))throw new Error(`Computed variable "${e}" computed must be an object`);let o=new Set,i=T(r,"expr"),s=T(r,"value");if(T(r,"branches")){if(tn(r,new Set(["branches","default"]),`Computed variable "${e}" computed`),i||s)throw new Error(`Computed variable "${e}" cannot combine branches with expr or value`);if(!Array.isArray(r.branches))throw new Error(`Computed variable "${e}" branches must be an array`);if(r.branches.length===0)throw new Error(`Computed variable "${e}" branches must not be empty`);if(!_e(r.default))throw new Error(`Computed variable "${e}" requires default`);return r.branches.forEach((a,c)=>{if(!_e(a))throw new Error(`Computed variable "${e}" branch ${c} must be an object`);if(tn(a,new Set(["when","expr","value"]),`Computed variable "${e}" branch ${c}`),!T(a,"when"))throw new Error(`Computed variable "${e}" branch ${c} requires when`);Mc(a.when,{variableId:e,variableConfigs:n,dependencies:o,path:`computed.branches[${c}].when`}),rr(a,{variableId:e,variableConfig:t,variableConfigs:n,dependencies:o,path:`computed.branches[${c}]`,allowedKeys:new Set(["when","expr","value"])})}),rr(r.default,{variableId:e,variableConfig:t,variableConfigs:n,dependencies:o,path:"computed.default"}),o}if(tn(r,new Set(["expr","value"]),`Computed variable "${e}" computed`),i===s)throw new Error(`Computed variable "${e}" must contain exactly one of expr, value, or branches`);return rr(r,{variableId:e,variableConfig:t,variableConfigs:n,dependencies:o,path:"computed"}),o},Xe=(e={})=>{if(!_e(e))throw new Error("Variable configs must be an object");if(T(e,"__proto__"))throw new Error('Variable id "__proto__" is reserved');if(T(e,""))throw new Error("Variable ids must not be empty");let t=new Map;Object.entries(e).forEach(([i,s])=>{if(Ce(s)){if(!_e(s))throw new Error(`Computed variable "${i}" must be an object`);if(!T(s,"type"))throw new Error(`Computed variable "${i}" requires type`);if(!T(s,"scope"))throw new Error(`Computed variable "${i}" requires scope`);if(T(s,"default"))throw new Error(`Computed variable "${i}" must not declare a top-level default`);if(_t(s.scope,i),!["number","boolean","string","object"].includes(s.type))throw new Error(`Invalid variable type: ${s.type} for computed variable ${i}`);t.set(i,Uc(i,s,e))}});let n=new Set,r=[];t.forEach((i,s)=>{if(n.has(s))return;let l=[{variableId:s,dependencies:[...t.get(s)??[]],nextDependencyIndex:0}],a=new Map([[s,0]]);for(;l.length>0;){let c=l.at(-1);if(c.nextDependencyIndex>=c.dependencies.length){l.pop(),a.delete(c.variableId),n.add(c.variableId),r.push(c.variableId);continue}let u=c.dependencies[c.nextDependencyIndex];if(c.nextDependencyIndex+=1,n.has(u))continue;let d=a.get(u);if(d!==void 0){let f=[...l.slice(d).map(({variableId:p})=>p),u].join(" -> ");throw new Error(`Computed variable cycle detected: ${f}`)}a.set(u,l.length),l.push({variableId:u,dependencies:[...t.get(u)??[]],nextDependencyIndex:0})}});let o=Object.freeze({evaluationOrder:Object.freeze(r)});return ti.set(e,o),o},Rt=({variables:e={},runtime:t={},variableConfigs:n={},eager:r=!0}={})=>{let{evaluationOrder:o}=ti.get(n)??Xe(n),i=dt(e,n),s=Object.entries(n).filter(([,y])=>Ce(y)).map(([y])=>y),l=Object.create(null),a=[],c=new Map(o.map((y,I)=>[y,I])),u=-1,d=!1,f=y=>{if(T(l,y))return l[y];let I=n[y];if(!Ce(I))return T(i,y)?i[y]:void 0;let w=a.indexOf(y);if(w>=0){let E=[...a.slice(w),y].join(" -> ");throw new Error(`Computed variable cycle detected: ${E}`)}a.push(y);try{let E=Lc(I.computed,m,y);return ei(y,I.type,E),ir(l,y,E),E}finally{a.pop()}},p=y=>{if(T(l,y))return l[y];let I=n[y];if(!Ce(I))return T(i,y)?i[y]:void 0;let w=c.get(y);if(r&&!d&&w!==void 0&&w>u){d=!0;try{for(let E=u+1;E<=w;E+=1)f(o[E]),u=E}finally{d=!1}return l[y]}return f(y)},h=new Proxy({},{get:(y,I)=>{if(typeof I=="string")return p(I)},has:(y,I)=>typeof I=="string"&&(T(i,I)||s.includes(I)),ownKeys:()=>[...new Set([...Object.keys(i),...s])],getOwnPropertyDescriptor:(y,I)=>{if(!(typeof I!="string"||!T(i,I)&&!s.includes(I)))return{enumerable:!0,configurable:!0}}}),m={variables:h,runtime:t,resolveVariable:p};return r?(s.forEach(y=>{p(y)}),{...i,...l}):h},Bc=({variables:e={},runtime:t={},variableConfigs:n,projectData:r}={})=>{let o=n??r?.resources?.variables??{};return Xe(o),Rt({variables:e,runtime:t,variableConfigs:o,eager:!0})},an=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{if(Ce(o))return;let i=Sc(o,r);o.scope==="context"?ir(t,r,i):ir(n,r,i)}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},_t=(e,t)=>{let n=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!n.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${n.join(", ")}`)},cn=(e,t,n)=>{let r={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=r[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${n}`);if(!Object.values(r).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${n}" of type "${e}". Valid operations: ${o.join(", ")}`)},zc=2,zo=12,oi=(e=zc)=>{if(!Number.isInteger(e)||e<0||e>zo)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${zo}.`);return e},qc=(e,t)=>{let n=10**t;return Math.round((e+Number.EPSILON)*n)/n},nn=e=>typeof e=="number"&&Number.isFinite(e),dr=(e,t,n,r,o={})=>{if(e==="number"){if(t==="set"&&!nn(n))throw new Error(`Operation "set" requires value to be a number for variable "${r}".`);if(t==="multiply"&&!nn(n))throw new Error(`Operation "multiply" requires value to be a number for variable "${r}".`);if(t==="divide"&&!nn(n))throw new Error(`Operation "divide" requires value to be a number for variable "${r}".`);if(t==="divide"){if(n===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${r}".`);oi(o.roundTo)}}},ln=(e,t,n,r={})=>{let o=(s,l,a)=>{let c=s??l;if(!nn(c))throw new Error(`Operation "${t}" requires ${a} to be a number.`);return c},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 n;case"multiply":return o(e,1,"current value")*o(n,void 0,"value");case"divide":return qc(o(e,0,"current value")/i(n),oi(r.roundTo));case"increment":return o(e,0,"current value")+o(n,1,"value");case"decrement":return o(e,0,"current value")-o(n,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var fr=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let n=new Date(e),r=s=>String(s).padStart(2,"0"),o=String(n.getFullYear()),i={DD:r(n.getDate()),MM:r(n.getMonth()+1),MMM:Cc[n.getMonth()],YYYY:o,YY:o.slice(-2),HH:r(n.getHours()),mm:r(n.getMinutes()),ss:r(n.getSeconds())};return t.replace(/YYYY|MMM|YY|MM|DD|HH|mm|ss/g,s=>i[s])},Hc=(e,t)=>{let n=i=>i?.ui,r=n(e),o=n(t);return JSON.stringify(r)===JSON.stringify(o)?null:r&&!o?{changeType:"delete",data:e}:o&&!r?{changeType:"add",data:t}:o&&r?{changeType:"update",data:t}:null},St=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,Wc=(e,t)=>{let n=e?.character?.sprite,r=t?.character?.sprite,o=St(n)?n:void 0,i=St(r)?r:void 0;return JSON.stringify(o)===JSON.stringify(i)?null:o&&!i?{changeType:"delete",data:o}:i&&!o?{changeType:"add",data:i}:i&&o?{changeType:"update",data:i}:null},qo=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};e.transformId!==void 0&&(t.transformId=e.transformId);for(let n of["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"])e[n]!==void 0&&(t[n]=e[n]);for(let n of["animationName","animationSpeed","loop"])e[n]!==void 0&&(t[n]=e[n]);return t},Ho=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},Wo=(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,Yc=(e,t)=>{let n={},r=Wo(qo(e),qo(t)),o=Wo(Ho(e),Ho(t));return r&&(n.resource=r),o&&(n.color=o),Object.keys(n).length>0?n:null},pr=(e={},t={})=>{let n={},r=["sfx","voice"],o=a=>{let c=e[a],u=t[a];u&&!c?n[a]={changeType:"add",data:u}:c&&!u?r.includes(a)||(n[a]={changeType:"delete",data:c}):c&&u&&JSON.stringify(c)!==JSON.stringify(u)&&(n[a]={changeType:"update",data:u})},i=Yc(e.background,t.background);i&&(n.background=i),o("screen"),o("bgm"),o("voice");let s=Hc(e.dialogue,t.dialogue);s&&(n.dialogue=s);let l=Wc(e.dialogue,t.dialogue);return l&&(n.dialogueSprite=l),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},hr=(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 n=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};n("layout"),n("choice"),n("form"),n("screen"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let r=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(l=>{let a={...l};return delete a.animations,i(a)?a:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return r("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),r("visual",o=>o.resourceId||o.transformId),t},Gc=(e,t)=>{if(!e||!t)return;let n=e;for(let r of t.split(".")){if(n==null||!(r in Object(n)))return;n=n[r]}return n},Kc=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let n=e.slice(7),r=Gc(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},Jc={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"])},ii=(e,t)=>{let n=e[e.length-1];return n?Jc[n]?.has(t)===!0:!1},cr=(e,t,n=[])=>Array.isArray(e)?e.map(r=>cr(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,ii(n,r)?o:cr(o,t,[...n,r])])):Kc(e,t),lr=(e,t,n=[])=>Array.isArray(e)?e.map(r=>lr(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,ii(n,r)?o:lr(o,t,[...n,r])])):typeof e=="string"?le(e,t):e,mr=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let n=cr(e,t._event);return lr(n,t)};var W=e=>structuredClone(ae(e)?Ke(e):e),V=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),si=e=>e?.animations?.playback?.continuity==="persistent",P=(e,t)=>V(e??{},t)&&e[t]!==void 0,kt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:W(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Xc=e=>P(e,"opacity")||P(e,"blur"),fi=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],pi=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],gr=["animationName","animationSpeed","loop"],Qc=e=>fi.some(t=>P(e,t)),hi=e=>e?.text&&P(e.text,"content")&&P(e.text,"textStyleId"),mi=e=>P(e,"text"),Zc=(e,t)=>e.resourceId?!0:hi(e)?!t?.text:!1,el=(e,t)=>{let n={...W(e),...t};return t.text&&e.text&&(n.text={...W(e.text),...W(t.text)}),n},tl=(e,t)=>{if(mi(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!hi(e)&&!t?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},ai=e=>pi.some(t=>P(e,t)),ci=e=>gr.some(t=>P(e,t)),nl=(e,t,{hasAuthoredTransformId:n=!1}={})=>{if(!t)return e;for(let r of pi)!n&&!P(e,r)&&P(t,r)&&(e[r]=t[r]),V(e,r)&&e[r]===void 0&&delete e[r];return e},gi=(e,t,n)=>{let r=e[n];return r?.id===t?.id?r:e.find(o=>o.id===t?.id)},rl=(e,t)=>{if(!t)return e;for(let n of fi)!P(e,n)&&P(t,n)&&(e[n]=t[n]),V(e,n)&&e[n]===void 0&&delete e[n];return e},ol=(e,t)=>(t&&(!P(e,"opacity")&&P(t,"opacity")&&(e.opacity=t.opacity),!P(e,"blur")&&P(t,"blur")&&(e.blur=W(t.blur)),V(e,"opacity")&&e.opacity===void 0&&delete e.opacity,V(e,"blur")&&e.blur===void 0&&delete e.blur),e),yi=(e,t,n=[],{hasPatchFn:r=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,l)=>{let a=gi(n,s,l),c=t(s,a),u=Xc(s),d=Qc(s),f=r(s),p=V(s,"animations"),h=W(s);return!c&&(u||d||f)&&a&&(h=o?o(a,h):{...W(a),...h},p||delete h.animations),ol(rl(h,a),a)}).filter(s=>t(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},il=e=>{if(e){if(e.character&&V(e.character,"name"))return e.character.name;if(V(e,"characterName"))return e.characterName}},bi=e=>!!e?.character&&V(e.character,"sprite"),sl=e=>{let t={},n=!1,r=il(e);return r!==void 0&&(t.name=r,n=!0),bi(e)&&(t.sprite=W(e.character.sprite),n=!0),n?t:void 0},li=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},ui=({dialogueState:e,dialogueAction:t,persistCharacter:n})=>V(t,"persistSprite")?t.persistSprite===!0:V(e,"persistSprite")?e.persistSprite===!0:n&&!V(t,"characterId"),di=({previousCharacter:e,characterFields:t,hasCharacterId:n,persistCharacter:r,persistSprite:o,hasExplicitPersistSprite:i,isAppendingAdvDialogueContent:s})=>{let l={},a=e??{},c=t??{},u=s&&!n,d=u&&!i;return V(c,"name")?l.name=c.name:(r&&!n||u)&&V(a,"name")&&(l.name=W(a.name)),V(c,"sprite")?l.sprite=W(c.sprite):(o||d)&&V(a,"sprite")&&(l.sprite=W(a.sprite)),Object.keys(l).length>0?l:void 0},al=({dialogueState:e,content:t,append:n=!1})=>{if(!n||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let r=Array.isArray(e.content)?e.content:[];r.length>0?e.initialRevealedContent=r.map(o=>W(o)):delete e.initialRevealedContent,e.content=[...r,...t]},cl=()=>({}),ll=(e,t)=>{if(!t.screen)return;let n=P(t.screen,"opacity"),r=P(t.screen,"blur"),o=V(t.screen,"animations");if(!n&&!r){o||delete e.screen;return}let i=e.screen,s={};if(n?s.opacity=t.screen.opacity:P(i,"opacity")&&(s.opacity=i.opacity),r?s.blur=W(t.screen.blur):P(i,"blur")&&(s.blur=W(i.blur)),V(s,"opacity")&&s.opacity===void 0&&delete s.opacity,V(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},ul=(e,t)=>{if(t.background){let n=P(t.background,"resourceId"),r=P(t.background,"colorId"),o=P(t.background,"opacity"),i=P(t.background,"blur"),s=P(t.background,"transformId"),l=ai(t.background),a=ci(t.background),{animationsOnly:c,state:u}=kt(t.background,p=>P(p,"resourceId")||P(p,"colorId")||P(p,"opacity")||P(p,"blur")||P(p,"transformId")||ai(p)||ci(p));if(c){e.background=e.background?{...W(e.background),...u}:u;return}if(!n&&!r&&!o&&!i&&!s&&!l&&!a){delete e.background;return}let d=e.background,f=W(t.background);if(!n&&d?.resourceId){f.resourceId=d.resourceId,!V(f,"transformId")&&d.transformId&&(f.transformId=d.transformId);for(let p of gr)!P(f,p)&&P(d,p)&&(f[p]=d[p])}nl(f,d,{hasAuthoredTransformId:s}),!r&&d?.colorId&&(f.colorId=d.colorId),!o&&P(d,"opacity")&&(f.opacity=d.opacity),!i&&P(d,"blur")&&(f.blur=W(d.blur)),V(f,"resourceId")&&f.resourceId===void 0&&delete f.resourceId,V(f,"colorId")&&f.colorId===void 0&&delete f.colorId,V(f,"animations")&&f.animations===void 0&&delete f.animations,V(f,"transformId")&&f.transformId===void 0&&delete f.transformId,V(f,"opacity")&&f.opacity===void 0&&delete f.opacity,V(f,"blur")&&f.blur===void 0&&delete f.blur;for(let p of gr)V(f,p)&&f[p]===void 0&&delete f[p];if(!f.resourceId&&!f.colorId){delete e.background;return}d?.resourceId===f.resourceId&&d?.transformId===f.transformId&&!V(f,"animations")&&si(d)&&(f.animations=W(d.animations)),e.background=f}else e.background?.animations&&!si(e.background)&&(e.background.animations={})},dl=(e,t)=>{if(!t.dialogue){if(e.dialogue&&(li(e.dialogue),e.dialogue.mode==="adv")){e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,delete e.dialogue.textSpeed;let u=e.dialogue.persistCharacter===!0,d=ui({dialogueState:e.dialogue,dialogueAction:{},persistCharacter:u});u||delete e.dialogue.characterId,e.dialogue.character=di({previousCharacter:e.dialogue.character,characterFields:{},hasCharacterId:!1,persistCharacter:u,persistSprite:d,hasExplicitPersistSprite:!1,isAppendingAdvDialogueContent:!1}),e.dialogue.character||delete e.dialogue.character}return}e.dialogue||(e.dialogue={});let n=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:u,state:d}=kt(t.dialogue.ui,f=>!!f.resourceId);u?e.dialogue.ui={...e.dialogue.ui,...d}: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 r=t.dialogue.append===!0&&n!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&al({dialogueState:e.dialogue,content:t.dialogue.content,append:r}),V(t.dialogue,"textSpeed")?e.dialogue.textSpeed=t.dialogue.textSpeed:delete e.dialogue.textSpeed;let o=V(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=ui({dialogueState:e.dialogue,dialogueAction:t.dialogue,persistCharacter:o});V(t.dialogue,"persistSprite")&&(e.dialogue.persistSprite=i);let s=V(t.dialogue,"characterId"),l=sl(t.dialogue),a=bi(t.dialogue);s?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!r&&delete e.dialogue.characterId;let c=di({previousCharacter:e.dialogue.character,characterFields:l,hasCharacterId:s,persistCharacter:o,persistSprite:i,hasExplicitPersistSprite:V(t.dialogue,"persistSprite"),isAppendingAdvDialogueContent:r});if(c?e.dialogue.character=c:delete e.dialogue.character,a||li(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 u={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.textSpeed!==void 0&&(u.textSpeed=e.dialogue.textSpeed),e.dialogue.character&&(u.character=W(e.dialogue.character)),e.dialogue.lines.push(u)}},fl=(e,t)=>{if(t.sfx){let n=Array.isArray(t.sfx.items)&&t.sfx.items.length>0,r=Array.isArray(t.sfx.channels)&&t.sfx.channels.length>0;if(!n&&!r){delete e.sfx;return}e.sfx=W(t.sfx)}else e.sfx&&delete e.sfx},pl=(e,t)=>{if(t.bgm){let n=Array.isArray(t.bgm.sounds);if(!t.bgm.resourceId&&!n||n&&t.bgm.sounds.length===0){e.bgm=void 0;return}e.bgm=W(t.bgm),t.bgm.resourceId&&(e.bgm.loop=t.bgm.loop??!0)}},hl=(e,t)=>{if(t.visual){let n=e.visual?.items||[];t.visual.items?.forEach((i,s)=>{tl(i,gi(n,i,s))});let{hasValidItems:r,processedItems:o}=yi(t.visual.items,Zc,n,{hasPatchFn:mi,mergeItemFn:el});r?e.visual={items:o}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},ml=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:n,processedItems:r}=yi(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);n?e.character={items:r}:delete e.character},gl=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},yl=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=kt(t.layout,o=>!!o.resourceId);if(n){e.layout=r;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},bl=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=kt(t.choice,o=>!!o.resourceId);if(n){e.choice={...e.choice,...r};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},Il=(e,t)=>{if(t.form){let{animationsOnly:n,state:r}=kt(t.form,o=>!!o.resourceId);if(n){e.form={...e.form,...r};return}if(!t.form.resourceId){delete e.form;return}e.form=W(t.form)}else e.form&&delete e.form},Al=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},wl=(e,t)=>{if(t.voice){let n=Array.isArray(t.voice.sounds);if(!t.voice.resourceId&&!n||n&&t.voice.sounds.length===0){delete e.voice;return}e.voice=W(t.voice)}else e.voice&&delete e.voice},El=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},Qe=e=>on(cl,[El,ll,ul,fl,pl,hl,dl,ml,gl,yl,bl,Il,Al,wl])(e);var ft=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=le(e,t);return n&&typeof n=="object"?e:n};var xl=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},autoForwardSpeed:{source:"global.autoForwardSpeed"},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"}}),Ze=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,autoForwardSpeed:1,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),$t=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Ii=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",autoForwardSpeed:"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"}),yr=Object.freeze(["dialogueTextSpeed","autoForwardDelay","autoForwardSpeed","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),br=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),vl=(e,t)=>{if(t.startsWith("global.")){let n=t.slice(7);return e?.global?.[n]}if(t.startsWith("context.runtime.")){let n=t.slice(16),r=Array.isArray(e?.contexts)?e.contexts:[];return r[r.length-1]?.runtime?.[n]}},et=e=>Object.fromEntries(Object.entries(xl).map(([t,n])=>{let r=vl(e,n.source),o=r!==void 0?r:Ze[t]??$t[t];return[t,o]})),Me=(e,t)=>et(e)[t],Ai=(e={})=>Object.fromEntries(yr.map(t=>[t,e[t]??Ze[t]]));var pt=Object.freeze({VISUAL_BEHIND_BACKGROUND:10,BACKGROUND:20,VISUAL_BEHIND_CHARACTER:30,CHARACTER:40,VISUAL_BEHIND_DIALOGUE:50,DIALOGUE:60,VISUAL_BEHIND_CHOICE:70,CHOICE:80,VISUAL_FOREGROUND:90}),$e=Object.freeze({BEHIND_BACKGROUND:pt.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:pt.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:pt.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:pt.VISUAL_BEHIND_CHOICE,FOREGROUND:pt.VISUAL_FOREGROUND}),Ir=$e.BEHIND_DIALOGUE,Ar=Object.freeze(Object.values($e).sort((e,t)=>e-t));var Le={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:fr},Cl=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,Sl=(e,t)=>{let n=String(t||"").trim();if(!n)return;let r=n.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of r){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},pn=(e,t,n)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),l=Cl.exec(s);if(l){let[,a,c,u]=l,d=Sl(t,u);if(!Array.isArray(d))continue;let f=Array.isArray(i[s])?i[s]:[];d.forEach((p,h)=>{let m={...t,[a]:p};c&&(m[c]=h),f.forEach(y=>{let I=pn(y,m,n),w=le(I,m,n);Array.isArray(w)?o.push(...w):o.push(w)})});continue}}o.push(pn(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=pn(i,t,n)}),r},Vr=({animationType:e,animationId:t,animationPath:n})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${n}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},Ol=({id:e,targetId:t,animation:n,playback:r,animationPath:o="animation"})=>{let i=structuredClone(n);if(Vr({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,r!==void 0){let s=$l(r,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},Rl=(e,{animationId:t="animation",animationPath:n="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Vr({animationType:e.type,animationId:t,animationPath:n}),e.type},_l=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},kl=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},$l=(e,t="animation.playback")=>{if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`[${t}] playback must be an object.`);if(e.continuity!==void 0&&e.continuity!=="render"&&e.continuity!=="persistent")throw new Error(`[${t}] playback.continuity must be "render" or "persistent".`);if(e.speed!==void 0&&(typeof e.speed!="number"||!Number.isFinite(e.speed)||e.speed<=0))throw new Error(`[${t}] playback.speed must be a finite number greater than 0.`);let n={};return e.continuity!==void 0&&(n.continuity=e.continuity),e.speed!==void 0&&e.speed!==1&&(n.speed=e.speed),Object.keys(n).length>0?n:void 0},Ll=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},tt=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Li=e=>e?.playback?.continuity==="persistent",Rr=e=>Array.isArray(e)?e.map(Rr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,n)=>(t[n]=Rr(e[n]),t),{}),mn=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return t.playback&&(delete t.playback.continuity,t.playback.speed===1&&delete t.playback.speed,Object.keys(t.playback).length===0&&delete t.playback),JSON.stringify(Rr(t))},Ti=(e=[])=>e.filter(t=>Li(t)).map(t=>structuredClone(t)),Ni=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,n)=>{let r=typeof n?.duration=="number"&&Number.isFinite(n.duration)?n.duration:0;return t+r},0):0,wr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,n)=>Math.max(t,Ni(n)),0),Di=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(wr(e.tween),wr(e.prev?.tween),wr(e.next?.tween),Ni(e.mask?.progress))/Ll(e),wi=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let n=new Set(t.map(mn).filter(Boolean));return e.some(r=>{if(!Li(r))return!1;let o=mn(r);return o?n.has(o):!1})},Se=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:n,activePersistentAnimations:r,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||n?!1:i&&!t||wi({animationInstances:e,activePersistentAnimations:r})?!0:i?!1:wi({animationInstances:e,activePersistentAnimations:o}),Tl=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Nl=(e,t)=>{if(Tl(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},Dl=({resources:e,animationId:t,playback:n,instanceId:r,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?Ol({id:r,targetId:o,animation:s,playback:n,animationPath:i}):null},Pl=(e,{defaultTargetId:t,defaultId:n,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Vr({animationType:o.type,animationId:o.id??n,animationPath:r}),o.id??=n,o.targetId??=t,o},jr=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r,animationPathPrefix:o=r})=>{t.forEach((i,s)=>{e.push(Pl(i,{defaultTargetId:n,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},_r=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(n=>n===null||typeof n!="object"||Array.isArray(n)))throw new Error(`${t} must be an array of objects`);return e},Vl=({content:e,path:t,variables:n})=>_r(e,t).reduce((r,o)=>{let i=ft(o.text,{variables:n});return r+`${i??""}`.length},0),Ei=(e=[])=>{let t=new Map;for(let n of e)n?.id&&t.set(n.id,(t.get(n.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,n])=>n>1).map(([n])=>n))},un=(e,t=0,n=new Set)=>{if(!n.has(e?.id))return`character-container-${e.id}`;let r=e?.sprites?.map(({resourceId:o})=>o)||[];return r.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${r.join("-")}`},dn=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return n},jl=(e,t={})=>{if(!t?.transformId)return;let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for background`);return n},Fl=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Ml=(e={})=>Fl.some(t=>tt(e,t)),Pi=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.spritesheets?.[t])return"spritesheet-animation";if(e.layouts?.[t])return"container"}},hn=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Ul=(e={})=>e.textStyles||{},Bl=(e={})=>e.images||{},zl=.5,ql=(e={},t,n)=>{if(t){if(!e.animations?.[t])throw new Error(`Animation '${t}' not found in spritesheet resource '${n}'`);return t}return Object.keys(e.animations??{})[0]},Vi=({id:e,resourceId:t,spritesheet:n,animationName:r,animationSpeed:o,loop:i,transform:s={}}={})=>{let l=ql(n,r,t),a=l?n.animations?.[l]:void 0;if(!a){console.warn(`Spritesheet animation not found: ${t}`);return}return{id:e,type:"spritesheet-animation",...s,width:n.width,height:n.height,src:n.fileId,atlas:n.jsonData,playback:{frames:a.frames,animationSpeed:o??a.animationSpeed??zl,loop:i??a.loop??!0}}},ji=({id:e,item:t,resources:n={}}={})=>{let r=n.images?.[t.resourceId];if(r)return{type:"sprite",id:e,src:r.fileId,width:r.width,height:r.height,x:0,y:0};let o=n.spritesheets?.[t.resourceId];if(o)return Vi({id:e,resourceId:t.resourceId,spritesheet:o,animationName:t.animationName,animationSpeed:t.animationSpeed,loop:t.loop,transform:{x:0,y:0}});console.warn(`Character sprite resource not found: ${t.resourceId}`)},Hl=(e={})=>e.colors||{},Wl=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Nt=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,mt=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},Er=(e,t,n)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);return e},xr=(e,t,n,r,{minimum:o}={})=>{if(e===void 0)return r;if(typeof e!="number"||!Number.isFinite(e)||o!==void 0&&e<o){let i=o===void 0?"a finite number":`a finite number >= ${o}`;throw new Error(`shadow.${t} for text style "${n}" must be ${i}`)}return e},bn=(e,t)=>{if(typeof e!="string"||!Wl.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(n=>n.repeat(2)).join("")}`:e},xi=(e,t,n)=>{let r=bn(e,n);if(t===1)return r;let o=Number.parseInt(r.slice(1,3),16),i=Number.parseInt(r.slice(3,5),16),s=Number.parseInt(r.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},Yl=(e={},t)=>{let n=Ul(e)?.[t];if(!n)throw new Error(`Text style "${t}" not found`);let o=(Array.isArray(n.fontId)?n.fontId:[n.fontId]).map(a=>{let c=e.fonts?.[a];if(!c)throw new Error(`Font "${a}" not found for text style "${t}"`);return c.fileId}),i=e.colors?.[n.colorId];if(!i)throw new Error(`Color "${n.colorId}" not found for text style "${t}"`);let s=Er(n.colorAlpha,"colorAlpha",t),l={fontFamily:Array.isArray(n.fontId)?o.join(", "):o[0],fontSize:n.fontSize??16,fontWeight:n.fontWeight??"400",fontStyle:n.fontStyle??"normal",lineHeight:n.lineHeight??1.2,fill:xi(i.hex,s,`Color "${n.colorId}" for text style "${t}"`)};if(n.align!==void 0&&(l.align=n.align),n.wordWrap!==void 0&&(l.wordWrap=n.wordWrap),n.breakWords!==void 0&&(l.breakWords=n.breakWords),n.wordWrapWidth!==void 0&&(l.wordWrapWidth=n.wordWrapWidth),n.strokeColorId){let a=e.colors?.[n.strokeColorId];if(!a)throw new Error(`Stroke color "${n.strokeColorId}" not found for text style "${t}"`);let c=Er(n.strokeAlpha,"strokeAlpha",t);l.strokeColor=xi(a.hex,c,`Stroke color "${n.strokeColorId}" for text style "${t}"`)}else if(n.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);if(n.strokeWidth!==void 0&&(l.strokeWidth=n.strokeWidth),n.shadow!==void 0){let a=e.colors?.[n.shadow.colorId];if(!a)throw new Error(`Shadow color "${n.shadow.colorId}" not found for text style "${t}"`);l.shadow={color:bn(a.hex,`Shadow color "${n.shadow.colorId}" for text style "${t}"`),alpha:Er(n.shadow.alpha,"shadow.alpha",t),blur:xr(n.shadow.blur,"blur",t,0,{minimum:0}),offsetX:xr(n.shadow.offsetX,"offsetX",t,2),offsetY:xr(n.shadow.offsetY,"offsetY",t,2)}}return l},kr=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>kr(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${n}". Use textStyleId instead`);let r={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(r[o]=kr(i,t,Nt(n,o)));return e.textStyleId!==void 0&&(mt(e.textStyleId,n,"textStyleId"),r.textStyle=Yl(t,e.textStyleId)),r},Fr=(e={},t)=>{let n=Hl(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return bn(n.hex,`Color "${t}"`)},Fi=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",vr=(e,t,n)=>{let r=e?.[t];if(!(!r||typeof r!="object"||Array.isArray(r))&&Object.prototype.hasOwnProperty.call(r,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${n}". Use ${Fi(`${t}.fill`)} instead`)},Gl=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Dt(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;let r={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(r[o]=Dt(i,t,Nt(n,o)));return e.colorId!==void 0&&(mt(e.colorId,n,"colorId"),r.fill=Fr(t,e.colorId)),r},Dt=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Dt(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${n}". Use ${Fi("fill")} instead`);vr(e,"hover",n),vr(e,"click",n),vr(e,"rightClick",n)}let r={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){r[o]=Gl(i,t,Nt(n,o));continue}r[o]=Dt(i,t,Nt(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(mt(e.colorId,n,"colorId"),r.fill=Fr(t,e.colorId)),r},Cr=(e={},t)=>{let n=Bl(e)?.[t];return n||null},Mi=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",vi=(e,t,n,r)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,r))throw new Error(`Inline ${t}.${r} is not allowed in sprite layout elements at "${n}". Use ${Mi(`${t}.${r}`)} instead`)},Ci=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},$r=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>$r(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${n}". Use ${Mi(o)} instead`);vi(e,"hover",n,"src"),vi(e,"click",n,"src")}let r={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(r[o]=$r(i,t,Nt(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){mt(e.imageId,n,"imageId");let o=Cr(t,e.imageId),i=o?.fileId??e.imageId;r.src=i,r.width===void 0&&o?.width!==void 0&&(r.width=o.width),r.height===void 0&&o?.height!==void 0&&(r.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(mt(e.hoverImageId,n,"hoverImageId"),Ci(r,"hover",Cr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(mt(e.clickImageId,n,"clickImageId"),Ci(r,"click",Cr(t,e.clickImageId)?.fileId??e.clickImageId)),r},Mr=(e,t={},n="root")=>$r(Dt(kr(e,t,n),t,n),t,n),Te=Mr,rt=(e=[])=>e.find(t=>t.id==="story"),Kl="#000000",Lr="bg-cg-background-color",Jl=({resources:e={},background:t={},screen:n})=>t?.colorId===void 0?bn(n?.backgroundColor??Kl,"screen.backgroundColor"):Fr(e,t.colorId),Ui=(e={})=>{if(tt(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Xl=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Si=(e={},{includeDefaultAlpha:t=!1}={})=>{let n=Ui(e),r=Xl(e),o={};return(t||n!==void 0)&&(o.alpha=n??1),r&&(o.blur=r),o},Ql=(e={})=>{if(tt(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Zl=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Bi=(e={})=>{let t=Ql(e),n=Zl(e),r={};return t!==void 0&&(r.alpha=t),n&&(r.blur=n),r},Lt=(e={})=>Bi(e),Ue=(e={},t={})=>{let n={x:t.x??e.x,y:t.y??e.y,anchorX:t.anchorX??e.anchorX,anchorY:t.anchorY??e.anchorY,rotation:t.rotation??e.rotation,scaleX:t.scaleX??e.scaleX,scaleY:t.scaleY??e.scaleY},r=t.originX??e.originX,o=t.originY??e.originY;return r!==void 0&&(n.originX=r),o!==void 0&&(n.originY=o),n},eu=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],Ur=(e={})=>e.text&&tt(e.text,"content")&&tt(e.text,"textStyleId"),Oi=(e={})=>{if(e.resourceId)return e.resourceId;if(Ur(e))return"text"},tu=e=>{if(e.text){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!Ur(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let t of eu)if(tt(e.text,t))throw new Error(`Visual item "${e.id}" text.${t} is reserved for the visual item`)}},nu=({resources:e,background:t,screen:n={width:1920,height:1080},includeOpacity:r=!1})=>{let o={id:Lr,type:"rect",x:0,y:0,width:n?.width??1920,height:n?.height??1080,fill:Jl({resources:e,background:t,screen:n})};if(r){let i=Ui(t);i!==void 0&&(o.alpha=i)}return o},ru=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.spritesheets?.[t]||e.layouts?.[t]):!1,Ri=({resources:e={},resourceId:t,colorId:n})=>{let r=Pi(e,t);return t&&(r||n===void 0)?{resourceId:t,targetId:hn({resourceId:t,kind:r})}:n!==void 0?{resourceId:Lr,targetId:Lr}:{resourceId:void 0,targetId:void 0}},zi=100,nt=zi,ou="channel:bgm",iu="channel:voice",su="default",au=e=>String(e).replaceAll("%","%25").replaceAll(":","%3A"),Tt=(...e)=>e.map(au).join(":"),gn=(e,t,n)=>{let r=new Set;e.forEach(({id:o})=>{if(r.has(o)){let i=n?` in ${n}`:"";throw new Error(`Duplicate ${t} id "${o}"${i}.`)}r.add(o)})},cu=(e,t)=>e*t/zi,qi=(e={},t)=>e?.[t]??Ze[t],Br=(e={},t,n=nt)=>cu(n,qi(e,t)),zr=({id:e,volume:t,muted:n,pan:r,loop:o,children:i,runtime:s})=>{let l={id:e,type:"audio-channel",volume:t,muted:!!s?.muteAll||(n??!1),pan:r??0,children:i};return o!==void 0&&(l.loop=o),l},fn=(e,t,n,r)=>e[n]!==void 0?e[n]:t[n]!==void 0?t[n]:r,lu=["muted","pan","playbackRate","startAt","endAt"],qr=({id:e,sound:t,resource:n,defaultLoop:r=!1})=>{let o={id:e,type:"sound",src:n.fileId,loop:fn(t,n,"loop",r),volume:fn(t,n,"volume",nt),startDelayMs:fn(t,n,"startDelayMs",0)};lu.forEach(s=>{let l=fn(t,n,s,void 0);l!==void 0&&(o[s]=l)});let i=o.startAt??0;if(o.endAt!==void 0&&o.endAt!==null&&o.endAt<i)throw new Error(`Sound "${e}" endAt (${o.endAt}) must be greater than or equal to startAt (${i}).`);return o},Oe=({variables:e,runtime:t,saveSlots:n=[],dialogueState:r,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,confirmDialog:d,form:f,historyDialogue:p=[],characters:h={},dialogueUIHidden:m,skipOnlyViewedLines:y,skipTransitionsAndAnimations:I}={})=>{let w={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,autoForwardSpeed:t?.autoForwardSpeed??1,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??m??!1,isLineCompleted:t?.isLineCompleted??i??!1},E=hu({dialogueState:r,includeInactiveAdvDialogue:o,characters:h,variables:e,runtime:w}),R={variables:e,runtime:w,saveSlots:n,isChoiceVisible:a,isFormVisible:c,canRollback:u,confirmDialog:d,form:f,historyDialogue:p,characters:h};return E&&(R.dialogue=E,R.dialogueLines=E.lines),R},_i=100,yn=(e,t)=>{if(Array.isArray(e))return e.map(r=>yn(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=yn(n[r],t)}),n.type==="text-revealing"?t(n):n},uu=e=>yn(e,t=>({...t,revealEffect:"none"})),du=e=>yn(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,_i):_i;return{...t,speed:r,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:r}:{}}}),Be=(e,{isLineCompleted:t=!1,skipMode:n=!1,skipTransitionsAndAnimations:r=!1}={})=>t||r?uu(e):n?du(e):e,Hi=({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:{}}}}),Tr=e=>{if(Array.isArray(e))return e.map(Tr);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Tr(s);let n=t.click?.payload;if(!n||typeof n!="object"||Array.isArray(n))return t;let r=n.actions,o=r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"nextLine")?{...r.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...n,bypassChoice:!0,...o?{actions:{...r,nextLine:o}}:{}}}}},fu=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),ki="submit",Sr=(e,t,n={})=>{let r=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},o=r.actions&&typeof r.actions=="object"?r.actions:{},i=n.replaceActions===!0?t:{...o,...t};return{...e||{},payload:{...r,actions:i}}},Nr=(e,t,n={})=>{if(Array.isArray(e))return e.map(c=>Nr(c,t,n));if(!e||typeof e!="object")return e;let r=typeof e.type=="string",o=r&&e.formRole===ki,i=r&&n.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},l={};for(let[c,u]of Object.entries(e))l[c]=Nr(u,t,c==="children"?s:{});let a=l;if(a.type==="input"&&typeof a.field=="string"){let c=t?.fields?.[a.field];if(c){let u={updateFormField:{formKey:t.key,field:c.id,value:"_event.value"}};a={...a,value:c.value,placeholder:a.placeholder===void 0?c.placeholder:a.placeholder,multiline:a.multiline===void 0?c.multiline:a.multiline,...a.maxLength===void 0&&c.maxLength!==void 0?{maxLength:c.maxLength}:{},change:Sr(a.change,u),submit:Sr(a.submit,t.submitActions)}}}return a.formRole===ki||i?{...a,click:Sr(a.click,t.submitActions,{replaceActions:!0})}:a},Dr=(e,t)=>{if(Array.isArray(e))return e.map(r=>Dr(r,t));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e))n[r]=Dr(o,t);for(let r of fu){let o=n[r]?.payload;!o||typeof o!="object"||Array.isArray(o)||(n[r]={...n[r],payload:{...o,_interactionSource:"form"}})}return n},Pr=({characterId:e,character:t,characterName:n,characters:r={},variables:o={}}={})=>{let i=e?r?.[e]:void 0,s=sn({characterId:e,character:t,characterName:n,characters:r,variables:o});return{...i||{},...t||{},name:s}},Wi=(e=[],t={},n={})=>e.map(r=>{let o=Pr({characterId:r.characterId,character:r.character,characterName:r.characterName,characters:t,variables:n}),i=typeof r.text=="string"?r.text:Array.isArray(r.content)?r.content.map(s=>s?.text??"").join(""):"";return{...r,text:i,character:o,characterName:o.name}}),pu=e=>!(!e||e.mode==="adv"&&e.content===void 0),hu=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:n={},variables:r,runtime:o}={})=>{if(!t&&!pu(e))return;let i=e.content===void 0?[{text:""}]:_r(e.content,"dialogue.content"),s=e.content===void 0?0:Vl({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:r}),l=o?.dialogueTextSpeed??Ze.dialogueTextSpeed,a=e.textSpeed??l,c=(e.lines||[]).map((d,f)=>{let p=_r(d.content,`dialogue.lines[${f}].content`),h=Pr({characterId:d.characterId,character:d.character,characterName:d.characterName,characters:n,variables:r});return{...d,textSpeed:d.textSpeed??l,content:p.map(m=>({...m,text:ft(m.text,{variables:r})})),character:h,characterName:h.name}}),u=Pr({characterId:e.characterId,character:e.character,characters:n,variables:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,persistSprite:e.persistSprite,character:u,textSpeed:a,content:i.map(d=>({...d,text:ft(d.text,{variables:r})})),initialRevealedCharacters:s,lines:c}},Yi=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=le(e,n,{functions:Le});return Te(Be(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},Or=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),$i=({renderStateKeyboard:e,keyboard:t,phase:n})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([r,o])=>{let i=e[r]??{},s=n==="keydown"?o?.keydown:o?.keyup;if(n==="keydown"&&s&&typeof s=="object"){e[r]={...i,keydown:{payload:Or(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[r].keyup={payload:Or(o.keyup)});return}e[r]={...i,[n]:{payload:Or(o)}}})},mu=(e={},t={})=>{let n={};return $i({renderStateKeyboard:n,keyboard:e,phase:"keydown"}),$i({renderStateKeyboard:n,keyboard:t,phase:"keyup"}),Object.keys(n).length>0?n:void 0},Ne=({animationsDef:e,resources:t,previousResourceId:n,currentResourceId:r,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l})=>{if(!e)return[];let a=[],c=({instanceId:I,targetId:w})=>{let E=Dl({resources:t,animationId:p,playback:h,instanceId:I,targetId:w,animationPath:s});E&&a.push(E)},u=n!=null&&n!==!1,d=r!=null&&r!==!1,f=o&&i&&o===i;Nl(e,s);let p=_l(e),h=kl(e),m=t?.animations?.[p],y=Rl(m,{animationId:p,animationPath:s});if(y==="update")return d&&i?c({instanceId:`${l}-animation-update`,targetId:i}):u&&o&&c({instanceId:`${l}-animation-update`,targetId:o}),a;if(y==="transition"){let I=`${l}-animation-transition`,w=h?.continuity==="persistent"?I:`${l}-animation-in`;if(u&&d&&f)return c({instanceId:I,targetId:i}),a;u&&c({instanceId:`${l}-animation-out`,targetId:o}),d&&c({instanceId:w,targetId:i})}return a},gu=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),yu=(e,{presentationState:t,previousPresentationState:n,currentLineActions:r,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:a,runtime:c,activePersistentAnimations:u,restoredPersistentAnimations:d,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:m,canRollback:y,form:I,saveSlots:w=[]})=>{let{elements:E,animations:R}=e;if(t.background){let j=r===void 0?!0:tt(r?.background??{},"animations"),F=E.find(de=>de.id==="story");if(!F)return e;let x=jl(o,t.background),z=x||Ml(t.background),q=n?.background?.resourceId,X=n?.background?.colorId,U=t.background.resourceId??(t.background.animations?q:void 0),Y=t.background.colorId??(t.background.animations?X:void 0),K=ru(o,U),Q={...t.background,colorId:Y};if((Y!==void 0||K)&&F.children.push(nu({resources:o,background:Q,screen:i,includeOpacity:!K})),U){let{images:de={},videos:fe={},spritesheets:Z={}}=o,oe=Pi(o,U),pe;if(oe==="sprite"?pe=de[U]:oe==="video"?pe=fe[U]:oe==="spritesheet-animation"&&(pe=Z[U]),pe){let S=oe==="video",_=oe==="spritesheet-animation",M={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...x},ie={...Si(t.background,{includeDefaultAlpha:!0}),...Ue(M,t.background)},se;_?se=Vi({id:hn({resourceId:U,kind:oe}),resourceId:U,spritesheet:pe,animationName:t.background.animationName,animationSpeed:t.background.animationSpeed,loop:t.background.loop,transform:ie}):se={id:hn({resourceId:U,kind:oe}),type:S?"video":"sprite",src:pe.fileId,width:pe.width,height:pe.height,...ie},S&&(se.loop=t.background.loop??!1,se.volume=pe.volume??50),se&&F.children.push(se)}}if(U){let{layouts:de={}}=o,fe=de[U];if(fe){let Z={id:hn({resourceId:U,kind:"container"}),type:"container",children:fe.elements,...Si(t.background)};z&&Object.assign(Z,Ue({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...x},t.background));let oe=le(Z,Oe({variables:a,runtime:c,saveSlots:w,dialogueState:t.dialogue,isLineCompleted:s,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:m,canRollback:y,form:I,characters:o.characters||{},skipTransitionsAndAnimations:l}),{functions:Le});F.children.push(Te(Be(oe,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:l}),o))}}let Re=Ri({resources:o,resourceId:q,colorId:X}),ne=Ri({resources:o,resourceId:U,colorId:Y}),re=Ne({animationsDef:t.background.animations,resources:o,previousResourceId:Re.resourceId,currentResourceId:ne.resourceId,previousTargetId:Re.targetId,currentTargetId:ne.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});Se({animationInstances:re,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:u,restoredPersistentAnimations:d,isAuthoredOnCurrentLine:j})&&R.push(...re)}return e},bu=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:a}=e;if(t.character&&r){let c=l.find(h=>h.id==="story");if(!c)return e;let u=t.character.items||[],d=n?.character?.items||[],f=Ei(u),p=Ei(d);for(let h=0;h<u.length;h++){let m=u[h],{transformId:y,sprites:I}=m,w=d.find(U=>U.id===m.id),E=d.findIndex(U=>U.id===m.id),R=w?.sprites&&w.sprites.length>0,j=I&&I.length>0,F=E>=0?un(w,E,p):void 0,x=Ne({animationsDef:m.animations,resources:r,previousResourceId:F,currentResourceId:j?un(m,h,f):void 0,previousTargetId:F,currentTargetId:j?un(m,h,f):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(m.animations&&!I&&!y&&R&&Se({animationInstances:x,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...x);continue}if(m.animations&&!I&&!y)continue;if(!I||I.length===0||!y){console.warn("Character item missing sprites or transformId:",m);continue}let z=un(m,h,f),q=r.transforms[y];if(!q){console.warn("Transform not found:",y);continue}let X={type:"container",id:z,...Ue(q,m),...Lt(m),children:[]};for(let U of I){let Y=ji({id:`${z}-${U.id}`,item:U,resources:r});Y&&X.children.push(Y)}c.children.push(X),Se({animationInstances:x,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...x)}}return e},Gi=(e,t)=>{if(!Ar.includes(e))throw new Error(`${t} must be one of: ${Ar.join(", ")}.`)},Iu=(e,t)=>{let n=!!e.resourceId||Ur(e),r=e.layer??(n?void 0:t?.layer)??Ir;return Gi(r,`Visual item "${e.id}" layer`),r},Au=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:l,activePersistentAnimations:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,saveSlots:m=[],visualLayer:y})=>{let{elements:I,animations:w}=e;if(t.visual&&r){let E=I.find(x=>x.id==="story");if(!E)return e;let R=t.visual.items,j=n?.visual?.items||[],F=Oe({variables:s,runtime:l,saveSlots:m,dialogueState:t.dialogue,isLineCompleted:o,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,characters:r.characters||{},skipTransitionsAndAnimations:i});y!==void 0&&Gi(y,"visualLayer");for(let x of R){let z=j.find(K=>K.id===x.id),q=Iu(x,z);if(y!==void 0&&q!==y)continue;if(tu(x),x.text){let K=dn(r,x),Q={...structuredClone(x.text),id:`visual-${x.id}`,type:"text",...Ue(K,x)};Object.assign(Q,Lt(x)),E.children.push(Te(le(Q,F,{functions:Le}),r))}if(x.resourceId){let{images:K={},videos:Q={},spritesheets:Re={}}=r,ne=Re[x.resourceId];if(ne){let re=dn(r,x),de=x.animationName;if(de){let fe=ne.animations?.[de];if(!fe)throw new Error(`Animation '${de}' not found in spritesheet resource '${x.resourceId}'`);let Z=Lt(x),oe={id:`visual-${x.id}`,type:"spritesheet-animation",...Ue(re,x),width:x.width??ne.width,height:x.height??ne.height,alpha:Z.alpha??x.alpha??1,src:ne.fileId,atlas:ne.jsonData,playback:{frames:fe.frames,animationSpeed:x.animationSpeed??fe.animationSpeed??.5,loop:x.loop??fe.loop??!0}};Z.blur&&(oe.blur=Z.blur),E.children.push(structuredClone(oe))}}else{let re=K[x.resourceId]||Q[x.resourceId];if(re){let de=Q[x.resourceId]!==void 0,fe=dn(r,x),Z={id:`visual-${x.id}`,type:de?"video":"sprite",src:re.fileId,width:re.width,height:re.height,...Ue(fe,x)};Object.assign(Z,Lt(x)),de&&(Z.loop=re.loop??!1,Z.volume=re.volume??50),E.children.push(Z)}}}if(x.resourceId){let{layouts:K={}}=r,Q=K[x.resourceId];if(Q){let Re=dn(r,x),ne={id:`visual-${x.id}`,type:"container",children:structuredClone(Q.elements),...Ue(Re,x)};Object.assign(ne,Lt(x));let re=le(ne,F,{functions:Le});E.children.push(Te(Be(re,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),r))}}let X=Oi(z),U=Oi(x),Y=Ne({animationsDef:x.animations,resources:r,previousResourceId:X,currentResourceId:U,previousTargetId:X?`visual-${x.id}`:void 0,currentTargetId:U?`visual-${x.id}`:void 0,animationPath:`visual.items[${x.id}].animations`,idPrefix:x.id});Se({animationInstances:Y,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:a})&&w.push(...Y)}}return e},ht="dialogue-character-sprite",wu=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=rt(e.elements);if(!a)return e;let c=t.dialogue?.character?.sprite,u=n?.dialogue?.character?.sprite,d=St(c),f=St(u),p=Ne({animationsDef:c?.animations,resources:r,previousResourceId:f?ht:void 0,currentResourceId:d?ht:void 0,previousTargetId:f?ht:void 0,currentTargetId:d?ht:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!d)return c?.animations&&f&&Se({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e;let h=r.transforms?.[c.transformId];if(!h)return console.warn("Transform not found:",c.transformId),e;let m={type:"container",id:ht,...Ue(h),children:[]};for(let y of c.items){let I=ji({id:`${ht}-${y.id}`,item:y,resources:r});I&&m.children.push(I)}return a.children.push(m),Se({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e},Eu=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,skipOnlyViewedLines:d,isLineCompleted:f,skipTransitionsAndAnimations:p,variables:h,runtime:m,activePersistentAnimations:y,saveSlots:I=[]})=>{let{elements:w,animations:E}=e;if(!t.dialogue||o)return e;let R=w.find(F=>F.id==="story");if(!R)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:F={}}=r,x=F[t.dialogue.ui.resourceId];if(x){let z={elements:x.elements},q=Oe({variables:h,runtime:m,saveSlots:I,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:f,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,characters:r.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:d,skipTransitionsAndAnimations:p}),X={functions:Le},U=pn(z,q,X),Y=le(U,q,X),K=Te(Be(Y?.elements,{isLineCompleted:f,skipMode:s,skipTransitionsAndAnimations:p}),r);if(Array.isArray(K))for(let Q of K)R.children.push(Q);else K&&R.children.push(K)}}wu(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let j=Ne({animationsDef:t.dialogue.ui?.animations,resources:r,previousResourceId:n?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:n?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return Se({animationInstances:j,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&E.push(...j),e},xu=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,activePersistentAnimations:m,saveSlots:y=[]})=>{let{elements:I,animations:w}=e;if(t.choice&&r){let E=rt(I);if(!E)return e;let R=r?.layouts[t.choice.resourceId];if(R&&R.elements){let F={elements:R.elements},x=le(F,{...Oe({variables:l,runtime:a,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:c,skipMode:u,isChoiceVisible:d??!!t.choice,isFormVisible:f,canRollback:p,form:h,characters:r.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:Le}),z=Tr(Te(Be(x?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r));if(Array.isArray(z))for(let q of z)E.children.push(q);else z&&E.children.push(z)}let j=Ne({animationsDef:t.choice.animations,resources:r,previousResourceId:n?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:n?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});Se({animationInstances:j,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:m})&&w.push(...j)}return e},vu=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,activePersistentAnimations:h,saveSlots:m=[],form:y})=>{let{elements:I,animations:w}=e;if(!y?.resourceId||!r)return e;let E=rt(I);if(!E)return e;let R=r?.layouts?.[y.resourceId];if(!R)return console.warn(`Form layout not found: ${y.resourceId}`),e;let j={id:"form-container",type:"container",x:0,y:0,children:R.elements||[]},F={...Oe({variables:l,runtime:a,saveSlots:m,dialogueState:t.dialogue,isLineCompleted:i,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,characters:r.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},x=le(j,F,{functions:Le}),z=Dr(Te(Be(Nr(x,y),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r),y);z&&E.children.push(z);let q=Ne({animationsDef:y.animations,resources:r,previousResourceId:n?.form?.resourceId,currentResourceId:y.resourceId,previousTargetId:n?.form?.resourceId?"form-container":void 0,currentTargetId:y.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return Se({animationInstances:q,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&w.push(...q),e},Cu=(e,{presentationState:t,resources:n={},variables:r,runtime:o,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,saveSlots:f=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=n.controls?.[t.control.resourceId];if(!h)return e;let m=mu(h.keyboard,h.keyup);if(m&&Object.keys(m).length>0&&(e.global.keyboard=m),!Array.isArray(h.elements)||h.elements.length===0)return e;let y=rt(e.elements);if(!y)return e;let I={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(Yi({container:I,resources:n,templateData:Oe({variables:r,runtime:o,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,characters:n.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:l,skipTransitionsAndAnimations:p})),e},Su=(e,{presentationState:t,resources:n,runtime:r,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&n){if(!rt(i))return e;let a=t.bgm,c=!Array.isArray(a.sounds),u=c?a.resourceId?[{id:"default",resourceId:a.resourceId,loop:a.loop??!0,volume:a.volume,startDelayMs:a.startDelayMs??0}]:[]:a.sounds,d=!c&&a.loop===!0,f=[];if(c||gn(u,"BGM sound"),d){let h=u.find(m=>m.loop===!0);if(h)throw new Error(`BGM sound "${h.id}" cannot loop inside a looping BGM channel.`)}if(u.forEach(h=>{let m=n.sounds?.[h.resourceId];if(!m)return;let y=d?{...h,loop:h.loop??!1}:h;f.push(qr({id:Tt("bgm",c?"default":h.id),sound:y,resource:m,defaultLoop:!d}))}),f.length===0)return e;let p=Oe({variables:o,runtime:r}).runtime;s.push(zr({id:ou,volume:Br(p,"musicVolume",c?nt:a.volume??nt),muted:a.muted,pan:a.pan,loop:c?void 0:a.loop,children:f,runtime:p}))}return e},Ou=(e,{presentationState:t,resources:n,runtime:r})=>{let{audio:o}=e;if(t.sfx&&n){let i=t.sfx,s=!Array.isArray(i.channels),l=s?[{id:su,sounds:i.items??[]}]:i.channels;s||gn(l,"SFX channel"),l.forEach(a=>{let c=!s&&a.loop===!0,u=[];if(s||gn(a.sounds,"SFX sound",`SFX channel "${a.id}"`),c){let d=a.sounds.find(f=>f.loop===!0);if(d)throw new Error(`SFX sound "${d.id}" cannot loop inside looping SFX channel "${a.id}".`)}a.sounds.forEach((d,f)=>{let p=n.sounds?.[d.resourceId];if(!p)return;let h=c?{...d,loop:d.loop??!1}:d;u.push(qr({id:s?Tt("sfx","default",f,d.id):Tt("sfx",a.id,d.id),sound:h,resource:p,defaultLoop:c?!1:void 0}))}),u.length!==0&&o.push(zr({id:Tt("channel","sfx",a.id),volume:Br(r,"soundVolume",a.volume??nt),muted:a.muted,pan:a.pan,loop:s?void 0:a.loop,children:u,runtime:r}))})}return e},Ru=(e,t,n)=>{if(!(!t||!n))return e?.voices?.[t]?.[n]},_u=(e,{presentationState:t,resources:n,currentSceneId:r,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let l=t.voice,a=!Array.isArray(l.sounds),c=a?l.resourceId?[{id:"default",resourceId:l.resourceId,loop:l.loop??!1,volume:nt,startDelayMs:l.startDelayMs??0}]:[]:l.sounds,u=!a&&l.loop===!0,d=[];if(a||gn(c,"Voice sound"),u){let p=c.find(h=>h.loop===!0);if(p)throw new Error(`Voice sound "${p.id}" cannot loop inside a looping Voice channel.`)}if(c.forEach(p=>{let h=Ru(n,r,p.resourceId);if(!h)return;let m=u?{...p,loop:p.loop??!1}:p;d.push(qr({id:Tt("voice",r,a?"default":p.id),sound:m,resource:h,defaultLoop:u?!1:void 0}))}),d.length===0)return e;let f=Oe({variables:i,runtime:o}).runtime;return s.push(zr({id:iu,volume:a?l.volume??qi(f,"soundVolume"):Br(f,"soundVolume",l.volume??nt),muted:l.muted,pan:l.pan,loop:a?void 0:l.loop,children:d,runtime:f})),e},ku=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,saveSlots:f=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:m})=>{let{elements:y,animations:I}=e;if(t.layout){let j=rt(y);if(!j)return e;let F=r.layouts[t.layout.resourceId];if(!F)return e;Array.isArray(F.transitions)&&!p&&!h&&jr({animations:I,transitions:F.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let x={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:F.elements||[]};j.children.push(Yi({container:x,resources:r,templateData:Oe({variables:o,runtime:i,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,characters:r.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:l,skipTransitionsAndAnimations:h}))}let w=n?.layout?.resourceId,E=t.layout?.resourceId,R=Ne({animationsDef:t.layout?.animations,resources:r,previousResourceId:w,currentResourceId:E,previousTargetId:w?`layout-${w}`:void 0,currentTargetId:E?`layout-${E}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return Se({animationInstances:R,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:m})&&I.push(...R),e},$u=(e,{currentLineActions:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=t?.screen?.animations;if(!a)return e;let c=n!=null,u=Ne({animationsDef:a,resources:r,previousResourceId:c?"story":void 0,currentResourceId:"story",previousTargetId:c?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return Se({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...u),e},Lu=(e,{presentationState:t})=>{let n=rt(e.elements);return!n||!t?.screen||Object.assign(n,Bi(t.screen)),e},Tu=(e,{presentationState:t,resources:n={},variables:r,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,overlayStack:d=[],dialogueHistory:f=[],saveSlots:p=[],screen:h,isLineCompleted:m,skipTransitionsAndAnimations:y})=>{let{elements:I,animations:w}=e;return d&&d.length>0&&d.forEach((E,R)=>{let j=n.layouts[E.resourceId];if(!j){console.warn(`Overlay layout not found: ${E.resourceId}`);return}Array.isArray(j.transitions)&&(y||jr({animations:w,transitions:j.transitions,defaultTargetId:`overlayStack-${R}`,idPrefix:`overlayStack-${R}`,animationPathPrefix:`overlayStack[${R}]`}));let F={id:`overlayStack-${R}`,type:"container",x:0,y:0,children:[Hi({id:`overlayStack-${R}-blocker`,screen:h}),...j.elements||[]]},x=Wi(f,n.characters,r),z=Oe({variables:r,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:m,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,historyDialogue:x,characters:n.characters||{},skipTransitionsAndAnimations:y}),q=le(F,z,{functions:Le}),[X,...U]=q.children||[],Y=Te(Be({...q,children:U},{isLineCompleted:m,skipMode:s,skipTransitionsAndAnimations:y}),n);I.push({...Y,children:X?[X,...Y.children||[]]:Y.children})}),e},Nu=(e,{presentationState:t,resources:n={},variables:r,runtime:o,saveSlots:i=[],autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,confirmDialog:f,dialogueHistory:p=[],screen:h,isLineCompleted:m,skipTransitionsAndAnimations:y})=>{let{elements:I,animations:w}=e;if(!f?.resourceId)return e;let E=n.layouts?.[f.resourceId];if(!E)return console.warn(`ConfirmDialog layout not found: ${f.resourceId}`),e;Array.isArray(E.transitions)&&!y&&jr({animations:w,transitions:E.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let R={id:"confirmDialog",type:"container",x:0,y:0,children:[Hi({id:"confirmDialog-blocker",screen:h}),...E.elements||[]]},j=Wi(p,n.characters,r),F=le(R,Oe({variables:r,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:m,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,confirmDialog:f,historyDialogue:j,characters:n.characters||{},skipTransitionsAndAnimations:y}),{functions:Le}),[x,...z]=F.children||[],q=Te(Be({...F,children:z},{isLineCompleted:m,skipMode:l,skipTransitionsAndAnimations:y}),n);return I.push({...q,children:x?[x,...q.children||[]]:q.children}),e},Pt=e=>(t,n)=>Au(t,{...n,visualLayer:e}),Du=Pt($e.BEHIND_BACKGROUND),Pu=Pt($e.BEHIND_CHARACTER),Vu=Pt($e.BEHIND_DIALOGUE),ju=Pt($e.BEHIND_CHOICE),Fu=Pt($e.FOREGROUND),Ki=e=>on(gu,[Cu,Du,yu,Pu,bu,Vu,Eu,ju,xu,vu,ku,Fu,Lu,$u,Su,Ou,_u,Tu,Nu])(e);function Ji(e,t=""){let n=[],r=e.length,o=0,i=0,s=-1,l=()=>{let a=0,c=0,u;do u=parseInt(e[o++],36),a+=(u&15)<<c,c+=4;while(u&16);return a};for(;o<r;){let a=s+1+l();s=a+l(),n.push([a,s,t?parseInt(t[i++],36):0])}return n}function Xi(e,t,n){let r=0,o=t.length-1;for(;r<=o;){let i=r+o>>>1,s=n[i];if(e<t[i])o=i-1;else if(e>s>>>5)r=i+1;else return s&31}return 0}var Qi="090001000h1v5g2903000hl2v6jh16ng1s210111110o35aa10u2k1g10l6600152113h2010u1q1r5aq3890o13181214r22k3158q2n1000v100h1k20000001207030001160721k171001h1j11610332010010321210090411021c1c02100o301201412230u1130b100h1j116111420120411001100k11l10051001h1j11611142011000321210072411021d0g10r3000000132120090o200200g1j11f2012031213711271t1001o301001000001121371b1f0c101h1l2011001031212000080a1t1001m40400102101600i11t301006c7i601008b6p41r10101041h3d0004115a1j290p3q223000511010100g1501010302003172030c0010016000e0i6v50n40n5tl12ir33s12t11u11cj30100060700010a90t220000l71i20m7203010241000502rd101004k300000006101027050920g3t22bk1300616g209030207u18c1000t10003010501b2o20000102000004g37070101o921c000640602001mcv3rg20000001o16d0c0m1fg6g2h30m10q55f1vm11c0ma0p1a42nc0ne1a090q3314902021204020112030318250105bb1201110i1021i15101131502141b15120511011k1155132040202510201010603060a1f02040104210b1g3290e0e0kn11vs12j11j3040pp12t80g6v1vmo7319g21g51gh103040n11010040j51i3f01q1h1d0m27p1a0000cs13200523j200010301010100v140018a4q2501010101c08000i1f12601011g3012215110u1a0001015000pcq181000100011000iji5fvc0u91g5bhg20ie0l94lo6002115303121s12240la1tj23h44tj11t45m4ah33q700000l3ep2021a200t220301012040a0i320j2040007f00100r20c100g3208000011531000s520201036020t900207l1101n311000000321210090a12634b910201l22001051020120011020000e1i520701020000n10h5001050000010000010001re0010323010001r11i520701000001q6000000107l600000230004gg12080001lc62027111n1000411230000000000t820321030030r10090n205001380800501020n2050c0001mc00002000000nc006150000i5l1100600010001q753011160000i441111000000rl11019100000c1h201043102n10ltk1f006eoss2b0202gs94r36si2033ku101m373h50b1rqs4113sli1t22m1uh2435070726u13k92rr7m34h380e0m141egl561g1261114k60ga6nn10t33sv13uf1jf0207150qt16t66pr60n23k6bf1f0e1l29g71c1e029j1n30p11ea0k1028139m16rb2v621122i52213040tf1u3b51n17127c0232041d120819052c28220104060306l5g3l4572g130152cqdl2c3o37a5o27u11c32d9m2cu2191obo57eh9gg1tv3",Zi="262122424333333393233393339333333333393393bf3b3b3b3b3f3f3bffff33b3bb33ff3f33b3b3333333bffff3b33bb33f33bffff33b3bb33ff3f33b3bbb333b3ff33b333f33b3b3b3b3333b3bf33b3bb39333b33b33b3b3b333b333333b3b33333f3b33b3ffb3f3fff3f3b33f35dc33333f3b3b3b33323333b3bb3b33b3fb3b3333b33333bff3b3f33bfb3b3ff3b3b3b3b3b333b333b3323e22442344444444444444444444444444444444444444444444444444444444444444444444444444444443333333333b3b3bb33333b353bff3b3b3b3f3ff3b3b333bfff3f33333fb3bb3fb3b3bb33232333f333fff333333333b3b3333bb3b39393f3b3fbf33bb3b393b3b3b3333b33b33b3bbb33b33ffff3b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b3fffff3bb39b9b3b33b3bf3f3b33f3b3f93b33b3b3bb33b33b3b3b3333393b3b3b33b39bffb3b332333b333dd3b3333233332333333333333333333333333333444444444444a4444444444444344444444444444444444444444444444444444444444",es="0001000000010010000000100000000000000000000000000001000000010014000100000001001000010101100101100000000000000000000100000001111000010000000110101001110111111111000100000021001000010000000100100001000000011010000100000001111000013000000100140001000000010010";var ts=65535,Hr=40960,In=126976,os=new Uint8Array(12288),is=new Uint8Array(3072),ss=new Uint8Array(2816),as,cs;{let e=(o,i,s,l,a)=>{let c=i+o.length-1;for(let u=s<i?i:s,d=l>c?c:l;u<=d;u++)o[u-i]=a},t=new Uint32Array(320),n=new Uint32Array(320),r=0;for(let[o,i,s]of Ji(Qi,Zi))e(os,0,o,i,s),e(is,Hr,o,i,s),e(ss,In,o,i,s),i>=65040&&!(o>=In&&i<=129791)&&(t[r]=o,n[r++]=i<<5|s);as=t.slice(0,r),cs=n.slice(0,r)}function ns(e){return e<12288?os[e]:e<Hr?e<12336?e>=12330?3:0:e<12443?e===12336||e===12349?4:e>=12441?3:0:e===12951||e===12953?4:0:e<44032?is[e-Hr]:e<55204?(e-44032)%28?8:7:e<57344?e<=55238?e>=55216?13:0:e>=55243&&e<=55291?12:0:e<65024?e===64286?3:0:e<65040?3:e>=In&&e<129792?ss[e-In]:e>=917504?e>921599?0:e>=917536&&e<917632||e>=917760&&e<918e3?3:2:Xi(e,as,cs)}var ls=Uint8Array.from(es,Number);function Mu(e){return e===2381||e===2509||e===2637||e===2765||e===2893||e===3149||e===3405||e===4153||e===6098||e===6752||e===6980||e===7083||e===43456||e===43766||e===68159||e===69939||e===70608||e===71998||e===72263||e===72345||e===73538}function rs(e,t,n){switch(t){case 3:return e&24?n===8204?e&6:(e&24)===16||Mu(n)?e&6|16:e&6|8:e&6;case 4:return 2;case 10:return e&1^1;case 14:return(e&2)<<1|e&24;default:return 8}}function*us(e){let t=e.length;if(t===0)return;let n=e.codePointAt(0),r=n>ts?2:1,o=ns(n),i=50200>>o&1?rs(0,o,n):0,s=0,l=n,a=o;for(;r<t;){n=e.codePointAt(r);let c=n>ts?2:1,u=ns(n),d=ls[o<<4|u],f;d===0?f=!0:d===1?f=!1:d===2?f=!(i&1):d===3?f=!(i&4):f=(i&24)!==16,i=50200>>u&1&&(i!==0||u!==3)?rs(i,u,n):0,f&&(yield{segment:e.slice(s,r),index:s,input:e,_hd:l,_catBegin:a===15?0:a,_catEnd:o===15?0:o},s=r,l=n,a=u),r+=c,o=u}yield{segment:e.slice(s),index:s,input:e,_hd:l,_catBegin:a===15?0:a,_catEnd:o===15?0:o}}function*ds(e){for(let t of us(e))yield t.segment}{let e=us("_");ls._keep=[e,e.next()]}var fs=1e3,Uu=1,Bu=60,zu=3,qu=.5,Hu=2e4,Wu=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,Yu=/^\s+$/u,ps,Gu=e=>{let t=`${e??""}`.normalize("NFC"),n=globalThis.Intl?.Segmenter;return typeof n!="function"?Array.from(ds(t)):(ps??=new n(void 0,{granularity:"grapheme"}),Array.from(ps.segment(t),({segment:r})=>r))},Ku=e=>Gu(e).reduce((t,n)=>Yu.test(n)?t+qu:Wu.test(n)?t+zu:t+1,0),hs=({text:e="",baseDelay:t=fs,speed:n=Uu}={})=>{let r=Number.isFinite(t)?Math.max(0,t):fs,o=Number.isFinite(n)&&n>0?n:1,i=Ku(e)*Bu/o,s=Math.max(r,Hu);return Math.min(r+i,s)};var An={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Is=1,Wr=1,yt="choice",ze="form",xn=()=>({manual:{...An.manual},auto:{...An.auto},applyMode:An.applyMode}),Yr=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...xn()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},D=e=>{let t=ae(e)?Ke(e):e;return structuredClone(t)},N=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),As=(e,t)=>{if(typeof t!="string"||t.length===0)throw new Error("Achievement action requires a non-empty resourceId");let n=e.projectData.resources?.achievements?.[t];if(!n)throw new Error(`Achievement resource "${t}" not found`);if(n.type!=="boolean"&&n.type!=="number")throw new Error(`Achievement resource "${t}" has invalid type "${n.type}"`);return n},jt=e=>String(e),ws=()=>({sections:[],resources:[]}),Ju=e=>N(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):ws(),Xu=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Qu=({sectionId:e,lineId:t,content:n,dialogueState:r,characterName:o})=>({sectionId:e,lineId:t,content:n,text:Xu(n),characterId:r.characterId,character:{...r.character||{},name:o},characterName:o}),Zu=()=>({resourceId:void 0}),ed=e=>{if(!N(e))return e;let t={...e};return Object.prototype.hasOwnProperty.call(t,"requireComplete")&&!Object.prototype.hasOwnProperty.call(t,"requireLineCompleted")&&(t.requireLineCompleted=t.requireComplete),delete t.requireComplete,t},bt=(e,t)=>{let n=e?.story?.scenes??{};for(let[r,o]of Object.entries(n))if(o?.sections?.[t])return{sceneId:r,section:o.sections[t]};return{sceneId:void 0,section:void 0}},Es=e=>{let t=e?.story?.scenes??{},n=new Map;for(let[r,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let l=n.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${r}". Section IDs must be globally unique.`);n.set(s,r)}}},xs=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},vs=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Is)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},td=(e,t={})=>{let n;try{n=vs(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:xs(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},nd=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,td(t,n)])),Cs=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:n})=>cp(n));return t.length>0?t:void 0},rd=e=>{!N(e)||!Array.isArray(e.timeline)||(e.returnabilityVersion=Wr,e.timeline.forEach(t=>{if(!N(t))return;typeof t.returnable!="boolean"&&delete t.returnable;let n=Cs(t.executedActions);if(n){t.executedActions=n;return}delete t.executedActions}))},ms=(e,t,n,r="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!N(e))throw new Error(`Malformed ${r}.${t}[${n}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${r}.${t}[${n}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${r}.sections[${n}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},od=(e,t="viewedRegistry")=>{if(e===void 0)return ws();if(!N(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let n=e.sections??[],r=e.resources??[];return{sections:Object.values(Object.fromEntries(n.map((o,i)=>{let s=ms(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(r.map((o,i)=>{let s=ms(o,"resources",i,t);return[s.resourceId,s]})))}},Ss=(e,t,n)=>{if(!N(e))throw new Error(`Malformed save slot ${n}.`);let{sectionId:r,lineId:o}=e;if(typeof r!="string"||r.length===0)throw new Error(`Malformed save slot ${n}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${n}: missing lineId.`);let{sceneId:i,section:s}=bt(t,r);if(!s)throw new Error(`Malformed save slot ${n}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(a=>a.id===o))throw new Error(`Malformed save slot ${n}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},Os=(e,t)=>e?.sectionId===t?.sectionId&&e?.lineId===t?.lineId,id=(e,t)=>{let{section:n}=bt(e,t?.sectionId);return n?.lines?.find(r=>r.id===t?.lineId)},sd=(e,t)=>{let{section:n}=bt(e,t?.sectionId),r=n?.lines?.findIndex(i=>i.id===t?.lineId);if(typeof r!="number"||r<0)return null;let o=n.lines[r+1];return o?{sectionId:t.sectionId,lineId:o.id}:null},Rs=(e,t,n)=>{if(typeof t?.sectionId!="string")return!1;let{section:r}=bt(e,t.sectionId);return Os({sectionId:t.sectionId,lineId:r?.lines?.[0]?.id},n)},ad=new Set(["jumpToLine","rollbackByOffset","rollbackToLine","sectionTransition","resetStoryAtSection"]),gt={always:"always",maybe:"maybe",never:"never"},cd=e=>{if(!Object.prototype.hasOwnProperty.call(e??{},"when"))return gt.always;let t=e.when,n;if(t===null||typeof t=="boolean"||typeof t=="number")n=t;else if(N(t)&&Object.keys(t).length===1&&Object.prototype.hasOwnProperty.call(t,"literal"))n=t.literal;else return gt.maybe;return n?gt.always:gt.never},_s=(e,t)=>{if(!Array.isArray(e?.branches))return!1;for(let n of e.branches){let r=cd(n);if(r!==gt.never){if(t(n))return!0;if(r===gt.always)return!1}}return!1},ks=e=>_s(e,t=>Object.entries(t?.actions??{}).some(([n,r])=>n==="conditional"?ks(r):ad.has(n))),$s=(e,t,n)=>_s(t,r=>Object.entries(r?.actions??{}).some(([o,i])=>o==="sectionTransition"?Rs(e,i,n):o==="conditional"?$s(e,i,n):!1)),ld=(e,t,n)=>{if(!t)return!0;let r=id(n,e)?.actions;if(!N(r))return!0;if(Rs(n,r.sectionTransition,t))return!1;let o=r.conditional;return o?!($s(n,o,t)||!(r.choice?.resourceId||r.form?.resourceId)&&!ks(o)&&Os(sd(n,e),t)):!0},ud=(e,t,n)=>{if(!N(e)||!Array.isArray(e.timeline))return Vt({pointer:t,replayStartIndex:1});let r=new WeakSet,o=e.timeline.flatMap((c,u)=>{if(!N(c))return[];try{let d=Ss(c,n,`rollback.timeline[${u}]`),f=En({sectionId:d.sectionId,lineId:d.lineId,rollbackPolicy:c.rollbackPolicy,returnable:c.returnable});typeof c.returnable=="boolean"&&r.add(f);let p=Cs(D(c.executedActions));return p&&(f.executedActions=p),[f]}catch{return[]}});if(o.length===0)return Vt({pointer:t,replayStartIndex:1});e.returnabilityVersion!==Wr&&o.forEach((c,u)=>{!r.has(c)&&!ld(c,o[u+1],n)&&(c.returnable=!1)});let s=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):o.length-1;(s<0||s>=o.length)&&(s=o.length-1);let l=o[s];if(l?.sectionId!==t.sectionId||l?.lineId!==t.lineId){let c=o.findLastIndex(u=>u.sectionId===t.sectionId&&u.lineId===t.lineId);c>=0?s=c:(o.push(En({sectionId:t.sectionId,lineId:t.lineId})),s=o.length-1)}let a=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),s):0;return{currentIndex:s,isRestoring:!1,replayStartIndex:a,timeline:o}},dd=(e,t,n)=>{if(!N(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=Jr(t),o=Ss(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!N(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);if(e.runtime!==void 0&&!N(e.runtime))throw new Error(`Malformed save slot contexts[${n}].runtime entry.`);let i=e.variables?dt(D(e.variables),t.resources?.variables??{}):{},s=vd({loadedContextRuntime:N(e.runtime)?D(e.runtime):{}}),l={currentPointerMode:"read",pointers:{read:o},configuration:N(e.configuration)?D(e.configuration):{},views:Array.isArray(e.views)?D(e.views):[],bgm:N(e.bgm)?D(e.bgm):{resourceId:void 0},variables:{...r,...i},rollback:ud(e.rollback,o,t)};return s&&(l.runtime=s),l},fd=(e,t)=>{if(!N(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((n,r)=>dd(n,t,r))}},pd=(e,t)=>{if(!N(e))throw new Error("Malformed save slot.");let n=vs(e.formatVersion);return{...e,formatVersion:n,state:fd(e.state,t)}},gs=(e,t,{required:n=!1}={})=>{if(e===void 0){if(n)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let r=D(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},hd=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:gs(e.confirmActions,"confirmActions",{required:!0}),cancelActions:gs(e.cancelActions,"cancelActions")}},It=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},md=e=>(N(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),At=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},Ls=e=>{if(!(!N(e)||!e.animations))return{animations:D(e.animations)}},gd=(e,t)=>{let n=Ls(t);if(n){e.global.pendingScreenTransition=n;return}delete e.global.pendingScreenTransition},yd=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},bd=(e,t)=>{let n=e?.sectionId,r=e?.lineId;if(!(!n||!r||!t))return`${n}:${r}:${t}`},wn=e=>String(e??""),Ts=(e,t)=>{let n=wn(t);return e?.trim===!0?n.trim():n},Id=e=>N(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>N(t)).map(([t,n])=>[t,{id:t,...D(n)}])):{},Ad=(e,t)=>{if(!t||!N(e.global.formDrafts))return;let n=e.global.formDrafts[t];return N(n)?n:void 0},Ns=(e,t)=>{let n=md(e);N(n[t])||(n[t]={values:{},touched:{},errors:{},submitted:!1});let r=n[t];return N(r.values)||(r.values={}),N(r.touched)||(r.touched={}),N(r.errors)||(r.errors={}),typeof r.submitted!="boolean"&&(r.submitted=!1),r},Gr=(e,t)=>{let n=Ts(e,t);return e?.required===!0&&n.length===0?"required":null},wd=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let r=ue({state:e},{sectionId:t.sectionId})?.lines||[],o=r.findIndex(i=>i.id===t.lineId);return o<0?{}:Qe(r.slice(0,o+1).map(i=>i.actions||{}))},Ed=({state:e,form:t,pointer:n})=>{if(!t?.resourceId)return null;let r=yd(t),o=bd(n,r);if(!r||!o)return null;let i=Ad(e,o),s=Id(t),l=Cn({state:e}),a={},c=[],u={},d=!0;return Object.entries(s).forEach(([f,p])=>{let h=wn(l?.[p.variableId]),m=Object.prototype.hasOwnProperty.call(i?.values??{},f)?wn(i.values[f]):h,y=i?.touched?.[f]===!0,I=Gr(p,m),w=i?.submitted||y?I:null,E=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,R={id:f,variableId:p.variableId,value:m,initialValue:h,valid:!I,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}:{}};I&&(d=!1),a[f]=R,c.push(R),u[f]=m}),{id:r,key:o,resourceId:t.resourceId,animations:t.animations,valid:d,submitted:i?.submitted===!0,fields:a,fieldList:c,values:u,submitActions:{submitForm:{formKey:o,actions:D(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:D(t.cancelActions??{})}}}},ot=[],ys="line",Kr="interaction",En=({sectionId:e,lineId:t,rollbackPolicy:n,returnable:r})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free",...typeof r=="boolean"?{returnable:r}:{}}),Jr=e=>{let{contextVariableDefaultValues:t}=an(e??{});return D(t)},Ds=()=>({...D($t)}),Ps=({loadedRuntime:e,runtimeIds:t,defaults:n={},path:r})=>{if(e===void 0)return{runtimeState:D(n),hasLoadedValues:!1};if(!N(e))throw new Error(`Malformed ${r}.`);let o=D(n),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Vs(s,D(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},xd=({loadedGlobalRuntime:e={}})=>Ps({loadedRuntime:e,runtimeIds:yr,defaults:Ze,path:"global.runtime"}).runtimeState,vd=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:n}=Ps({loadedRuntime:e,runtimeIds:br,defaults:Ds(),path:"context.runtime"});return n?t:void 0},vn=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Cd=e=>e.runtime?(br.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=D($t[t]))}),e.runtime):(e.runtime=Ds(),e.runtime),Sd=e=>Ai(e.global),Od=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Sd(e)}})},Rd=e=>Ii[e],_d=(e,t)=>{let n=Rd(e);if(n==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(n==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(n==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},Vs=(e,t)=>{if(_d(e,t),e==="autoForwardSpeed"&&t<=0)throw new Error("autoForwardSpeed requires a value greater than 0");return e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t},js=(e,t,n)=>{let r=Vs(t,n);if(t in $t){let o=vn(e);if(!o)return r;let i=Cd(o);return i[t]=r,r}return e.global[t]=r,r},Fs=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:D(e)},configuration:{},views:[],bgm:Zu(),variables:Jr(t),rollback:Vt({pointer:e})}),wt=e=>e?(e.currentPointerMode="read",N(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,kd=(e,{queueRender:t=!0}={})=>{let n=e.contexts?.[e.contexts.length-1],r=n?.pointers?.read;if(!n||!r?.sectionId||!r?.lineId)return null;let o=Fs({pointer:r,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,$d(e,{queueRender:t}),o},$d=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,It(e),At(e),e.global.nextLineConfig=xn(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},Ms=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},Vt=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[En({sectionId:e.sectionId,lineId:e.lineId})]:[]}},st=(e,t={})=>{if(e?.rollback)return Ms(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let n=e?.pointers?.read;return e.rollback=Vt({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},Xr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=st(n);r.isRestoring||(r.currentIndex<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,r.currentIndex+1)),r.timeline.push(En(t)),r.currentIndex=r.timeline.length-1)},Ld=({state:e})=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!Array.isArray(n?.timeline)||typeof n.currentIndex!="number"?null:{checkpointIndex:n.currentIndex,checkpoint:n.timeline[n.currentIndex]??null}},Td=({state:e},t={})=>{let{checkpointIndex:n,checkpointIdentity:r,sectionId:o,lineId:i}=t,l=e.contexts?.[e.contexts.length-1]?.rollback;if(!Number.isInteger(n)||!Array.isArray(l?.timeline)||typeof l.currentIndex!="number")return e;let a=l.timeline[n];return(ae(a)?qn(a):a)!==r||a?.sectionId!==o||a?.lineId!==i||(a.returnable=!1),e},Nd=({state:e},t={})=>{let{slotId:n,saveSlotIdentity:r,checkpointIndex:o,sectionId:i,lineId:s}=t,l=jt(n),a=e.global.saveSlots?.[l],c=ae(a)?qn(a):a;if(!a||c!==r)return e;let u=a.state?.contexts,d=Array.isArray(u)?u.at(-1):null,f=d?.rollback,p=f?.timeline?.[o];return!Number.isInteger(o)||f?.currentIndex!==o||d?.pointers?.read?.sectionId!==i||d?.pointers?.read?.lineId!==s||p?.sectionId!==i||p?.lineId!==s||(p.returnable=!1,f.returnabilityVersion=Wr,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}})),e},Dd=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;if(!n||n.isRestoring||!Array.isArray(n.timeline)||typeof n.currentIndex!="number")return null;let r=ot[ot.length-1],o=typeof r?.checkpointIndex=="number"?r.checkpointIndex:n.currentIndex;return o<0||o>=n.timeline.length?null:(typeof r?.checkpointIndex!="number"&&o<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,o+1)),n.timeline[o]??null)},Pd=({state:e},t={})=>{let n=t?.source===ys?ys:Kr,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?(ot.push({checkpointIndex:null,source:n}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),ot.push({checkpointIndex:o.currentIndex,source:n}),e)},Vd=({state:e})=>(ot.pop(),e),ke=(e,t,n)=>{let o=ot[ot.length-1]?.source??Kr;if(!lp(t,o))return;let i=Dd(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:D(n)}))},bs=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:l}of r){let a=e.projectData.resources?.variables?.[o],c=a?.scope,u=a?.type;if(Ce(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);_t(c,o),cn(u,i,o),dr(u,i,s,o,{roundTo:l}),c==="context"&&(n.variables[o]=ln(n.variables[o],i,s,{roundTo:l}))}},jd=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:n,payload:r})=>{up(e,n,r)})},Fd=(e,t)=>{let{sectionId:n,lineId:r}=t,s=ue({state:e},{sectionId:n})?.lines?.find(l=>l.id===r)?.actions;s&&Object.entries(s).forEach(([l,a])=>{ra(e,l,a)})},Us=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=st(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Mt({state:e}),e.global.skipMode&&qe({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=Jr(e.projectData),delete n.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=D(An),e.global.overlayStack=[],It(e),At(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let l=i;l<=t;l++)l>i&&Yr(e),Fd(e,r.timeline[l]),jd(e,r.timeline[l]);let s=wt(n);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{r.isRestoring=!1}return e},Md=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=n;Es(t),Xe(t?.resources?.variables??{});let l=t.story.initialSceneId,a=t.story.scenes[l],c=a.initialSectionId,u=a.sections[c],d={sceneId:l,sectionId:c,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:f}=an(t),p={...f,...dt(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:od(s,"accountViewedRegistry"),nextLineConfig:xn(),saveSlots:nd(r),overlayStack:[],variables:p,...xd({loadedGlobalRuntime:i})},contexts:[Fs({pointer:d,projectData:t})]}},Ud=({state:e})=>e.global.overlayStack||[],Bd=({state:e})=>e.global.pendingEffects,Bs=({state:e})=>e.global.skipMode,zd=({state:e})=>e.global.autoMode,zs=({state:e})=>e.global.dialogueUIHidden,qs=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(!n)return[];let{sectionId:r,lineId:o}=n.pointers.read,i=ue({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(d=>d.id===o),l=i.lines.slice(0,s+1),a=[],c={},u=Rt({variables:{...e.global?.variables??{},...vn(e)?.variables??{}},runtime:et(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let d of l){let f=d.actions||{};if(c=Qe([c,f]),!f.dialogue)continue;let p=c.dialogue||{},h=sn({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:u}),m=Qu({sectionId:r,lineId:d.id,content:f.dialogue.append===!0?p.content:f.dialogue.content,dialogueState:p,characterName:h});if(f.dialogue.append===!0&&a.length>0){a[a.length-1]={...a[a.length-1],content:m.content,text:m.text,characterId:m.characterId,character:m.character,characterName:m.characterName};continue}a.push(m)}return a},qd=({state:e})=>e.global.confirmDialog??null,Ft=({state:e},{pointer:t}={})=>{let n=t??Ee({state:e})?.pointer,r=wd({state:e,pointer:n});return Ed({state:e,form:r.form,pointer:n})},Hd=({state:e},{pointer:t}={})=>!!Ft({state:e},{pointer:t}),xe=({state:e},{pointer:t}={})=>{let n=Ft({state:e},{pointer:t});if(n)return{source:ze,formId:n.id,formKey:n.key};let r=Hs({state:e,pointer:t});return r?{source:yt,resourceId:r}:null},Wd=({state:e,registry:t},n)=>{let{sectionId:r,lineId:o}=n,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===r);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let l=ue({state:e},{sectionId:r});if(!l||!l.lines||!Array.isArray(l.lines))return s.lastLineId===o;let a=l.lines.findIndex(u=>u.id===s.lastLineId),c=l.lines.findIndex(u=>u.id===o);return a===-1||c===-1?s.lastLineId===o:c<=a},Yd=({registry:e},t)=>{let{resourceId:n}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===n)},Qr=({state:e},t)=>Wd({state:e,registry:e.global.accountViewedRegistry},t),Gd=({state:e},t)=>Yd({registry:e.global.accountViewedRegistry},t),Kd=({state:e})=>e.global.nextLineConfig,Hs=({state:e,pointer:t}={})=>{let n=t??Ee({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=ue({state:e},{sectionId:r})?.lines||[],l=s.findIndex(c=>c.id===o);if(l<0)return;let a;for(let c of s.slice(0,l+1)){let u=c?.actions;if(u?.cleanAll&&(a=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){a=void 0;continue}let d=u.choice;if(d?.resourceId){a=d.resourceId;continue}d?.animations||(a=void 0)}return a},Ws=({state:e})=>!!Hs({state:e}),Jd=({state:e})=>structuredClone(e),Xd=({state:e})=>D(e.projectData.resources?.achievements??{}),Qd=({state:e},t)=>{let n=e.projectData.resources?.achievements?.[t?.resourceId];return n===void 0?void 0:D(n)},Ys=({state:e})=>e.global.saveSlots,Zd=({state:e},t)=>{let n=t?.slotId,r=jt(n);return e.global.saveSlots[r]},Zr=({state:e})=>et(e),ef=({state:e},t)=>Me(e,t?.runtimeId),Cn=({state:e})=>{let t={...e.global?.variables??{},...vn(e)?.variables??{}};return Rt({variables:t,runtime:et(e),variableConfigs:e.projectData.resources?.variables??{}})},Ee=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(n)return{currentPointerMode:"read",pointer:n.pointers?.read}},ue=({state:e},t)=>{let{sectionId:n}=t;return bt(e.projectData,n).section},Sn=({state:e})=>{let t=Ee({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=ue({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},Gs=({state:e})=>{let{sectionId:t,lineId:n}=Ee({state:e}).pointer,o=ue({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n),l=o.slice(0,i+1).map(c=>{let u=c.actions||{},d={};return Object.keys(u).forEach(f=>{d[f]=u[f]}),d});return Qe(l)},tf=e=>{let t=Sn({state:e})?.actions?.dialogue;if(t?.clear===!0||!Array.isArray(t?.content))return"";let n=Cn({state:e});return t.content.map(r=>`${ft(r?.text,{variables:n})??""}`).join("")},On=({state:e})=>hs({text:tf(e),baseDelay:Me(e,"autoForwardDelay"),speed:Me(e,"autoForwardSpeed")}),nf=({state:e})=>{let t=Ks({state:e}),r=Sn({state:e})?.actions??{},o=Qe([t??{},r]);return pr(t??{},o??{})},rf=({state:e},{sectionId:t})=>{let n=ue({state:e},{sectionId:t});if(!n?.lines)return[];let r=[],o={};for(let i of n.lines){let s=i.actions||{},l=Qe([o,s]),a=pr(o,l);r.push({id:i.id,changes:a,presentationState:l}),o=hr(l)}return r},of=({state:e},{sectionId:t,includePresentationState:n=!1})=>{let r=rf({state:e},{sectionId:t});return n?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},Ks=({state:e})=>{let{sectionId:t,lineId:n}=Ee({state:e}).pointer,o=ue({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===n);if(i<=0)return null;let l=o.slice(0,i).map(a=>{let c=a.actions||{},u={};return Object.keys(c).forEach(d=>{u[d]=c[d]}),u});return hr(Qe(l))},eo=({state:e},{slotsPerPage:t=6}={})=>{let o=((Zr({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let l=o+s,a=e.global.saveSlots&&e.global.saveSlots[jt(l)]||{};i.push({...a,slotId:l})}return{saveSlots:i}},sf=Ys,af=eo,cf=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!n||!Array.isArray(n.timeline)||typeof n.currentIndex!="number"?!1:n.currentIndex>=0&&n.currentIndex<n.timeline.length-1},lf=({state:e},t={})=>{let n=Gs({state:e}),r=Ks({state:e}),o=Sn({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:D(i)}:o,l=i?.animations&&r===null?{}:r,{sectionId:a}=Ee({state:e}).pointer,{sceneId:c}=bt(e.projectData,a),u=Zr({state:e}),d=t?.activePersistentAnimations??[],f=t?.restoredPersistentAnimations??[],p=Ft({state:e}),h=Ws({state:e}),m=Cn({state:e}),{saveSlots:y}=eo({state:e}),I=cf(e);return Ki({presentationState:n,previousPresentationState:l,currentLineActions:s,resources:e.projectData.resources,currentSceneId:c,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:sa({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||I,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:qs({state:e}),saveSlots:y,variables:m,runtime:u,activePersistentAnimations:d,restoredPersistentAnimations:f})},uf=({state:e},t)=>(e.global.confirmDialog=hd(t),e.global.pendingEffects.push({name:"render"}),e),df=({state:e})=>(e.global.confirmDialog&&(It(e),e.global.pendingEffects.push({name:"render"})),e),ff=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),ke(e,"pushOverlay",t),e),pf=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),ke(e,"popOverlay",void 0),e),hf=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),ke(e,"replaceLastOverlay",t),e),mf=({state:e})=>(e.global.overlayStack=[],It(e),At(e),e.global.pendingEffects.push({name:"render"}),ke(e,"clearOverlays",void 0),e),gf=(e,{activeInteraction:t})=>{e.global.autoMode&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),t&&e.global.skipMode&&e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},Rn=(e,t,{screenTransition:n}={})=>{e.global.isLineCompleted=!1,gd(e,n),At(e);let r=xe({state:e},{pointer:t}),o=r?.source===yt,i=r?.source===ze;return gf(e,{activeInteraction:r}),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:r}},_n=(e,t,n)=>{!(t?.source===yt||t?.source===ze)||n||!e.global.skipMode||e.global.pendingEffects.push({name:"startSkipNextTimer"})},Js=({state:e})=>(xe({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:On({state:e})}}),e.global.pendingEffects.push({name:"render"})),e),Mt=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),yf=({state:e})=>{let t=e.global.autoMode;return xe({state:e})&&!t||(t?Mt({state:e}):Js({state:e})),e},Xs=({state:e})=>(xe({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),qe=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),bf=({state:e})=>{let t=Bs({state:e});return xe({state:e})&&!t||(t?qe({state:e}):Xs({state:e})),e},kn=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),ke(e,"showDialogueUI",void 0),e),Qs=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),ke(e,"hideDialogueUI",void 0),e),If=({state:e})=>(zs({state:e})?kn({state:e}):Qs({state:e}),e),He=(e,t,n)=>(js(e,t,n),Od(e),e.global.pendingEffects.push({name:"render"}),e),Ut=(e,t,n,r)=>{let o=js(e,t,n);return e.global.pendingEffects.push({name:"render"}),ke(e,r,{value:o}),e},Af=({state:e},t)=>He(e,"dialogueTextSpeed",t?.value),wf=({state:e},t)=>He(e,"autoForwardDelay",t?.value),Ef=({state:e},t)=>He(e,"autoForwardSpeed",t?.value),xf=({state:e},t)=>He(e,"skipUnseenText",t?.value),vf=({state:e},t)=>He(e,"skipTransitionsAndAnimations",t?.value),Cf=({state:e},t)=>He(e,"soundVolume",t?.value),Sf=({state:e},t)=>He(e,"musicVolume",t?.value),Of=({state:e},t)=>He(e,"muteAll",t?.value),Rf=({state:e},t)=>Ut(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),_f=({state:e})=>{let t=Me(e,"saveLoadPagination")+1;return Ut(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},kf=({state:e})=>{let t=Me(e,"saveLoadPagination")-1;return Ut(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},$f=({state:e},t)=>Ut(e,"menuPage",t?.value,"setMenuPage"),Lf=({state:e},t)=>Ut(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Tf=({state:e})=>(e.global.pendingEffects=[],e),Nf=({state:e},t)=>(e.global.pendingEffects.push(t),e),Df=({state:e},t)=>{let n=t?.resourceId;return As(e,n),e.global.pendingEffects.push({name:"completeAchievement",payload:{resourceId:n}}),e},Pf=({state:e},t)=>{let n=t?.resourceId,r=As(e,n);if(r.type!=="number")throw new Error(`Achievement resource "${n}" does not support numeric progress`);let o=t?.current;if(!Number.isInteger(o)||o<0)throw new Error(`Achievement progress for "${n}" must be a non-negative integer`);if(!Number.isInteger(r.target)||r.target<1)throw new Error(`Achievement resource "${n}" must have a positive integer target`);let i=Math.min(o,r.target);return e.global.pendingEffects.push({name:"setAchievementProgress",payload:{resourceId:n,current:i,target:r.target,completed:i>=r.target}}),e},Zs=(e,{sectionId:t,resetStoryState:n=!1,screen:r})=>{let o=!!Ls(r),i=ue({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(n&&!kd(e,{queueRender:!o}))return e;let l=xe({state:e});n&&e.global.skipMode&&qe({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let u=wt(a),d=u.read;n||it(e,{sectionId:d?.sectionId,lineId:d?.lineId}),a.rollback||st(a,{compatibilityAnchor:!0}),u.read={sectionId:t,lineId:s.id},n?a.rollback=Vt({pointer:u.read}):Xr(e,{sectionId:t,lineId:s.id})}let{activeInteraction:c}=Rn(e,a?.pointers?.read,{screenTransition:r});return _n(e,l,c),e},Vf=({state:e},t)=>Zs(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),ea=e=>(e.global.accountViewedRegistry=Ju(e.global.accountViewedRegistry),e.global.accountViewedRegistry),to=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(n=>({scope:n.scope,path:n.path,op:n.op,value:D(n.value)}))}})},ta=(e,t)=>{to(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(n=>({sectionId:n.sectionId,...n.lastLineId===void 0?{}:{lineId:n.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},jf=(e,t,{sectionId:n,lineId:r})=>{if(!n||!r)return!1;let o=N(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===n);if(i){if(i.lastLineId===void 0)return!1;let s=ue({state:e},{sectionId:n});if(s?.lines){let l=s.lines.findIndex(c=>c.id===i.lastLineId),a=s.lines.findIndex(c=>c.id===r);if(l===-1||a>l)return i.lastLineId===r?!1:(i.lastLineId=r,!0)}else return i.lastLineId===r?!1:(i.lastLineId=r,!0);return!1}else return o.sections.push({sectionId:n,lastLineId:r}),!0},it=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;jf(e,ea(e),t)&&ta(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},Ff=({state:e},t)=>(it(e,t),e.global.pendingEffects.push({name:"render"}),e),Mf=({state:e},t)=>{let{resourceId:n}=t;if(e.global.accountViewedRegistry!==void 0){let r=ea(e);r.resources.find(i=>i.resourceId===n)||(r.resources.push({resourceId:n}),ta(e,{sections:[],resources:[{resourceId:n}]}))}return e.global.pendingEffects.push({name:"render"}),e},na=({state:e},t)=>{let n=ed(t.manual),{auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;n&&r?(e.global.nextLineConfig={manual:n,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let a=e.global.nextLineConfig.auto?.enabled,c=xe({state:e});return!l&&!c&&a===!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&&a===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),ke(e,"setNextLineConfig",t),e},Uf=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:r}=t,o=t?.savedAt,i=jt(n),s=D(e.contexts);s?.forEach(c=>{wt(c),Ms(c.rollback),rd(c.rollback)});let l={contexts:s},a={formatVersion:Is,slotId:xs(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:l};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Bf=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=jt(n),o=e.global.saveSlots[r];if(o){let i=pd(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=xn(),e.global.overlayStack=[],e.global.isLineCompleted=!0,It(e),At(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},zf=({state:e},t)=>{let{projectData:n}=t;Es(n),Xe(n?.resources?.variables??{}),e.projectData=n;let r=n?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=an(n??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...dt(e.global.variables,r)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...dt(s.variables,r)})}),It(e),At(e),e.global.pendingEffects.push({name:"render"}),e},qf=({state:e},t)=>{let{sectionId:n,lineId:r}=t;if(!r)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=n||o.pointers.read?.sectionId;if(n&&!ue({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=ue({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(d=>d.id===r))return console.warn(`Line not found: ${r} in section ${i}`),e;let a=xe({state:e}),c=wt(o);c.read={sectionId:i,lineId:r};let{activeInteraction:u}=Rn(e,c.read);return _n(e,a,u),e},Hf=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return kn({state:e}),e;let n=xe({state:e});if(n?.source===yt&&t?.bypassChoice!==!0||n?.source===ze&&t?._interactionSource!==ze)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=Ee({state:e})?.pointer,d=u?.sectionId,f=u?.lineId;d&&f&&it(e,{sectionId:d,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&!n&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:On({state:e})}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&!n&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let r=Ee({state:e})?.pointer,o=r?.sectionId,i=ue({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],l=i?.lines||[],c=l.findIndex(u=>u.id===r?.lineId)+1;if(c<l.length){let u=l[c],d=!Me(e,"skipUnseenText");if(e.global.skipMode&&d&&!Qr({state:e},{sectionId:o,lineId:u.id}))return qe({state:e}),e;if(s&&!s.rollback&&st(s,{compatibilityAnchor:!0}),s){let p=wt(s),h=p.read?.lineId;h&&o&&it(e,{sectionId:o,lineId:h}),p.read={sectionId:o,lineId:u.id}}Xr(e,{sectionId:o,lineId:u.id}),Yr(e);let{activeInteraction:f}=Rn(e,{sectionId:o,lineId:u.id});_n(e,n,f)}else e.global.autoMode&&Mt({state:e}),e.global.skipMode&&qe({state:e});return e},Wf=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=xe({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:On({state:e})}});let n=Ee({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&it(e,{sectionId:r,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},Yf=({state:e},t)=>Zs(e,{sectionId:t?.sectionId,screen:t?.screen}),Gf=({state:e},t)=>{let n=t?._conditionalContinuation===!0;if(e.global.dialogueUIHidden&&!n)return kn({state:e}),e;let r=xe({state:e});if(r?.source===yt&&t?.bypassChoice!==!0||r?.source===ze&&t?._interactionSource!==ze||r&&r.source!==yt&&r.source!==ze)return e;let o=Ee({state:e})?.pointer,i=o?.sectionId,s=ue({state:e},{sectionId:i}),l=e.contexts[e.contexts.length-1],a=s?.lines||[],u=a.findIndex(d=>d.id===o?.lineId)+1;if(u<a.length){let d=a[u],f=!Me(e,"skipUnseenText");if(e.global.skipMode&&f&&!Qr({state:e},{sectionId:i,lineId:d.id})&&(qe({state:e}),!n))return e;if(l&&!l.rollback&&st(l,{compatibilityAnchor:!0}),l){let h=wt(l),m=h.read?.lineId;m&&i&&it(e,{sectionId:i,lineId:m}),h.read={sectionId:i,lineId:d.id}}Xr(e,{sectionId:i,lineId:d.id}),Yr(e);let{activeInteraction:p}=Rn(e,{sectionId:i,lineId:d.id});_n(e,r,p)}else e.global.autoMode&&Mt({state:e}),e.global.skipMode&&qe({state:e}),e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},no=(e,t={})=>{let n=Ft({state:e});return!n||t.formKey&&t.formKey!==n.key||t.formId&&t.formId!==n.id?null:n},Kf=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let n=e.projectData.resources?.variables?.[t.variableId],r=n?.scope,o=n?.type;if(Ce(n))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(n?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return _t(r,t.variableId),cn(o,"set",t.variableId),{variableConfig:n,scope:r}},Jf=(e,t)=>({id:e.id,key:e.key,valid:!0,values:D(t),fields:D(e.fields),fieldList:D(e.fieldList)}),Xf=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ee({state:e})?.pointer,n=t?.sectionId,r=t?.lineId;n&&r&&it(e,{sectionId:n,lineId:r})},Qf=({state:e},t={})=>{let n=no(e,t),r=t.field;if(!n?.fields?.[r])return e;let o=Ns(e,n.key),i=wn(t.value),s=n.fields[r],l=Gr(s,i);return o.values[r]=i,o.touched[r]=!0,l?o.errors[r]=l:delete o.errors[r],e.global.pendingEffects.push({name:"render"}),e},Zf=({state:e},t={})=>{let n=no(e,t);if(!n)return{submitted:!1,valid:!1,reason:"inactive"};let r=Ns(e,n.key);r.submitted=!0;let o={},i={};if(Object.entries(n.fields).forEach(([d,f])=>{let p=Object.prototype.hasOwnProperty.call(r.values,d)?r.values[d]:f.value,h=Gr(f,p);r.touched[d]=!0,h&&(i[d]=h),o[d]=Ts(f,p)}),r.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:D(i),form:{id:n.id,key:n.key,values:D(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let l=!1,a=[],c=[];Object.entries(n.fields).forEach(([d,f])=>{let{scope:p}=Kf(e,f),h=p==="context"?s.variables:e.global.variables,m=o[d];h[f.variableId]=ln(h[f.variableId],"set",m),p==="context"&&(l=!0,c.push({variableId:f.variableId,op:"set",value:m})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${f.variableId}`,op:"set",value:D(h[f.variableId])})}),l&&ke(e,"updateVariable",{id:"submitForm",operations:c}),to(e,a);let u=Jf(n,o);return Xf(e),delete e.global.formDrafts[n.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},ep=({state:e},t={})=>{let n=no(e,t);return n?(delete e.global.formDrafts?.[n.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:n.id,key:n.key,values:D(n.values),fields:D(n.fields),fieldList:D(n.fieldList)}}):{cancelled:!1,reason:"inactive"}},tp=({state:e},t)=>{let{id:n,operations:r=[]}=t;if(!n)throw new Error("updateVariable requires an id field");if(typeof n!="string"||!/^[a-zA-Z0-9]+$/.test(n))throw new Error(`updateVariable id must be alphanumeric, got: "${n}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],l=[];return r.forEach(({variableId:a,op:c,value:u,roundTo:d})=>{let f=e.projectData.resources?.variables?.[a],p=f?.scope,h=f?.type;if(Ce(f))throw new Error(`Cannot update computed variable: ${a}`);if(f?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);_t(p,a),cn(h,c,a),dr(h,c,u,a,{roundTo:d});let m=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:a,op:c,value:u};d!==void 0&&(y.roundTo=d),l.push(y)}m[a]=ln(m[a],c,u,{roundTo:d}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:D(m[a])})}),i&&ke(e,"updateVariable",{id:n,operations:l}),to(e,s),e.global.pendingEffects.push({name:"render"}),e},np=e=>(t,n)=>e({state:t},n),rp=e=>({variables:Rt({variables:{...e.global?.variables??{},...vn(e)?.variables??{}},runtime:et(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:et(e)}),op=e=>{if(!N(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")},ip=(e,t,n)=>{if(!N(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!N(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==n-1)throw new Error("conditional else branch must be the last branch")},sp=(e,t)=>{op(t);for(let n=0;n<t.branches.length;n+=1){let r=t.branches[n];if(ip(r,n,t.branches.length),!(Object.prototype.hasOwnProperty.call(r,"when")&&!Ot(r.when,rp(e)))){Object.entries(r.actions).forEach(([i,s])=>{ra(e,i,s)});return}}},ap={conditional:{replayLine:sp},updateVariable:{recordSources:[Kr],replayLine:bs,replayRecorded:bs,persistInSaveSlot:!0},setNextLineConfig:{replayLine:np(na)}},$n=e=>ap[e]??null,cp=e=>$n(e)?.persistInSaveSlot===!0,lp=(e,t)=>{let n=$n(e)?.recordSources;return Array.isArray(n)&&n.includes(t)},up=(e,t,n)=>{$n(t)?.replayRecorded?.(e,n)},ra=(e,t,n)=>{$n(t)?.replayLine?.(e,n)},dp=e=>e?.returnable!==!1,oa=(e,t)=>{if(t>=0)return e.currentIndex+t;let n=Math.abs(t);for(let r=e.currentIndex-1;r>=0;r-=1)if(dp(e.timeline[r])&&(n-=1,n===0))return r;return-1},ia=({state:e},t)=>{let{offset:n}=t;if(n===void 0||typeof n!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let r=e.contexts[e.contexts.length-1];if(!r)return null;let o=r.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=oa(o,n);if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},sa=({state:e})=>ia({state:e},{offset:-1})!==null,fp=({state:e},t)=>{let{offset:n=-1}=t;if(n>=0)throw new Error("rollbackByOffset requires a negative offset");let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let o=st(r,{compatibilityAnchor:!r.rollback}),i=oa(o,n);return i<0||i>=o.timeline.length?e:Us(e,i)},pp=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=st(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===n&&a.lineId===r);if(l===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return l===i.currentIndex?e:Us(e,l)},aa=e=>{let t=Md(e);return Go(t,{selectPendingEffects:Bd,selectSkipMode:Bs,selectAutoMode:zd,selectIsChoiceVisible:Ws,selectIsFormVisible:Hd,selectActiveInteraction:xe,selectActiveForm:Ft,selectDialogueUIHidden:zs,selectDialogueHistory:qs,selectConfirmDialog:qd,selectIsLineAccountViewed:Qr,selectIsResourceAccountViewed:Gd,selectNextLineConfig:Kd,selectSystemState:Jd,selectAchievements:Xd,selectAchievement:Qd,selectSaveSlotMap:Ys,selectSaveSlots:sf,selectSaveSlot:Zd,selectRuntime:Zr,selectRuntimeValue:ef,selectAllVariables:Cn,selectCurrentPointer:Ee,selectSection:ue,selectCurrentLine:Sn,selectPresentationState:Gs,selectAutoForwardTimerDelay:On,selectPresentationChanges:nf,selectSectionLineChanges:of,selectSaveSlotPage:eo,selectCurrentPageSlots:af,selectRenderState:lf,selectOverlayStack:Ud,selectLineIdByOffset:ia,selectCanRollback:sa,selectRollbackCursor:Ld,startAutoMode:Js,stopAutoMode:Mt,toggleAutoMode:yf,startSkipMode:Xs,stopSkipMode:qe,toggleSkipMode:bf,showDialogueUI:kn,hideDialogueUI:Qs,toggleDialogueUI:If,setDialogueTextSpeed:Af,setAutoForwardDelay:wf,setAutoForwardSpeed:Ef,setSkipUnseenText:xf,setSkipTransitionsAndAnimations:vf,setSoundVolume:Cf,setMusicVolume:Sf,setMuteAll:Of,setSaveLoadPagination:Rf,incrementSaveLoadPagination:_f,decrementSaveLoadPagination:kf,setMenuPage:$f,setMenuEntryPoint:Lf,showConfirmDialog:uf,hideConfirmDialog:df,resetStoryAtSection:Vf,clearPendingEffects:Tf,appendPendingEffect:Nf,completeAchievement:Df,setAchievementProgress:Pf,beginRollbackActionBatch:Pd,endRollbackActionBatch:Vd,markRollbackCheckpointTransient:Td,markSavedRollbackCheckpointTransient:Nd,addViewedLine:Ff,addViewedResource:Mf,setNextLineConfig:na,saveSlot:Uf,loadSlot:Bf,updateProjectData:zf,sectionTransition:Yf,jumpToLine:qf,nextLine:Hf,markLineCompleted:Wf,rollbackToLine:pp,rollbackByOffset:fp,pushOverlay:ff,popOverlay:pf,replaceLastOverlay:hf,clearOverlays:mf,updateFormField:Qf,submitForm:Zf,cancelForm:ep,updateVariable:tp,nextLineFromSystem:Gf},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var hp="route-engine",mp="projectPersistence";var la=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),te=e=>Object.prototype.toString.call(e)==="[object Object]",ca="variables.",gp=(e={})=>{let t=te(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!te(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lineId=="string"?{lineId:n.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!te(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},yp=(e={})=>{let t=te(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!te(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lastLineId=="string"?{lastLineId:n.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!te(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},bp=(e,t)=>{let n=yp(e),r=gp(t),o=n.sections.map(s=>({...s})),i=n.resources.map(s=>({...s}));return r.sections.forEach(s=>{let l=o.find(a=>a.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}}),r.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},ua=(e={})=>{let t=te(e)?e:{};return{saveSlots:te(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:te(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:te(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:te(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:te(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Ip=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,n)=>{if(!te(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${n}] entry.`);let r=t.path?.startsWith(ca)?t.path.slice(ca.length):null;if(r!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(r.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${n}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:r}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${n}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${n}].`)})},Ap=(e,t)=>{let n={};return Ip(t).forEach(r=>{if(r.path==="viewedRegistry"){n.accountViewedRegistry=bp(n.accountViewedRegistry??e.accountViewedRegistry,r.value);return}let o=r.scope==="device"?"globalDeviceVariables":"globalAccountVariables";n[o]={...e[o],...n[o],[r.variableId]:r.value}}),n},ro=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},wp=e=>{let t=ro(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Ep=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},xp=({indexedDB:e,databaseName:t,objectStoreName:n})=>new Promise((r,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(n)||s.createObjectStore(n,{keyPath:"namespace"})},i.onsuccess=()=>{r(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),vp=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let a=r.transaction(t,"readonly").objectStore(t).get(n);a.onsuccess=()=>{o(a.result??null)},a.onerror=()=>{i(a.error??new Error(`Failed to read persisted namespace "${n}" from IndexedDB.`))}})},Bt=async({databasePromise:e,objectStoreName:t,namespace:n,patch:r})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),a=l.objectStore(t),c=a.get(n),u=!1,d=p=>{u||(u=!0,s(p))},f=()=>{u||(u=!0,i())};c.onerror=()=>{d(c.error??new Error(`Failed to read persisted namespace "${n}" before updating IndexedDB.`))},c.onsuccess=()=>{let p=ua(c.result),h=typeof r=="function"?r(p):r,m={namespace:n,version:1,...la(),...p,...h},y=a.put(m);y.onerror=()=>{d(y.error??new Error(`Failed to persist namespace "${n}" to IndexedDB.`))}},l.oncomplete=()=>{f()},l.onerror=()=>{d(l.error??new Error(`IndexedDB transaction failed while updating namespace "${n}".`))},l.onabort=()=>{d(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${n}".`))}})},Cp=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let s=r.transaction(t,"readwrite"),a=s.objectStore(t).delete(n),c=!1,u=f=>{c||(c=!0,i(f))},d=()=>{c||(c=!0,o())};a.onerror=()=>{u(a.error??new Error(`Failed to clear persisted namespace "${n}" from IndexedDB.`))},s.oncomplete=()=>{d()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${n}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${n}".`))}})},oo=(e={})=>{let{indexedDB:t,databaseName:n=hp,objectStoreName:r=mp,namespace:o}=e,i=Ep(t),s=wp(o),l=xp({indexedDB:i,databaseName:n,objectStoreName:r});return{namespace:s,load:async()=>{let a=await vp({databasePromise:l,objectStoreName:r,namespace:s});return{...la(),...ua(a)}},clear:async()=>Cp({databasePromise:l,objectStoreName:r,namespace:s}),saveSlots:async a=>Bt({databasePromise:l,objectStoreName:r,namespace:s,patch:{saveSlots:te(a)?a:{}}}),saveGlobalDeviceVariables:async a=>Bt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:te(a)?a:{}}}),saveGlobalAccountVariables:async a=>Bt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalAccountVariables:te(a)?a:{}}}),saveGlobalRuntime:async a=>Bt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalRuntime:te(a)?a:{}}}),applyScopedDataUpdates:async a=>Bt({databasePromise:l,objectStoreName:r,namespace:s,patch:c=>Ap(c,a)})}},Sp=oo;var Op=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Rp=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),da="conditional",ao=Symbol("conditionalAutoContinue"),_p=new Set(["sectionTransition","resetStoryAtSection"]),kp=new Set(["nextLine","nextLineFromSystem","resetStoryAtSection","sectionTransition"]),$p=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),io="form",Lp=new Set(["submitForm","cancelForm"]),zt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ln=e=>e?.type===ao,so=(e,t)=>e?.sectionId===t?.sectionId&&e?.lineId===t?.lineId;function co(e){let t,n=0,r=null,o=0,i=!1,s=0,l=[],a=null,c=new Map,u=new Map,d=new Map,{handlePendingEffects:f}=e,p=(b=new Map,A=Date.now())=>new Map(Array.from(b.entries()).filter(([,v])=>A<v.expiresAt).map(([v,O])=>[v,{animation:structuredClone(O.animation),startedAt:O.startedAt,expiresAt:O.expiresAt}])),h=(b=new Map)=>Array.from(b.values()).map(A=>structuredClone(A.animation)),m=(b=Date.now())=>{c=new Map(Array.from(c.entries()).filter(([,A])=>b<A.expiresAt))},y=()=>{if(!(o>0||i)){i=!0;try{for(;t.selectPendingEffects().length>0;){let b=[...t.selectPendingEffects()];t.clearPendingEffects();try{f(b)}catch(A){throw t.clearPendingEffects(),b.forEach(v=>{t.appendPendingEffect(v)}),A}}}finally{i=!1}}},I=b=>{o+=1;let A=!1;try{let v=b();return A=!0,v}finally{o-=1,A&&y()}},w=({initialState:b,namespace:A})=>{t=aa(b),n=0,r=ro(A),o=0,i=!1,s=0,l=[],a=null,c=new Map,u=new Map,d=new Map,t.appendPendingEffect({name:"handleLineActions"}),y()},E=()=>r,R=()=>t.selectPresentationState(),j=()=>t.selectPresentationChanges(),F=b=>t.selectSectionLineChanges(b),x=(b={})=>{n+=1;let A=Date.now();m(A);let v=u.size>0,O=p(c,A),$=v?p(u,A):new Map,G={...t.selectRenderState({activePersistentAnimations:h(O),restoredPersistentAnimations:h($)}),id:`render-${n}`};return d.set(G.id,{builtAt:A,persistentAnimationSessions:new Map([...$.entries(),...O.entries()]),usedRestoredPersistentAnimationSessions:v}),G},z=(b={})=>x(b),q=(b={})=>x(b),X=b=>{let A=typeof b?.id=="string"&&b.id.length>0?b.id:null,v=A?d.get(A):null;A&&d.delete(A);let O=new Map;Ti(b?.animations).forEach($=>{let B=mn($);if(!B)return;let G=v?.persistentAnimationSessions?.get(B)??c.get(B),he=Math.max(0,Di($)),ct=G?.startedAt??v?.builtAt??Date.now();O.set(B,{animation:structuredClone($),startedAt:ct,expiresAt:ct+he})}),c=O,v?.usedRestoredPersistentAnimationSessions&&(u=new Map)},U=()=>t.selectSystemState(),Y=()=>t.selectAchievements(),K=b=>t.selectAchievement(b),Q=()=>t.selectSaveSlotMap(),Re=b=>t.selectSaveSlot(b),ne=b=>t.selectSaveSlotPage(b),re=()=>t.selectSkipMode(),de=()=>t.selectAutoMode(),fe=()=>t.selectRuntime(),Z=()=>t.selectIsChoiceVisible(),oe=()=>t.selectIsFormVisible(),pe=()=>t.selectActiveInteraction(),S=()=>t.selectPendingEffects().some(b=>b?.name==="handleLineActions"||b?.name==="render"),_=(b,A,v={})=>!zt(A)||b!=="nextLine"?A:v.bypassChoice===!0?{...A,bypassChoice:!0}:v.interactionSource===io?{...A,_interactionSource:io}:A,M=(b={})=>({type:ao,payload:_("nextLine",{_conditionalContinuation:!0},b)}),ie=(b,A)=>Ln(b)?{type:ao,payload:{...b.payload,...A.payload}}:A,se=b=>{b.savedCheckpointOccurrences.forEach(A=>{t.markSavedRollbackCheckpointTransient(A)}),b.savedCheckpointOccurrences=[]},H=(b,A)=>{let v=a;return a=null,!v||!so(v.pointer,b)||v.checkpointIndex!==A?.checkpointIndex||v.checkpointIdentity!==A?.checkpoint?[]:v.savedCheckpointOccurrences},De=b=>{b.markCurrentCheckpointTransient&&(t.markRollbackCheckpointTransient({checkpointIndex:b.rollbackCursor?.checkpointIndex,checkpointIdentity:b.rollbackCursor?.checkpoint,sectionId:b.pointer?.sectionId,lineId:b.pointer?.lineId}),se(b))},at=(b,A,v)=>kp.has(b)?b==="resetStoryAtSection"?v?.checkpoint!==A?.checkpoint:v?.checkpoint!==A?.checkpoint&&v?.checkpointIndex>A?.checkpointIndex:!1,ha=b=>{let A=l.at(-1);if(!A?.markCurrentCheckpointTransient)return;let v=t.selectSaveSlot({slotId:b?.slotId});v&&A.savedCheckpointOccurrences.push({slotId:b.slotId,saveSlotIdentity:v,checkpointIndex:A.rollbackCursor?.checkpointIndex,sectionId:A.pointer?.sectionId,lineId:A.pointer?.lineId})},ma=(b,A,v)=>{let O=l.at(-1);if(!O)return;let $=t.selectCurrentPointer()?.pointer,B=at(b,A,v);if(so(O.pointer,$)){let G=v?.checkpoint!==A?.checkpoint||v?.checkpointIndex!==A?.checkpointIndex;(B||G&&$p.has(b))&&(De(O),O.pointer=$,O.rollbackCursor=v,O.markCurrentCheckpointTransient=B,O.savedCheckpointOccurrences=[]);return}De(O),O.pointer=$,O.rollbackCursor=t.selectRollbackCursor?.()??null,O.markCurrentCheckpointTransient=B,O.savedCheckpointOccurrences=[]},qt=(b,A)=>{if(!t[b])return;b==="updateProjectData"&&ga(A),_p.has(b)&&(s+=1),Op.has(b)&&(Rp.has(b)?u=p(c):u=new Map,c=new Map);let v=t.selectRollbackCursor?.()??null,O=t[b](A),$=t.selectRollbackCursor?.()??null;return b==="saveSlot"&&ha(A),ma(b,v,$),y(),O},ga=b=>{if(!Object.prototype.hasOwnProperty.call(b??{},"projectData"))throw new Error("updateProjectData requires projectData");Xe(b?.projectData?.resources?.variables??{})},ya=(b,A,v)=>{let O=t.selectCurrentPointer()?.pointer;A!==O||v!==s||(t.appendPendingEffect({name:"clearAutoNextTimer"}),t.appendPendingEffect({name:"clearNextLineConfigTimer"}),qt("nextLineFromSystem",b.payload))},ba=()=>({renderSequence:n,conditionalRoutingSequence:s,rollbackNavigationContexts:l.slice(),pendingRollbackLineEntrySaveHandoff:a,persistentAnimationSessions:new Map(c),restoredPersistentAnimationSessions:new Map(u),renderPersistentAnimationMetadata:new Map(d)}),Ia=b=>{n=b.renderSequence,s=b.conditionalRoutingSequence,l=b.rollbackNavigationContexts.slice(),a=b.pendingRollbackLineEntrySaveHandoff,c=new Map(b.persistentAnimationSessions),u=new Map(b.restoredPersistentAnimationSessions),d=new Map(b.renderPersistentAnimationMetadata)},uo=(b,A={})=>I(()=>{let v=ba();try{return t[ur](()=>{let O,$=t.selectCurrentPointer()?.pointer??null,B=t.selectRollbackCursor?.()??null,G=s,he={pointer:$,rollbackCursor:B,markCurrentCheckpointTransient:A.rollbackSource==="line",savedCheckpointOccurrences:A.savedCheckpointOccurrences?.slice()??[]};l.push(he);try{t.beginRollbackActionBatch({source:A.rollbackSource});try{O=b()}finally{t.endRollbackActionBatch({})}Ln(O)&&ya(O,$,G)}finally{l.pop(),(!so($,he.pointer)||B?.checkpoint!==he.rollbackCursor?.checkpoint)&&he.markCurrentCheckpointTransient&&he.savedCheckpointOccurrences.length>0&&(a={pointer:he.pointer,checkpointIndex:he.rollbackCursor?.checkpointIndex,checkpointIdentity:he.rollbackCursor?.checkpoint,savedCheckpointOccurrences:he.savedCheckpointOccurrences})}})}catch(O){throw Ia(v),O}}),fo=(b,A,v,O={})=>{if(b===da)return uo(()=>{let $=Nn(v),B=mr({[b]:A},$);return po(B[b],v,O)},O);qt(b,A)},Aa=(b,A)=>{fo(b,A)},Nn=b=>{if(!b)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(b,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:A,...v}=b,O=t.selectAllVariables?t.selectAllVariables():void 0;return{...v,_event:A,variables:O,runtime:t.selectRuntime?t.selectRuntime():{}}},wa=b=>{if(!zt(b))throw new Error("conditional action payload must be an object");if(!Array.isArray(b.branches))throw new Error("conditional action requires branches array");if(b.branches.length===0)throw new Error("conditional action requires at least one branch")},Ea=(b,A,v)=>{if(!zt(b))throw new Error(`conditional branch at index ${A} must be an object`);if(!zt(b.actions))throw new Error(`conditional branch at index ${A} requires actions object`);if(!Object.prototype.hasOwnProperty.call(b,"when")&&A!==v-1)throw new Error("conditional else branch must be the last branch")},po=(b,A,v)=>{wa(b);let O=M(v);for(let $=0;$<b.branches.length;$+=1){let B=b.branches[$];Ea(B,$,b.branches.length);let G=Nn(A);if(Object.prototype.hasOwnProperty.call(B,"when")&&!Ot(B.when,G))continue;let ct=Dn(B.actions,A,v);return Ln(ct)?ie(O,ct):O}return O},xa=(b,A)=>({...b??{},_form:A}),va=(b,A,v,O)=>{let $=qt(b,A),B=$?.submitted===!0&&$.valid===!0,G=$?.cancelled===!0;if(!(!B&&!G)&&zt(A.actions))return Dn(A.actions,xa(v,$.form),{...O,interactionSource:io})},Ca=(b,A,v,O)=>{let $=Nn(v),G=mr({[b]:A},$)[b];if(b===da)return po(G,v,O);let he=_(b,G,O);if(Lp.has(b))return va(b,he,v,O);qt(b,he)},Dn=(b,A,v)=>{let O;return Object.entries(b).forEach(([$,B])=>{let G=Ca($,B,A,v);Ln(G)&&(O=ie(O,G))}),O},ho=(b,A,v={})=>uo(()=>Dn(b,A,v),v),Sa=b=>{let A=t.selectCurrentPointer()?.pointer;if(b!==A||t.selectActiveInteraction())return;let v=t.selectNextLineConfig();v?.auto?.enabled&&v.auto.trigger==="fromStart"&&t.appendPendingEffect({name:"nextLineConfigTimer",payload:{delay:v.auto.delay}})};return{init:w,handleAction:fo,handleInternalAction:Aa,handleActions:ho,selectRenderState:z,prepareRenderState:q,commitRenderState:X,selectPresentationState:R,selectPresentationChanges:j,selectSectionLineChanges:F,selectSystemState:U,selectAchievements:Y,selectAchievement:K,selectSaveSlotMap:Q,selectSaveSlot:Re,selectSaveSlotPage:ne,selectSaveSlots:Q,selectRuntime:fe,selectIsChoiceVisible:Z,selectIsFormVisible:oe,selectActiveInteraction:pe,selectHasPendingRenderWork:S,handleLineActions:()=>I(()=>{let b=t.selectCurrentPointer()?.pointer,A=t.selectRollbackCursor?.()??null,v=a,O=H(b,A),$=t.selectCurrentLine(),B=!1;if($?.actions){try{ho($.actions,void 0,{rollbackSource:"line",savedCheckpointOccurrences:O})}catch(G){throw a=v,G}B=!0}return Sa(b),B}),getNamespace:E}}var lo=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},Tp=80,pa=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{if(e.selectHasPendingRenderWork?.())return;let o=e.prepareRenderState?.(r)??e.selectRenderState(r);n?.(o),t.render(o),e.commitRenderState?.(o)},Np=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&pa({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},Dp=({engine:e,ticker:t,autoTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(t.remove(i),n.setCallback(null),n.setElapsed(0),Tn(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Pp=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Vp=({engine:e,ticker:t,skipTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r?.delay??Tp;n.getElapsed()>=l&&(n.setElapsed(0),Tn(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},jp=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Fp=({engine:e,ticker:t,nextLineConfigTimerState:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(n.setElapsed(0),Tn(e,"nextLineFromSystem",{}),t.remove(i),n.getCallback()===i&&n.setCallback(null))};n.setCallback(i),t.add(i)},Mp=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Up=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveSlots(t?.saveSlots))},Bp=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalDeviceVariables(t?.globalDeviceVariables))},zp=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalAccountVariables(t?.globalAccountVariables))},qp=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalRuntime(t?.globalRuntime))},Hp=({enqueuePersistenceWrite:e},t)=>{e(n=>{if(typeof n.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return n.applyScopedDataUpdates(t?.updates)})},fa={render:pa,saveSlots:Up,saveGlobalDeviceVariables:Bp,saveGlobalAccountVariables:zp,saveGlobalRuntime:qp,applyScopedDataUpdates:Hp,handleLineActions:Np,startAutoNextTimer:Dp,clearAutoNextTimer:Pp,startSkipNextTimer:Vp,clearSkipNextTimer:jp,nextLineConfigTimer:Fp,clearNextLineConfigTimer:Mp},Wp=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Tn=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},Yp=(e=[])=>{let t=new Set,n=[];for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!Wp.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},Gp=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let a=lo(),c=lo(),u=lo(),d=s??null,f=Promise.resolve(),p=null,h=null,m=!1,y=0,I=S=>{if(o){o(S);return}console.error("RouteEngine persistence write failed.",S)},w=()=>{if(d)return d;let S=e();return d=oo({indexedDB:i,namespace:l??S?.getNamespace?.()}),d},E=S=>{f=f.catch(()=>{}).then(()=>{let _=w();return S(_)}).catch(_=>{I(_)})},R=S=>{let _=typeof S?.id=="string"&&S.id.length>0?S.id:null;y+=1,p=_,m=!1},j=()=>y,F=(S={})=>{if(S?.aborted===!0)return!1;let _=typeof S?.id=="string"&&S.id.length>0?S.id:null;return _?_!==p||_===h?!1:(h=_,!0):p!==null||m?!1:(m=!0,!0)},x=(S,_={})=>{if(S!=="renderComplete"||!F(_))return!1;let M=e();return Tn(M,"markLineCompleted",{}),!0},z=new Set(["updateFormField","submitForm","cancelForm"]),q=new Set(["updateVariable"]),X=S=>typeof S?.selectActiveInteraction=="function"?S.selectActiveInteraction():typeof S?.selectIsChoiceVisible=="function"&&S.selectIsChoiceVisible()?{source:"choice"}:null,U=S=>S?._formKey??S?.formKey,Y=(S,_)=>U(S)===_?.formKey,K=(S,_)=>!S||typeof S!="object"||Array.isArray(S)?!1:S._interactionSource===_?.source,Q=(S,_)=>K(S,_)?_.source==="form"?Y(S,_):!0:!1,Re=(S,_)=>!S||typeof S!="object"||Array.isArray(S)||_?.source!=="form"?!1:Y(S,_),ne=(S={})=>Object.keys(S).some(_=>z.has(_)),re=(S={},_)=>Object.entries(S).some(([M,ie])=>z.has(M)&&Re(ie,_)),de=(S={})=>Object.keys(S).length>0&&Object.keys(S).every(_=>q.has(_)),fe=(S={},_)=>{let M=S?.actions;return _?.source==="form"?!M||typeof M!="object"||Array.isArray(M)?!1:re(M,_)?!0:ne(M)?!1:de(M):Q(S,_)?!0:!M||typeof M!="object"||Array.isArray(M)?!1:Object.values(M).some(ie=>Q(ie,_))},Z=(S,_={})=>{if(!_?.actions)return!1;let M=X(S);return!M||M.source==="choice"?!1:!fe(_,M)},oe=({preprocessPayload:S,onEvent:_}={})=>async(M,ie={})=>{let se=e();if(Z(se,ie))return _?.(M,ie);let H=await S?.(M,ie)??ie;if(Z(se,H))return _?.(M,H);if(x(M,H),H?.actions){let De=H?._event?{_event:H._event}:H?.event?{_event:H.event}:void 0,at;H?.bypassChoice===!0?at={bypassChoice:!0}:H?._interactionSource&&(at={interactionSource:H._interactionSource}),at?se.handleActions(H.actions,De,at):se.handleActions(H.actions,De)}return _?.(M,H)},pe=S=>{let _=e(),M=Yp(S),ie=M.some(H=>H.name==="handleLineActions");M.forEach(H=>{if(!fa[H.name]&&!r)throw new Error(`Unhandled pending effect "${H.name}".`)});let se={engine:_,routeGraphics:t,ticker:n,autoTimer:a,skipTimer:c,nextLineConfigTimerState:u,trackRenderDispatch:R,getRenderDispatchCount:j,enqueuePersistenceWrite:E};for(let H of M){if(ie&&H.name==="render")continue;let De=fa[H.name];if(De){De(se,H.payload);continue}r(H,se)}};return pe.handleRouteGraphicsEvent=x,pe.createRouteGraphicsEventHandler=oe,pe},Kp=Gp;var Jp=(e,t={})=>{let{resources:n={}}=t;return Mr(e,n)};var Rm=co;export{Ir as DEFAULT_VISUAL_LAYER,pt as RENDER_LAYER,$e as VISUAL_LAYER,Kp as createEffectsHandler,Sp as createIndexedDbPersistence,Rm as default,fr as formatDate,Bc as resolveComputedVariables,Jp as resolveLayoutReferences};
1
+ var Vc=Object.defineProperty;var jc=(e,n)=>{for(var t in n)Vc(e,t,{get:n[t],enumerable:!0})};var oi=Symbol.for("immer-nothing"),Zo=Symbol.for("immer-draftable"),ye=Symbol.for("immer-state");function Ee(e,...n){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var bn=Object.getPrototypeOf;function ie(e){return!!e&&!!e[ye]}function nn(e){return e?ii(e)||Array.isArray(e)||!!e[Zo]||!!e.constructor?.[Zo]||ht(e)||yt(e):!1}var Fc=Object.prototype.constructor.toString();function ii(e){if(!e||typeof e!="object")return!1;let n=bn(e);if(n===null)return!0;let t=Object.hasOwnProperty.call(n,"constructor")&&n.constructor;return t===Object?!0:typeof t=="function"&&Function.toString.call(t)===Fc}function ur(e){return ie(e)||Ee(15,e),e[ye].base_}function ft(e,n){gt(e)===0?Reflect.ownKeys(e).forEach(t=>{n(t,e[t],e)}):e.forEach((t,r)=>n(r,t,e))}function gt(e){let n=e[ye];return n?n.type_:Array.isArray(e)?1:ht(e)?2:yt(e)?3:0}function or(e,n){return gt(e)===2?e.has(n):Object.prototype.hasOwnProperty.call(e,n)}function si(e,n,t){let r=gt(e);r===2?e.set(n,t):r===3?e.add(t):e[n]=t}function Uc(e,n){return e===n?e!==0||1/e===1/n:e!==e&&n!==n}function ht(e){return e instanceof Map}function yt(e){return e instanceof Set}function en(e){return e.copy_||e.base_}function ir(e,n){if(ht(e))return new Map(e);if(yt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let t=ii(e);if(n===!0||n==="class_only"&&!t){let r=Object.getOwnPropertyDescriptors(e);delete r[ye];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let s=o[i],l=r[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(r[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(bn(e),r)}else{let r=bn(e);if(r!==null&&t)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function dr(e,n=!1){return bt(e)||ie(e)||!nn(e)||(gt(e)>1&&(e.set=e.add=e.clear=e.delete=Bc),Object.freeze(e),n&&Object.entries(e).forEach(([t,r])=>dr(r,!0))),e}function Bc(){Ee(2)}function bt(e){return Object.isFrozen(e)}var Gc={};function tn(e){let n=Gc[e];return n||Ee(0,e),n}var Ln;function ai(){return Ln}function zc(e,n){return{drafts_:[],parent_:e,immer_:n,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function ei(e,n){n&&(tn("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=n)}function sr(e){ar(e),e.drafts_.forEach(qc),e.drafts_=null}function ar(e){e===Ln&&(Ln=e.parent_)}function ni(e){return Ln=zc(Ln,e)}function qc(e){let n=e[ye];n.type_===0||n.type_===1?n.revoke_():n.revoked_=!0}function ti(e,n){n.unfinalizedDrafts_=n.drafts_.length;let t=n.drafts_[0];return e!==void 0&&e!==t?(t[ye].modified_&&(sr(n),Ee(4)),nn(e)&&(e=pt(n,e),n.parent_||mt(n,e)),n.patches_&&tn("Patches").generateReplacementPatches_(t[ye].base_,e,n.patches_,n.inversePatches_)):e=pt(n,t,[]),sr(n),n.patches_&&n.patchListener_(n.patches_,n.inversePatches_),e!==oi?e:void 0}function pt(e,n,t){if(bt(n))return n;let r=n[ye];if(!r)return ft(n,(o,i)=>ri(e,r,n,o,i,t)),n;if(r.scope_!==e)return n;if(!r.modified_)return mt(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let o=r.copy_,i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),ft(i,(l,a)=>ri(e,r,o,l,a,t,s)),mt(e,o,!1),t&&e.patches_&&tn("Patches").generatePatches_(r,t,e.patches_,e.inversePatches_)}return r.copy_}function ri(e,n,t,r,o,i,s){if(ie(o)){let l=i&&n&&n.type_!==3&&!or(n.assigned_,r)?i.concat(r):void 0,a=pt(e,o,l);if(si(t,r,a),ie(a))e.canAutoFreeze_=!1;else return}else s&&t.add(o);if(nn(o)&&!bt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;pt(e,o),(!n||!n.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(t,r)&&mt(e,o)}}function mt(e,n,t=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&dr(n,t)}function Yc(e,n){let t=Array.isArray(e),r={type_:t?1:0,scope_:n?n.scope_:ai(),modified_:!1,finalized_:!1,assigned_:{},parent_:n,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=fr;t&&(o=[r],i=Pn);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var fr={get(e,n){if(n===ye)return e;let t=en(e);if(!or(t,n))return Hc(e,t,n);let r=t[n];return e.finalized_||!nn(r)?r:r===tr(e.base_,n)?(rr(e),e.copy_[n]=lr(r,e)):r},has(e,n){return n in en(e)},ownKeys(e){return Reflect.ownKeys(en(e))},set(e,n,t){let r=ci(en(e),n);if(r?.set)return r.set.call(e.draft_,t),!0;if(!e.modified_){let o=tr(en(e),n),i=o?.[ye];if(i&&i.base_===t)return e.copy_[n]=t,e.assigned_[n]=!1,!0;if(Uc(t,o)&&(t!==void 0||or(e.base_,n)))return!0;rr(e),cr(e)}return e.copy_[n]===t&&(t!==void 0||n in e.copy_)||Number.isNaN(t)&&Number.isNaN(e.copy_[n])||(e.copy_[n]=t,e.assigned_[n]=!0),!0},deleteProperty(e,n){return tr(e.base_,n)!==void 0||n in e.base_?(e.assigned_[n]=!1,rr(e),cr(e)):delete e.assigned_[n],e.copy_&&delete e.copy_[n],!0},getOwnPropertyDescriptor(e,n){let t=en(e),r=Reflect.getOwnPropertyDescriptor(t,n);return r&&{writable:!0,configurable:e.type_!==1||n!=="length",enumerable:r.enumerable,value:t[n]}},defineProperty(){Ee(11)},getPrototypeOf(e){return bn(e.base_)},setPrototypeOf(){Ee(12)}},Pn={};ft(fr,(e,n)=>{Pn[e]=function(){return arguments[0]=arguments[0][0],n.apply(this,arguments)}});Pn.deleteProperty=function(e,n){return Pn.set.call(this,e,n,void 0)};Pn.set=function(e,n,t){return fr.set.call(this,e[0],n,t,e[0])};function tr(e,n){let t=e[ye];return(t?en(t):e)[n]}function Hc(e,n,t){let r=ci(n,t);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function ci(e,n){if(!(n in e))return;let t=bn(e);for(;t;){let r=Object.getOwnPropertyDescriptor(t,n);if(r)return r;t=bn(t)}}function cr(e){e.modified_||(e.modified_=!0,e.parent_&&cr(e.parent_))}function rr(e){e.copy_||(e.copy_=ir(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Wc=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(n,t,r)=>{if(typeof n=="function"&&typeof t!="function"){let i=t;t=n;let s=this;return function(a=i,...c){return s.produce(a,u=>t.call(this,u,...c))}}typeof t!="function"&&Ee(6),r!==void 0&&typeof r!="function"&&Ee(7);let o;if(nn(n)){let i=ni(this),s=lr(n,void 0),l=!0;try{o=t(s),l=!1}finally{l?sr(i):ar(i)}return ei(i,r),ti(o,i)}else if(!n||typeof n!="object"){if(o=t(n),o===void 0&&(o=n),o===oi&&(o=void 0),this.autoFreeze_&&dr(o,!0),r){let i=[],s=[];tn("Patches").generateReplacementPatches_(n,o,i,s),r(i,s)}return o}else Ee(1,n)},this.produceWithPatches=(n,t)=>{if(typeof n=="function")return(s,...l)=>this.produceWithPatches(s,a=>n(a,...l));let r,o;return[this.produce(n,t,(s,l)=>{r=s,o=l}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){nn(e)||Ee(8),ie(e)&&(e=Ue(e));let n=ni(this),t=lr(e,void 0);return t[ye].isManual_=!0,ar(n),t}finishDraft(e,n){let t=e&&e[ye];(!t||!t.isManual_)&&Ee(9);let{scope_:r}=t;return ei(r,n),ti(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,n){let t;for(t=n.length-1;t>=0;t--){let o=n[t];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}t>-1&&(n=n.slice(t+1));let r=tn("Patches").applyPatches_;return ie(e)?r(e,n):this.produce(e,o=>r(o,n))}};function lr(e,n){let t=ht(e)?tn("MapSet").proxyMap_(e,n):yt(e)?tn("MapSet").proxySet_(e,n):Yc(e,n);return(n?n.scope_:ai()).drafts_.push(t),t}function Ue(e){return ie(e)||Ee(10,e),li(e)}function li(e){if(!nn(e)||bt(e))return e;let n=e[ye],t;if(n){if(!n.modified_)return n.base_;n.finalized_=!0,t=ir(e,n.scope_.immer_.useStrictShallowCopy_)}else t=ir(e,!0);return ft(t,(r,o)=>{si(t,r,li(o))}),n&&(n.finalized_=!1),t}var we=new Wc,pr=we.produce,bh=we.produceWithPatches.bind(we),Ih=we.setAutoFreeze.bind(we),wh=we.setUseStrictShallowCopy.bind(we),Ah=we.applyPatches.bind(we),Eh=we.createDraft.bind(we),xh=we.finishDraft.bind(we);var y={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},M={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},In={NOT:0};var R=class extends Error{constructor(n){super(`Parse Error: ${n}`),this.name="JemplParseError"}},pe=class extends Error{constructor(n){super(`Render Error: ${n}`),this.name="JemplRenderError"}};var mr=e=>{if(!e||e.trim()==="")throw new R("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let t=e.includes("===")?"==":"!=";throw new R(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${t}'? (got: '${e}')`)}let n=["<",">","<=",">=","==","!="];for(let t of n)if(e.trim().endsWith(t))throw new R(`Incomplete comparison expression - missing right operand (got: '${e}')`)},ui=e=>{if(e.trim().endsWith(" in"))throw new R(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new R(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[n,t]=e.split(" in ");if(!t||t.trim()==="")throw new R(`Missing iterable expression after 'in' (got: '$for ${e}')`);let r=n.includes(",")?n.split(",").map(o=>o.trim()):[n.trim()];for(let o of r){if(!o)throw new R(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new R(`Invalid loop syntax (got: '$for ${e}')`)}};var di=(e,n,t=!1)=>{if(n===null)return new pe(`Cannot iterate over null value at '$for ${e}'`);if(n===void 0)return new pe(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof n;return t?new pe(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new pe(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},fi=(e,n)=>{let t=n&&Object.keys(n).length>0?Object.keys(n).join(", "):"no custom functions provided";return new pe(`Unknown function '${e}' (${t})`)};var Kc=(e,n,t={})=>{let r={},o={};t&&typeof t=="object"&&(t.functions!==void 0||t.partials!==void 0?(r=t.functions||{},o=t.partials||{}):typeof t=="object"&&(r=t));let s=V(e,{functions:r,partials:o},n,{});return s===void 0?{}:s},V=(e,n,t,r)=>{let o=n.functions||n;if(e.var&&!e.type)return ee(e.var,t,r);if(e.type===y.LITERAL)return e.value;if(e.type===y.VARIABLE)return ee(e.path,t,r);if(e.type===y.INTERPOLATION)return Xc(e.parts,n,t,r);switch(e.type){case y.FUNCTION:return mi(e,n,t,r);case y.BINARY:return gi(e,n,t,r);case y.UNARY:return hi(e,n,t,r);case y.CONDITIONAL:return Zc(e,n,t,r);case y.LOOP:return ol(e,n,t,r);case y.OBJECT:return sl(e,n,t,r);case y.ARRAY:return al(e,n,t,r);case y.PARTIAL:return cl(e,n,t,r);case y.PATH_REFERENCE:return ll(e,n,t,r);default:throw new Error(`Unknown node type: ${e.type}`)}},pi=new Map,Jc=e=>{let n=[],t="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")t&&(n.push({type:"property",value:t}),t=""),r=!0;else if(i==="]"){if(r&&t){let s=t.trim();if(/^\d+$/.test(s))n.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let l=s.slice(1,-1);n.push({type:"property",value:l})}else n.push({type:"property",value:s});t=""}r=!1}else t+=i}return t&&n.push({type:"property",value:t}),n},ee=(e,n,t)=>{if(!e)return;if(e in t)return t[e];let r=pi.get(e);if(!r){let i=[],s="",l=0;for(let a=0;a<e.length;a++){let c=e[a];c==="["?(l++,s+=c):c==="]"?(l--,s+=c):c==="."&&l===0?s&&(i.push(s),s=""):s+=c}s&&i.push(s),r=[];for(let a of i){let c=Jc(a.trim());r.push(...c)}pi.set(e,r)}let o=n;for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="property"&&s.value in t){o=t[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},Xc=(e,n,t,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=V(i,n,t,r);o.push(s!=null?String(s):"")}return o.join("")},mi=(e,n,t,r)=>{let o=n.functions||n,i=o[e.name];if(!i)throw fi(e.name,o);let s=e.args.map(l=>V(l,n,t,r));return i(...s)},Be=(e,n,t,r)=>{if(e.var&&!e.type)return ee(e.var,t,r);switch(e.type){case y.VARIABLE:return ee(e.path,t,r);case y.LITERAL:return e.value;case y.BINARY:return gi(e,n,t,r);case y.UNARY:return hi(e,n,t,r);case y.FUNCTION:return mi(e,n,t,r);default:return V(e,n,t,r)}},gi=(e,n,t,r)=>{if(e.op===M.AND||e.op===M.OR){let s=Be(e.left,n,t,r),l=Be(e.right,n,t,r);switch(e.op){case M.AND:return s&&l;case M.OR:return s||l}}let o=V(e.left,n,t,r),i=V(e.right,n,t,r);switch(e.op){case M.EQ:return o==i;case M.NEQ:return o!=i;case M.GT:return o>i;case M.LT:return o<i;case M.GTE:return o>=i;case M.LTE:return o<=i;case M.IN:return Array.isArray(i)?i.includes(o):!1;case M.ADD:if(typeof o!="number"||typeof i!="number")throw new pe(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case M.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new pe(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},hi=(e,n,t,r)=>{let o=e.op===In.NOT?Be(e.operand,n,t,r):V(e.operand,n,t,r);if(e.op===In.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Qc=(e,n,t,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===y.VARIABLE)if(ee(o.path,t,r)){let s=e.bodies[0];if(s.type===y.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?V(a.parsedKey,n,t,r):a.key,u=a.value;if(u.type===y.LITERAL)l[c]=u.value;else if(u.type===y.VARIABLE)l[c]=ee(u.path,t,r);else if(u.type===y.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===y.VARIABLE){let p=ee(f.path,t,r);d.push(p!=null?String(p):"")}else{let p=V(f,n,t,r);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=V(u,n,t,r)}return l}}else{let s=e.bodies[1];if(s.type===y.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?V(a.parsedKey,n,t,r):a.key,u=a.value;if(u.type===y.LITERAL)l[c]=u.value;else if(u.type===y.VARIABLE)l[c]=ee(u.path,t,r);else if(u.type===y.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===y.VARIABLE){let p=ee(f.path,t,r);d.push(p!=null?String(p):"")}else{let p=V(f,n,t,r);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=V(u,n,t,r)}return l}}}return null},Zc=(e,n,t,r)=>{let o=Qc(e,n,t,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||Be(s,n,t,r))return V(e.bodies[i],n,t,r)}return yi},el=(e,n)=>{let t=e.body,r=e.itemVar;if(t.type===y.CONDITIONAL&&t.conditions.length===1&&t.conditions[0].type===y.VARIABLE){let o=t.conditions[0].path,i=t.bodies[0];if(o.startsWith(r+".")){let s=o.substring(r.length+1);if(i.type===y.OBJECT&&i.properties.length<=5){for(let a of i.properties)if(a.parsedKey)return null;let l=[];for(let a=0;a<n.length;a++){let c=n[a];if(c[s]){let u={};for(let d of i.properties){let f=d.key,p=d.value;if(p.type===y.LITERAL)u[f]=p.value;else if(p.type===y.VARIABLE){let g=p.path;if(g===r)u[f]=c;else if(g.startsWith(r+".")){let h=g.substring(r.length+1);u[f]=c[h]}else return null}else if(p.type===y.INTERPOLATION){let g=[],h=!0;for(let b of p.parts)if(typeof b=="string")g.push(b);else if(b.type===y.VARIABLE){let I=b.path;if(I===r)g.push(c!=null?String(c):"");else if(I.startsWith(r+".")){let E=I.substring(r.length+1),A=c[E];g.push(A!=null?String(A):"")}else{h=!1;break}}else{h=!1;break}if(!h)return null;u[f]=g.join("")}else return null}l.push(u)}}return l}}}return null},nl=(e,n)=>{let t=e.body,r=e.itemVar,o=el(e,n);if(o!==null)return o;if(t.type===y.OBJECT&&t.properties.length<=5&&!t.whenCondition){for(let l of t.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of t.properties){let a=l.key,c=l.value;if(c.type===y.LITERAL)i.push({key:a,type:"literal",value:c.value});else if(c.type===y.VARIABLE){let u=c.path;if(u===r)i.push({key:a,type:"item"});else if(u.startsWith(r+".")){let d=u.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:a,type:"prop",prop:d});else{s=!1;break}}else{s=!1;break}}else if(c.type===y.INTERPOLATION&&c.parts.length===1){let u=c.parts[0];if(u.type===y.VARIABLE){let d=u.path;if(d===r)i.push({key:a,type:"item_string"});else if(d.startsWith(r+".")){let f=d.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:a,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(n.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 a=0;a<n.length;a++){let c=n[a];l[a]={id:c.id,title:c.title!=null?String(c.title):"",completed:c.completed}}else for(let a=0;a<n.length;a++){let c=n[a],u={};for(let d of i)if(d.type==="literal")u[d.key]=d.value;else if(d.type==="item")u[d.key]=c;else if(d.type==="prop")u[d.key]=c[d.prop];else if(d.type==="item_string")u[d.key]=c!=null?String(c):"";else if(d.type==="prop_string"){let f=c[d.prop];u[d.key]=f!=null?String(f):""}l[a]=u}return l}}return null},tl=(e,n,t,r,o)=>{let i=[],s=e.body;if(s.type===y.OBJECT&&s.fast!==!1){let l=e.itemVar,a=e.indexVar;for(let c=0;c<o.length;c++){let u=o[c],d={},f={...r,[l]:u,...a&&{[a]:c}};f.__paths__||(f.__paths__=r.__paths__||{});let p=e.iterable.path||"";if(r&&r.__paths__&&p){let g=p.split("."),h=g[0];h in r.__paths__&&(p=r.__paths__[h],g.length>1&&(p+="."+g.slice(1).join(".")))}f.__paths__={...f.__paths__,[l]:`${p}[${c}]`,...a&&{[a]:c}};for(let g of s.properties){let h=g.parsedKey?V(g.parsedKey,n,t,f):g.key,b=g.value;if(b.type===y.LITERAL)d[h]=b.value;else if(b.type===y.VARIABLE){let I=b.path;if(I===l)d[h]=u;else if(I===a)d[h]=c;else if(I.startsWith(l+".")){let E=I.substring(l.length+1);!E.includes(".")&&!E.includes("[")?d[h]=u[E]:d[h]=ee(I,t,{...r,[l]:u,...a&&{[a]:c}})}else d[h]=ee(I,t,{...r,[l]:u,...a&&{[a]:c}})}else if(b.type===y.INTERPOLATION){let I=[];for(let E of b.parts)if(typeof E=="string")I.push(E);else if(E.type===y.VARIABLE){let A=E.path,$;if(A===l)$=u;else if(A===a)$=c;else if(A.startsWith(l+".")){let B=A.substring(l.length+1);!B.includes(".")&&!B.includes("[")?$=u[B]:$=ee(A,t,{...r,[l]:u,...a&&{[a]:c}})}else $=ee(A,t,{...r,[l]:u,...a&&{[a]:c}});I.push($!=null?String($):"")}else{let A={...r,[l]:u,...a&&{[a]:c}},$=V(E,n,t,A);I.push($!=null?String($):"")}d[h]=I.join("")}else{let I={...r,[l]:u,...a&&{[a]:c}};d[h]=V(b,n,t,I)}}i.push(d)}return i}return null},rl=(e,n,t)=>{let r=e.body;if(r.type===y.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===y.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===y.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===y.OBJECT&&s.properties.length===2){let l=s.properties[0],a=s.properties[1];if(l.key==="id"&&l.value.type===y.VARIABLE&&l.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===y.CONDITIONAL){let c=[];for(let u=0;u<n.length;u++){let d=n[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),c.push(f)}}return c}}}}return null},ol=(e,n,t,r)=>{let o=V(e.iterable,n,t,r);if(!Array.isArray(o)){let c,u=!1;if(e.iterable.type===y.FUNCTION){u=!0;let f=e.iterable.args.map(p=>p.type===y.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===y.VARIABLE?p.path:p.type===y.FUNCTION?`${p.name}(...)`:"?").join(", ");c=`${e.iterable.name}(${f})`}else c=e.iterable.path||"undefined";let d=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${c}`;throw di(d,o,u)}if(!e.indexVar){let c=rl(e,o,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=nl(e,o);if(c!==null)return c}let i=tl(e,n,t,r,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(r&&r.__paths__&&l){let c=l.split("."),u=c[0];u in r.__paths__&&(l=r.__paths__[u],c.length>1&&(l+="."+c.slice(1).join(".")))}let a=!1;e.body.type===y.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(c=>c.type===y.OBJECT&&c.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let c=0;c<o.length;c++){let u=e.indexVar?{...r,[e.itemVar]:o[c],[e.indexVar]:c}:{...r,[e.itemVar]:o[c]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${c}]`},e.indexVar&&(u.__paths__[e.indexVar]=c);let d=V(e.body,n,t,u);if(Array.isArray(d)&&d.length===1&&!a){let f=d[0];s.push(f===void 0?{}:f)}else s.push(d===void 0?{}:d)}return s},il=(e,n,t,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?V(o.parsedKey,n,t,r):o.key,s=o.value;if(s.type===y.OBJECT&&s.properties.length<=10&&!s.whenCondition){let l={},a={},c=!0;for(let u of s.properties){let d=u.parsedKey?V(u.parsedKey,n,t,r):u.key,f=u.value;if(f.type===y.LITERAL)a[d]=f.value;else if(f.type===y.VARIABLE)a[d]=ee(f.path,t,r);else if(f.type===y.INTERPOLATION){let p=[];for(let g of f.parts)if(typeof g=="string")p.push(g);else if(g.type===y.VARIABLE){let h=ee(g.path,t,r);p.push(h!=null?String(h):"")}else{c=!1;break}if(!c)break;a[d]=p.join("")}else if(f.type===y.OBJECT&&f.properties.length<=5){let p={};for(let g of f.properties){let h=g.key,b=g.value;if(b.type===y.LITERAL)p[h]=b.value;else if(b.type===y.VARIABLE)p[h]=ee(b.path,t,r);else if(b.type===y.INTERPOLATION){let I=[];for(let E of b.parts)if(typeof E=="string")I.push(E);else if(E.type===y.VARIABLE){let A=ee(E.path,t,r);I.push(A!=null?String(A):"")}else{c=!1;break}if(!c)break;p[h]=I.join("")}else{c=!1;break}}if(!c)break;a[d]=p}else{c=!1;break}}if(c)return l[i]=a,l}}return null},sl=(e,n,t,r)=>{let o=n.functions||n;if(e.whenCondition&&!Be(e.whenCondition,o,t,r))return;let i=il(e,n,t,r);if(i!==null)return i;if(e.fast){let c={};for(let u of e.properties){let d=u.parsedKey?V(u.parsedKey,n,t,r):u.key,f=u.value;if(f.type===y.LITERAL)c[d]=f.value;else if(f.type===y.VARIABLE)c[d]=ee(f.path,t,r);else if(f.type===y.INTERPOLATION){let p=[];for(let g of f.parts)if(typeof g=="string")p.push(g);else if(g.type===y.VARIABLE){let h=ee(g.path,t,r);p.push(h!=null?String(h):"")}else{let h=V(g,n,t,r);p.push(h!=null?String(h):"")}c[d]=p.join("")}else c[d]=V(f,n,t,r)}return c}let s={},l=null,a=!1;for(let c of e.properties)if(!c.key.startsWith("$if ")&&!c.key.match(/^\$if\s+\w+.*:?$/)&&!c.key.startsWith("$elif")&&!c.key.startsWith("$else")&&!c.key.startsWith("$for ")){a=!0;break}for(let c of e.properties)if(c.key.startsWith("$if ")||c.key.match(/^\$if\s+\w+.*:?$/)){let u=V(c.value,n,t,r);if(!a&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(c.key.startsWith("$for ")){if(e.properties.length===1)return V(c.value,n,t,r)}else{let u=c.value;if(u&&u.type===y.OBJECT&&u.properties){let d=u.properties.find(f=>f.key.startsWith("$for "));if(d){let f=V(d.value,n,t,r);f!==void 0&&(s[c.key]=f)}else{let f=V(c.value,n,t,r);f!==void 0&&(s[c.key]=f)}}else{let d=c.parsedKey?V(c.parsedKey,n,t,r):c.key,f=V(c.value,n,t,r);f!==void 0&&(s[d]=f)}}return s},yi={},al=(e,n,t,r)=>{let o=[];for(let i of e.items)if(i.type===y.LOOP){let s=V(i,n,t,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=V(i,n,t,r);s!==yi&&s!==void 0&&o.push(s)}return o},cl=(e,n,t,r)=>{let{name:o,data:i,whenCondition:s}=e,l=n.partials||{},a=n.functions||n;if(s&&!Be(s,a,t,r))return;if(!l[o])throw new pe(`Partial '${o}' is not defined`);let c=r._partialStack||[];if(c.includes(o))throw new pe(`Circular partial reference detected: ${o}`);let u=l[o],d=t,f={...r,_partialStack:[...c,o]};if(r){d={...t};for(let p of Object.keys(r))p.startsWith("_")||(d[p]=r[p])}if(i){let p=V(i,n,t,r);d={...d,...p}}return V(u,n,d,f)},ll=(e,n,t,r)=>{let{path:o}=e,i=o.split("."),s=i[0],l=i.slice(1);if(!r||!(s in r))throw new pe(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(s in r.__paths__))throw new pe(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=r.__paths__[s];if(typeof a=="number"){if(l.length>0)throw new pe(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return l.length>0&&(a+="."+l.join(".")),a};var gr=Kc;var ul=/\$\{([^}]*)\}/g,dl=/#\{([^}]*)\}/g,Ii=(e,n={})=>{let t=e.match(/^(\w+)\((.*)\)$/);if(!t)return{isFunction:!1};let[,r,o]=t,i=fl(o,n);return{isFunction:!0,type:y.FUNCTION,name:r,args:i}},fl=(e,n={})=>e.trim()?pl(e).map(r=>ml(r.trim(),n)):[],pl=e=>{let n=[],t="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],a=s>0?e[s-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,t+=l):o&&l===i&&a!=="\\"?(o=!1,i="",t+=l):!o&&l==="("?(r++,t+=l):!o&&l===")"?(r--,t+=l):!o&&l===","&&r===0?(n.push(t),t=""):t+=l}return t&&n.push(t),n},ml=(e,n={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:y.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:y.LITERAL,value:parseFloat(e)};if(e==="true")return{type:y.LITERAL,value:!0};if(e==="false")return{type:y.LITERAL,value:!1};if(e==="null")return{type:y.LITERAL,value:null};let t=Ii(e,n);if(t.isFunction)return{type:t.type,name:t.name,args:t.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:l,type:a}of o){let c=0;for(;c<r.length;){let u=rn(r.substring(c),l);if(u===-1)break;let d=c+u;d>i&&(i=d,s={op:l,type:a}),c=d+l.length}}if(i!==-1)try{return re(r,n)}catch{return{type:y.VARIABLE,path:r}}return{type:y.VARIABLE,path:r}},wi=/^\w+\(.*\)$/,gl=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,hl=e=>{if(!(!e||e.trim()===""||wi.test(e))&&gl.test(e))throw e.includes("?")&&e.includes(":")?new R(`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 R(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new R(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},bi=e=>{let n=e.trim();if(wi.test(n))throw new R(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(n.includes("["))throw new R(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(n))throw new R(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(n))throw new R(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(n.includes("?")&&n.includes(":"))throw new R(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:y.PATH_REFERENCE,path:n}},Nn=(e,n={})=>{let t=e.trim();hl(t);let r=Ii(t,n);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};if(t.includes("[")&&!/[\s+\-*/%|&?:]/.test(t)){let o=0;for(let i of t)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:y.VARIABLE,path:t}},hr=(e,n={})=>{let t=e,r=[];(e.includes("\\${")||e.includes("\\#{"))&&(t=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),t=t.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),t=t.replace(/\\(\$\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${r.length}__`;return r.push(u),d}),t=t.replace(/\\(#\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${r.length}__`;return r.push(u),d}),t=t.replace(/\\DOUBLE_ESC_VAR/g,"\\"),t=t.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...t.matchAll(ul)],i=[...t.matchAll(dl)],s=[...o.map(c=>({match:c,type:"variable"})),...i.map(c=>({match:c,type:"pathref"}))].sort((c,u)=>c.match.index-u.match.index);if(s.length===0){let c=t;for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);return{type:y.LITERAL,value:c}}if(s.length===1&&s[0].match[0]===t&&r.length===0){let{match:c,type:u}=s[0];try{return u==="variable"?Nn(c[1],n):bi(c[1])}catch(d){if(d.message==="Invalid array index syntax")return{type:y.LITERAL,value:t};throw d}}let l=[],a=0;for(let{match:c,type:u}of s){let[d,f]=c,p=c.index;if(p>a){let g=t.substring(a,p);for(let h=0;h<r.length;h++)g=g.replace(`__ESCAPED_${h}__`,r[h]);g&&l.push(g)}try{let g;u==="variable"?g=Nn(f.trim(),n):g=bi(f.trim()),l.push(g)}catch(g){if(g.message==="Invalid array index syntax")l.push(d);else throw g}a=p+d.length}if(a<t.length){let c=t.substring(a);for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);c&&l.push(c)}return{type:y.INTERPOLATION,parts:l}};var Ir=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),xi=e=>Object.keys(e),ue=e=>e.join("."),Ge=(e,n,t)=>{let r=xi(e).filter(o=>!n.has(o));if(r.length>0)throw new R(`Unexpected key '${r[0]}' in condition JSON at '${ue(t)}'`)},ze=(e,n)=>typeof e=="string"?hr(e,n):typeof e=="object"&&e!==null?Array.isArray(e)?bl(e,n):Il(e,n):{type:y.LITERAL,value:e},yl=e=>{let{$each:n,...t}=e;if(typeof n!="string")throw new R("$each value must be a non-empty string");let r=n.trim();if(r==="")throw new R("$each value must be a non-empty string");if(Object.keys(t).length===0)throw new R("Empty $each body not allowed");if(t.$partial!==void 0)throw new R("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:t}},bl=(e,n)=>{let t=[],r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let a=yl(i),c=Object.keys(a);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let u=Ei(c[0],a[c[0]],n,!0);t.push(u),r=!0;continue}}catch(a){throw a instanceof R?a:new R(a.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let a=Ei(l[0],i[l[0]],n);t.push(a),r=!0;continue}}let s=ze(i,n);t.push(s),(s.type===y.FUNCTION||s.type===y.CONDITIONAL||s.type===y.LOOP||s.type===y.PARTIAL||s.type===y.OBJECT&&!s.fast||s.type===y.ARRAY&&!s.fast)&&(r=!0)}return{type:y.ARRAY,items:t,fast:!r}},Il=(e,n)=>{let t=[],r=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new R("$partial value must be a string");if(e.$partial.trim()==="")throw new R("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],c=[];for(let[I]of i)for(let E of a)if(I===E||I.startsWith(E+" ")||I.startsWith(E+"#")){c.push(E);break}if(c.length>0)throw new R(`Cannot use $partial with ${c.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:d,...f}=e,p={},g=!1;for(let[I,E]of Object.entries(f)){let A=I;(I.startsWith("\\$")||I.startsWith("$$"))&&(A=I.slice(1)),p[A]=E,g=!0}let h=null;if(g&&(h=ze(p,n),h.type===y.OBJECT)){let I=!1;for(let E of h.properties)if(E.value.type===y.VARIABLE||E.value.type===y.INTERPOLATION||E.value.type===y.FUNCTION||E.value.type===y.CONDITIONAL||E.value.type===y.OBJECT&&!E.value.fast||E.value.type===y.ARRAY&&!E.value.fast){I=!0;break}I&&(h.fast=!1)}let b={type:y.PARTIAL,name:u,data:h};return d!==void 0&&(b.whenCondition=Ai(d,n)),b}for(let[a,c]of i)if(a==="$when"){if(o!==null)throw new R("Multiple '$when' directives on the same object are not allowed");if(c==null)throw new R("Missing condition expression after '$when'");o=Ai(c,n),r=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new R("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[a,c]=i[s];if(a==="$when"){s++;continue}if(a==="$each")throw new R("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let u=wl(i,s,n);t.push({key:a,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let u=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",d=u?`:${u}`:"";throw new R(`$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(a.startsWith("$elif ")||a.startsWith("$else"))throw new R(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new R("Missing condition expression after '$if'");{let u=ze(c,n);(u.type===y.FUNCTION||u.type===y.CONDITIONAL||u.type===y.PARTIAL||u.type===y.OBJECT&&!u.fast||u.type===y.ARRAY&&!u.fast)&&(r=!0);let d=hr(a,n),f={key:a,value:u};(d.type!==y.LITERAL||d.value!==a)&&(f.parsedKey=d),t.push(f),s++}}}let l={type:y.OBJECT,properties:t,fast:!r};return o&&(l.whenCondition=o),l},wl=(e,n,t={})=>{let r=[],o=[],i=n,[s,l]=e[i],a=null,c;if(s.startsWith("$if#")){let d=s.match(/^\$if#(\w+)\s+(.+)$/);if(d)a=d[1],c=d[2];else throw new R(`Invalid conditional syntax: ${s}`)}else c=s.substring(4),c.endsWith(":")&&(c=c.slice(0,-1).trim());mr(c);let u=re(c,t);for(r.push(u),o.push(ze(l,t)),i++;i<e.length;){let[d,f]=e[i],p=!1,g;if(a?d.startsWith(`$elif#${a} `)?(g=d.substring(`$elif#${a} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),p=!0):(d===`$else#${a}`||d===`$else#${a}:`)&&(p=!0,g=null):d.startsWith("$elif ")?(g=d.substring(6),g.endsWith(":")&&(g=g.slice(0,-1).trim()),p=!0):(d==="$else"||d==="$else:")&&(p=!0,g=null),p){if(g===null)r.push(null);else{mr(g);let h=re(g,t);r.push(h)}if(o.push(ze(f,t)),i++,g===null)break}else break}return{node:{type:y.CONDITIONAL,conditions:r,bodies:o,id:a},nextIndex:i}},yr={eq:M.EQ,neq:M.NEQ,gt:M.GT,gte:M.GTE,lt:M.LT,lte:M.LTE,in:M.IN,add:M.ADD,sub:M.SUBTRACT},br={all:M.AND,any:M.OR},Al=new Set(["var","literal","call","not",...Object.keys(yr),...Object.keys(br)]),El=(e,n,t)=>{if(!Array.isArray(e))throw new R(`Condition JSON operator '${n}' at '${ue(t)}' requires an array`);if(e.length!==2)throw new R(`Condition JSON operator '${n}' at '${ue(t)}' requires exactly 2 operands`);return e},xl=(e,n,t,r,o)=>{if(!Array.isArray(e))throw new R(`Condition JSON operator '${n}' at '${ue(o)}' requires an array`);if(e.length===0)throw new R(`Condition JSON operator '${n}' at '${ue(o)}' requires at least 1 condition`);return e.map((s,l)=>be(s,r,[...o,l])).reduce((s,l)=>({type:y.BINARY,op:t,left:s,right:l}))},vl=(e,n,t)=>{let r,o;if(typeof e.call=="string")r=e.call,o=e.args??[],Ge(e,new Set(["call","args"]),t);else if(Ir(e.call))r=e.call.name,o=e.call.args??[],Ge(e,new Set(["call"]),t),Ge(e.call,new Set(["name","args"]),[...t,"call"]);else throw new R(`Condition JSON call at '${ue(t)}' requires a function name`);if(typeof r!="string"||r.trim()==="")throw new R(`Condition JSON call at '${ue(t)}' requires a non-empty function name`);if(!/^\w+$/.test(r))throw new R(`Invalid condition JSON function name '${r}' at '${ue(t)}'`);if(!Array.isArray(o))throw new R(`Condition JSON call '${r}' at '${ue(t)}' requires args to be an array`);return{type:y.FUNCTION,name:r,args:o.map((i,s)=>be(i,n,[...t,"args",s]))}},be=(e,n={},t=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:y.LITERAL,value:e};if(Array.isArray(e))throw new R(`Condition JSON array at '${ue(t)}' must be wrapped in an operator or { literal: [...] }`);if(!Ir(e))throw new R(`Invalid condition JSON value at '${ue(t)}'`);let r=xi(e);if(r.length===0)throw new R(`Condition JSON object at '${ue(t)}' must contain an operator`);let o=r.filter(s=>Al.has(s));if(o.length===0)throw new R(`Unknown condition JSON operator '${r[0]}' at '${ue(t)}'`);if(o.length>1)throw new R(`Condition JSON at '${ue(t)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(Ge(e,new Set(["var"]),t),typeof e.var!="string"||e.var.trim()==="")throw new R(`Condition JSON var at '${ue(t)}' requires a non-empty path`);return{type:y.VARIABLE,path:e.var}}if(i==="literal")return Ge(e,new Set(["literal"]),t),{type:y.LITERAL,value:e.literal};if(i==="call")return vl(e,n,t);if(i==="not")return Ge(e,new Set(["not"]),t),{type:y.UNARY,op:In.NOT,operand:be(e.not,n,[...t,"not"])};if(i in br)return Ge(e,new Set([i]),t),xl(e[i],i,br[i],n,[...t,i]);if(i in yr){Ge(e,new Set([i]),t);let s=El(e[i],i,[...t,i]);return{type:y.BINARY,op:yr[i],left:be(s[0],n,[...t,i,0]),right:be(s[1],n,[...t,i,1])}}throw new R(`Unknown condition JSON operator '${i}' at '${ue(t)}'`)},Ai=(e,n={})=>{if(e==null)throw new R("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new R("Empty condition expression after '$when'");return re(e,n)}return Ir(e)||Array.isArray(e)?be(e,n):{type:y.LITERAL,value:e}},re=(e,n={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let c=e.slice(1,-1),u=0,d=!0;for(let f=0;f<c.length;f++)if(c[f]==="("?u++:c[f]===")"&&u--,u<0){d=!1;break}if(d&&u===0)return re(c,n)}let t=rn(e,"||");if(t!==-1)return{type:y.BINARY,op:M.OR,left:re(e.substring(0,t).trim(),n),right:re(e.substring(t+2).trim(),n)};let r=rn(e,"&&");if(r!==-1)return{type:y.BINARY,op:M.AND,left:re(e.substring(0,r).trim(),n),right:re(e.substring(r+2).trim(),n)};let o=[{op:">=",type:M.GTE},{op:"<=",type:M.LTE},{op:"==",type:M.EQ},{op:"!=",type:M.NEQ},{op:">",type:M.GT},{op:"<",type:M.LT},{op:" in ",type:M.IN}];for(let{op:c,type:u}of o){let d=rn(e,c);if(d!==-1)return{type:y.BINARY,op:u,left:re(e.substring(0,d).trim(),n),right:re(e.substring(d+c.length).trim(),n)}}let i=-1,s=null,l=[{op:" + ",type:M.ADD},{op:" - ",type:M.SUBTRACT}];for(let{op:c,type:u}of l){let d=0;for(;d<e.length;){let f=rn(e.substring(d),c);if(f===-1)break;let p=d+f;p>i&&(i=p,s={op:c,type:u}),d=p+c.length}}if(i!==-1&&s)return{type:y.BINARY,op:s.type,left:re(e.substring(0,i).trim(),n),right:re(e.substring(i+s.op.length).trim(),n)};let a=[" * "," / "," % "];for(let c of a)if(rn(e,c)!==-1)throw new R(`Arithmetic operations are not allowed in conditionals: "${c}"`);return e.startsWith("!")?{type:y.UNARY,op:In.NOT,operand:re(e.substring(1).trim(),n)}:vi(e,n)},rn=(e,n)=>{let t=0,r=0;for(;r<=e.length-n.length;){if(e[r]==="(")t++;else if(e[r]===")")t--;else if(t===0&&e.substring(r,r+n.length)===n)return r;r++}return-1},Sl=e=>{if(e=e.trim(),e==="true")return{type:y.LITERAL,value:!0};if(e==="false")return{type:y.LITERAL,value:!1};if(e==="null")return{type:y.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:y.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:y.LITERAL,value:""};if(e==="{}")return{type:y.LITERAL,value:{}};if(e==="[]")return{type:y.LITERAL,value:[]};let n=Number(e);return!isNaN(n)&&isFinite(n)?{type:y.LITERAL,value:n}:{type:y.VARIABLE,path:e}},vi=(e,n)=>{let t=e.trim();if(t.match(/^(\w+)\((.*)\)$/))return Nn(t,n);let o=Sl(t);if(o.type===y.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(t))return{type:y.VARIABLE,path:t};try{return Nn(t,n)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Rl=(e,n=!1)=>{let t=n?"$each":"$for";try{ui(e)}catch(r){if(r instanceof R&&n){let o=r.message.replace(/\$for/g,"$each");throw new R(o.replace("Parse Error: ",""))}throw r}},Ei=(e,n,t,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let b=r?"$each":"$for";throw new R(`Invalid loop syntax (got: '${e.replace("$for",b)}')`)}let s=i[1],l=i[2].trim();Rl(l,r);let a=l.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let b=r?"$each":"$for";throw new R(`Invalid loop syntax - missing 'in' keyword (got: '${b} ${l}')`)}let c=a[1].trim(),u=a[2].trim(),d,f=null;if(c.includes(",")){let b=c.split(",").map(I=>I.trim());if(b.length!==2)throw new R(`Invalid loop variables: ${c}. Expected format: "item" or "item, index"`);d=b[0],f=b[1]}else d=c;let p=["this","undefined","null","true","false"];if(p.includes(d))throw new R(`Reserved variable name: ${d}`);if(f&&p.includes(f))throw new R(`Reserved variable name: ${f}`);let g=vi(u,t),h=ze(n,t);return{type:y.LOOP,itemVar:d,indexVar:f,iterable:g,body:h,flatten:s!=="nested"}};var Cl=(e,n={})=>{let{functions:t={}}=n;return ze(e,t)},It=Cl;var Dn={};jc(Dn,{now:()=>_l});var _l=()=>Date.now();var kl=(e,n,t={})=>{let{functions:r={},partials:o={}}=t,i={...Dn,...r},s=It(e,{functions:i}),l={};for(let[a,c]of Object.entries(o))l[a]=It(c,{functions:i});return gr(s,n,{functions:i,partials:l})},on=kl;var Ol=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",$l=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Tl=(e,n)=>{if(Ol(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new R("Empty condition expression");return re(e,n)}return be(e,n)},Ll=(e,n={},t={})=>{let r=$l(t),o={...Dn,...r},i=Tl(e,o);return!!Be(i,{functions:o,partials:{}},n,{})},wr=Ll;var kr=Symbol("runStoreTransaction"),vr="__routeEngineConditionComparison",wt=(e,n)=>typeof e=="number"&&typeof n=="number"&&Number.isFinite(e)&&Number.isFinite(n)||typeof e=="string"&&typeof n=="string",qe=Object.freeze({eq:(e,n)=>e===n,neq:(e,n)=>e!==n,gt:(e,n)=>wt(e,n)&&e>n,gte:(e,n)=>wt(e,n)&&e>=n,lt:(e,n)=>wt(e,n)&&e<n,lte:(e,n)=>wt(e,n)&&e<=n}),$i=Object.freeze(Object.fromEntries(Object.keys(qe).map(e=>[e,`${vr}${e}`]))),Pl=Object.freeze(Object.fromEntries(Object.entries($i).map(([e,n])=>[n,qe[e]]))),Si=(e,n)=>Object.prototype.hasOwnProperty.call(e??{},n),Nl=e=>{if(typeof e?.call=="string")return e.call;if(e?.call!==null&&typeof e?.call=="object"&&!Array.isArray(e.call))return e.call.name},At=e=>{if(Array.isArray(e))return e.map(At);if(e===null||typeof e!="object"||Si(e,"literal")||Si(e,"var"))return e;if(Nl(e)?.startsWith(vr))throw new Error(`Condition function names beginning with "${vr}" are reserved`);let t=Object.entries(e);if(t.length===1){let[[r,o]]=t,i=$i[r];if(i)return{call:i,args:o.map(At)}}return Object.fromEntries(t.map(([r,o])=>[r,At(o)]))},Vn=(e,n={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return be(e),wr(At(e),n,{functions:Pl})},Dl=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Ti=(e,n,t={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:l=c=>c}=t;for(let[c,u]of Object.entries(n))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...d)=>u(s(r),...d):i[c]=(...d)=>{let f;return r=pr(r,g=>{let h=u(l(g),...d);f=h!==void 0&&!ie(h)?h:void 0}),f});let a=c=>{if(typeof c!="function")throw new Error("Store transaction requires a callback");let u=r;try{return c()}catch(d){throw r=u,d}};return{...o,...i,[kr]:a}},St=(e,n)=>t=>{let r=e(),o=Array.isArray(t)?t:[t];return pr(r,i=>{o.forEach(s=>{n.forEach(l=>{l(i,s)})})})};var Ml=(e,n)=>{if(e.default!==void 0)return e.default;let t=["number","boolean","string","object"];if(!t.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${n}. Expected one of: ${t.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},P=(e,n)=>Object.prototype.hasOwnProperty.call(e??{},n),Sr=(e,n,t)=>{Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0})},ne=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Vl=new Set(["pageSize","groups"]),jl=new Set(["id","variants"]),Fl=new Set(["id","imageId"]),Ul=new Set(["pageSize","tracks"]),Bl=new Set(["id","soundId","title","artist","album","description","coverImageId"]),Gl=new Set(["pageSize","replays"]),zl=new Set(["id","title","thumbnailImageId","startSectionId","initialVariables"]),sn=(e,n,t)=>{Object.keys(e).forEach(r=>{if(!n.has(r))throw new Error(`${t} contains unsupported property "${r}"`)})},wn=(e,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} must be a non-empty string`)},jn=(e={})=>{let n=e?.resources?.imageGallery;if(n===void 0)return;if(!ne(n))throw new Error("resources.imageGallery must be an object");if(sn(n,Vl,"resources.imageGallery"),!Number.isInteger(n.pageSize)||n.pageSize<1)throw new Error("resources.imageGallery.pageSize must be an integer greater than or equal to 1");if(!Array.isArray(n.groups))throw new Error("resources.imageGallery.groups must be an array");let t=new Set;for(let[r,o]of n.groups.entries()){let i=`resources.imageGallery.groups[${r}]`;if(!ne(o))throw new Error(`${i} must be an object`);if(sn(o,jl,i),wn(o.id,`${i}.id`),t.has(o.id))throw new Error(`Duplicate image gallery group id "${o.id}"`);if(t.add(o.id),!Array.isArray(o.variants)||o.variants.length===0)throw new Error(`${i}.variants must be a non-empty array`);let s=new Set;for(let[l,a]of o.variants.entries()){let c=`${i}.variants[${l}]`;if(!ne(a))throw new Error(`${c} must be an object`);if(sn(a,Fl,c),wn(a.id,`${c}.id`),wn(a.imageId,`${c}.imageId`),s.has(a.id))throw new Error(`Duplicate image gallery variant id "${a.id}" in group "${o.id}"`);if(s.add(a.id),!P(e?.resources?.images,a.imageId))throw new Error(`Image gallery variant "${o.id}.${a.id}" references unknown image "${a.imageId}"`)}}},Fn=(e={})=>{let n=e?.resources?.musicRoom;if(n===void 0)return;if(!ne(n))throw new Error("resources.musicRoom must be an object");if(sn(n,Ul,"resources.musicRoom"),!Number.isInteger(n.pageSize)||n.pageSize<1)throw new Error("resources.musicRoom.pageSize must be an integer greater than or equal to 1");if(!Array.isArray(n.tracks))throw new Error("resources.musicRoom.tracks must be an array");let t=new Set;for(let[r,o]of n.tracks.entries()){let i=`resources.musicRoom.tracks[${r}]`;if(!ne(o))throw new Error(`${i} must be an object`);sn(o,Bl,i);for(let a of["id","soundId","title"])wn(o[a],`${i}.${a}`);for(let a of["artist","album","description","coverImageId"])o[a]!==void 0&&wn(o[a],`${i}.${a}`);if(t.has(o.id))throw new Error(`Duplicate music room track id "${o.id}"`);t.add(o.id);let s=e?.resources?.sounds?.[o.soundId];if(!P(e?.resources?.sounds,o.soundId))throw new Error(`Music room track "${o.id}" references unknown sound "${o.soundId}"`);if(!ne(s))throw new Error(`Music room track "${o.id}" references invalid sound "${o.soundId}"`);if(s.playbackRate!==void 0&&(typeof s.playbackRate!="number"||!Number.isFinite(s.playbackRate)||s.playbackRate<=0))throw new Error(`Music room sound "${o.soundId}" playbackRate must be a finite number greater than 0`);let l=s.startAt??0;if(typeof l!="number"||!Number.isFinite(l)||l<0)throw new Error(`Music room sound "${o.soundId}" startAt must be a finite non-negative number`);if(s.endAt!==void 0&&s.endAt!==null&&(typeof s.endAt!="number"||!Number.isFinite(s.endAt)||s.endAt<=l))throw new Error(`Music room sound "${o.soundId}" endAt must be a finite number greater than startAt`);if(o.coverImageId!==void 0&&!P(e?.resources?.images,o.coverImageId))throw new Error(`Music room track "${o.id}" references unknown cover image "${o.coverImageId}"`)}},ql=(e,n,t)=>{let r=Array.isArray(t)?"array":typeof t;switch(n.type){case"number":if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Scene replay initial variable "${e}" expected type number, got ${r}`);return;case"boolean":if(typeof t!="boolean")throw new Error(`Scene replay initial variable "${e}" expected type boolean, got ${r}`);return;case"string":if(typeof t!="string")throw new Error(`Scene replay initial variable "${e}" expected type string, got ${r}`);return;case"object":if(t===null||typeof t!="object")throw new Error(`Scene replay initial variable "${e}" expected type object, got ${r}`);return;default:throw new Error(`Scene replay initial variable "${e}" has invalid variable type "${n.type}"`)}},Un=(e={})=>{let n=e?.resources?.sceneReplay;if(n===void 0)return;if(!ne(n))throw new Error("resources.sceneReplay must be an object");if(sn(n,Gl,"resources.sceneReplay"),!Number.isInteger(n.pageSize)||n.pageSize<1)throw new Error("resources.sceneReplay.pageSize must be an integer greater than or equal to 1");if(!Array.isArray(n.replays))throw new Error("resources.sceneReplay.replays must be an array");let t=new Map;Object.values(e?.story?.scenes??{}).forEach(o=>{Object.entries(o?.sections??{}).forEach(([i,s])=>{t.set(i,s)})});let r=new Set;for(let[o,i]of n.replays.entries()){let s=`resources.sceneReplay.replays[${o}]`;if(!ne(i))throw new Error(`${s} must be an object`);sn(i,zl,s);for(let a of["id","title","thumbnailImageId","startSectionId"])wn(i[a],`${s}.${a}`);if(r.has(i.id))throw new Error(`Duplicate scene replay id "${i.id}"`);if(r.add(i.id),!P(e?.resources?.images,i.thumbnailImageId))throw new Error(`Scene replay "${i.id}" references unknown thumbnail image "${i.thumbnailImageId}"`);if(!t.has(i.startSectionId))throw new Error(`Scene replay "${i.id}" references unknown start section "${i.startSectionId}"`);let l=t.get(i.startSectionId);if(l.initialLineId!==void 0&&!l.lines?.some(a=>a.id===l.initialLineId))throw new Error(`Scene replay "${i.id}" start section "${i.startSectionId}" references unknown initial line "${l.initialLineId}"`);if(i.initialVariables!==void 0){if(!ne(i.initialVariables))throw new Error(`${s}.initialVariables must be an object`);for(let[a,c]of Object.entries(i.initialVariables)){let u=e?.resources?.variables?.[a];if(!u)throw new Error(`Scene replay "${i.id}" initialVariables references unknown variable "${a}"`);if(Se(u))throw new Error(`Scene replay "${i.id}" cannot initialize computed variable "${a}"`);if(u.readonly===!0)throw new Error(`Scene replay "${i.id}" cannot initialize readonly variable "${a}"`);if(u.scope!=="context")throw new Error(`Scene replay "${i.id}" can only initialize context variable "${a}"`);ql(a,u,c)}}}},Li=e=>{let n=ie(e)?Ue(e):e;return structuredClone(n)},Yl=({characterId:e,resourceCharacter:n,variables:t={}}={})=>{if(!P(n,"nameVariableId"))return;let r=n.nameVariableId,o=t?.[r];if(typeof o!="string")throw new Error(`Character "${e}" nameVariableId "${r}" must resolve to a string variable`);return o},Rt=({characterId:e,character:n,characterName:t,characters:r={},variables:o={}}={})=>{let i=e?r?.[e]:void 0;if(n?.name!==void 0)return n.name;if(t!==void 0)return t;let s=Yl({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},Se=e=>P(e,"computed"),An=(e={},n={})=>Object.fromEntries(Object.entries(e??{}).filter(([t])=>!Se(n[t]))),ve=(e,n)=>new Error(`${n} has invalid path: ${JSON.stringify(e)}`),Hl=(e,n,t)=>{if(e[0]==='"')try{return JSON.parse(e)}catch{throw ve(n,t)}let o="";for(let i=1;i<e.length-1;i+=1){let s=e[i];if(s!=="\\"){if(s.charCodeAt(0)<32)throw ve(n,t);o+=s;continue}if(i+=1,i>=e.length-1)throw ve(n,t);let l=e[i];if(l==="u"){let c=e.slice(i+1,i+5);if(c.length!==4||!/^[0-9a-fA-F]{4}$/.test(c))throw ve(n,t);o+=String.fromCharCode(Number.parseInt(c,16)),i+=4;continue}let a={"\\":"\\",'"':'"',"'":"'","/":"/",n:`
2
+ `,r:"\r",t:" ",b:"\b",f:"\f"};if(!P(a,l))throw ve(n,t);o+=a[l]}return o},Pi=(e,n="Computed expression var")=>{if(typeof e!="string"||e.length===0||e.trim()!==e)throw ve(e,n);let t=[],r=0,o=()=>{let s=r;for(;r<e.length&&e[r]!=="."&&e[r]!=="["&&e[r]!=="]";)r+=1;let l=e.slice(s,r);if(l.length===0||l.trim()!==l||/\s/.test(l))throw ve(e,n);t.push(l)},i=()=>{for(r+=1;r<e.length&&/\s/.test(e[r]);)r+=1;let s=e[r];if(/\d/.test(s??"")){let u=r;for(;r<e.length&&/\d/.test(e[r]);)r+=1;let d=e.slice(u,r);for(;r<e.length&&/\s/.test(e[r]);)r+=1;if(e[r]!=="]"||d.length>1&&d.startsWith("0"))throw ve(e,n);r+=1,t.push(d);return}if(s!=='"'&&s!=="'")throw ve(e,n);let l=s,a=r;r+=1;let c=!1;for(;r<e.length;){let u=e[r];if(c)c=!1;else if(u==="\\")c=!0;else if(u===l){let d=e.slice(a,r+1);for(r+=1;r<e.length&&/\s/.test(e[r]);)r+=1;if(e[r]!=="]")throw ve(e,n);r+=1,t.push(Hl(d,e,n));return}r+=1}if(c||r>=e.length)throw ve(e,n)};for(o();r<e.length;){if(e[r]==="."){r+=1,o();continue}if(e[r]==="["){i();continue}throw ve(e,n)}return t},Ar=(e,n)=>{let t=e;for(let r of n){if(t==null||!P(t,r))return;t=t[r]}return t},Ni=(e,n={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let t=Pi(e),[r,o,...i]=t;if(r==="variables"){if(!o)return n.variables;let s=typeof n.resolveVariable=="function"?n.resolveVariable(o):n.variables?.[o];return Ar(s,i)}return r==="runtime"?Ar(n.runtime,t.slice(1)):Ar(n,t)},Di=(e,n,t)=>{if(!Array.isArray(n))throw new Error(`Computed expression operator "${e}" requires an array`);if(t!==void 0&&n.length!==t)throw new Error(`Computed expression operator "${e}" requires ${t} operand(s)`)},Rr=(e,n)=>{if(!Array.isArray(n))throw new Error(`Computed expression operator "${e}" requires an array`);if(n.length===0)throw new Error(`Computed expression operator "${e}" requires at least one operand`)},Wl=(e,n)=>{if(typeof n!="number"||!Number.isFinite(n))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},_e=(e,n,t,r)=>(Di(e,n,r),n.map(o=>vt(o,t))),xe=(e,n,t,r)=>{let o=_e(e,n,t,r);return o.forEach(i=>Wl(e,i)),o},Kl=(e,n,t)=>{switch(e){case"var":return Ni(n,t);case"add":{let[r,o]=xe(e,n,t,2);return r+o}case"sub":{let[r,o]=xe(e,n,t,2);return r-o}case"mul":{let[r,o]=xe(e,n,t,2);return r*o}case"div":{let[r,o]=xe(e,n,t,2);return r/o}case"mod":{let[r,o]=xe(e,n,t,2);return r%o}case"neg":{let[r]=xe(e,n,t,1);return-r}case"round":{let[r]=xe(e,n,t,1);return Math.round(r)}case"floor":{let[r]=xe(e,n,t,1);return Math.floor(r)}case"ceil":{let[r]=xe(e,n,t,1);return Math.ceil(r)}case"min":{let[r,o]=xe(e,n,t,2);return Math.min(r,o)}case"max":{let[r,o]=xe(e,n,t,2);return Math.max(r,o)}case"clamp":{let[r,o,i]=xe(e,n,t,3);return Math.min(i,Math.max(o,r))}case"eq":{let[r,o]=_e(e,n,t,2);return qe.eq(r,o)}case"neq":{let[r,o]=_e(e,n,t,2);return qe.neq(r,o)}case"gt":{let[r,o]=_e(e,n,t,2);return qe.gt(r,o)}case"gte":{let[r,o]=_e(e,n,t,2);return qe.gte(r,o)}case"lt":{let[r,o]=_e(e,n,t,2);return qe.lt(r,o)}case"lte":{let[r,o]=_e(e,n,t,2);return qe.lte(r,o)}case"in":{let[r,o]=_e(e,n,t,2);return Array.isArray(o)?o.includes(r):!1}case"and":case"all":return Rr(e,n),n.every(r=>!!vt(r,t));case"or":case"any":return Rr(e,n),n.some(r=>!!vt(r,t));case"not":{let[r]=_e(e,n,t,1);return!r}case"length":{let[r]=_e(e,n,t,1);return typeof r=="string"||Array.isArray(r)?r.length:ne(r)?Object.keys(r).length:0}case"includes":{let[r,o]=_e(e,n,t,2);return typeof r=="string"?typeof o=="string"&&r.includes(o):Array.isArray(r)?r.includes(o):!1}case"literal":return Li(n);default:throw new Error(`Unknown computed expression operator: ${e}`)}},vt=(e,n={})=>{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 t=Object.entries(e);if(t.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[r,o]]=t;return Kl(r,o,n)},Cr=(e,n)=>{if(e===null||typeof e!="object"||P(e,"literal"))return e;if(P(e,"var"))return{literal:Ni(e.var,n)};if(P(e,"call"))throw new Error("Function calls are not supported in computed-variable conditions");return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Array.isArray(r)?r.map(o=>Cr(o,n)):Cr(r,n)]))},Jl=(e,n={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return be(e),Vn(Cr(e,n))},Mi=(e,n)=>{if(!ne(e))throw new Error(`${n} must be an object`);let t=P(e,"expr"),r=P(e,"value");if(t===r)throw new Error(`${n} must contain exactly one of expr or value`)},Er=(e,n,t)=>(Mi(e,n),P(e,"value")?Li(e.value):vt(e.expr,t)),Xl=(e,n={},t="unknown")=>{if(!ne(e))throw new Error(`Computed variable "${t}" computed must be an object`);let r=P(e,"expr"),o=P(e,"value");if(P(e,"branches")){if(r||o)throw new Error(`Computed variable "${t}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${t}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${t}" branches must not be empty`);if(!ne(e.default))throw new Error(`Computed variable "${t}" requires default`);for(let s=0;s<e.branches.length;s+=1){let l=e.branches[s];if(!ne(l))throw new Error(`Computed variable "${t}" branch ${s} must be an object`);if(!P(l,"when"))throw new Error(`Computed variable "${t}" branch ${s} requires when`);if(Jl(l.when,n))return Er(l,`Computed variable "${t}" branch ${s}`,n)}return Er(e.default,`Computed variable "${t}" default`,n)}if(r===o)throw new Error(`Computed variable "${t}" must contain exactly one of expr, value, or branches`);return Er(e,`Computed variable "${t}"`,n)},Vi=(e,n,t)=>{switch(n){case"number":if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(t)?"array":typeof t}`);return;case"boolean":if(typeof t!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(t)?"array":typeof t}`);return;case"string":if(typeof t!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(t)?"array":typeof t}`);return;case"object":if(t===null||typeof t!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof t}`);return;default:throw new Error(`Invalid variable type: ${n} for computed variable ${e}`)}},Ql=Object.freeze({add:2,sub:2,mul:2,div:2,mod:2,neg:1,round:1,floor:1,ceil:1,min:2,max:2,clamp:3,eq:2,neq:2,gt:2,gte:2,lt:2,lte:2,in:2,not:1,length:1,includes:2}),Zl=new Set(["and","or","all","any"]),eu=new Set(["add","sub","mul","div","mod","neg","round","floor","ceil","min","max","clamp","length"]),nu=new Set(["add","sub","mul","div","mod","neg","round","floor","ceil","min","max","clamp"]),tu=new Set(["eq","neq","gt","gte","lt","lte","in","and","or","all","any","not","includes"]),ru=new Set(["all","any","eq","neq","gt","gte","lt","lte","in","add","sub"]),ji=new WeakMap,Ri=e=>e===null?"null":Array.isArray(e)?"object":typeof e,Et=(e,n,t)=>{for(let r of Object.keys(e))if(!n.has(r))throw new Error(`${t} contains unsupported property "${r}"`)},ou=(e,n,t,r)=>{if(t!==void 0&&t!==n)throw new Error(`Computed variable "${e}" ${r} expected type ${n}, got ${t}`)},Fi=(e,{variableId:n,variableConfigs:t,dependencies:r,path:o})=>{let i=`Computed variable "${n}" ${o} var`,[s,l,...a]=Pi(e,i);if(s!=="variables"&&s!=="runtime")throw new Error(`${i} must reference variables.* or runtime.*, got ${JSON.stringify(e)}`);if(!l)throw new Error(`${i} must reference a concrete ${s} member, got ${JSON.stringify(e)}`);if(s==="runtime")return;if(!P(t,l))throw new Error(`Computed variable "${n}" ${o} references unknown variable "${l}"`);let c=t[l];return Se(c)&&r.add(l),a.length===0?c?.type:void 0},Ui=(e,{variableId:n,variableConfigs:t,dependencies:r,path:o})=>{if(e===null||typeof e!="object"){if(typeof e=="number"&&!Number.isFinite(e))throw new Error(`Computed variable "${n}" ${o} must use finite numeric literals`);return Ri(e)}if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let i=Object.entries(e);if(i.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[s,l]]=i;if(s==="var"){if(typeof l!="string"||l.trim()==="")throw new Error("Computed expression var requires a non-empty string path");return Fi(l,{variableId:n,variableConfigs:t,dependencies:r,path:o})}if(s==="literal"){if(typeof l=="number"&&!Number.isFinite(l))throw new Error(`Computed variable "${n}" ${o} must use finite numeric literals`);return Ri(l)}let a=Ql[s];if(a===void 0&&!Zl.has(s))throw new Error(`Unknown computed expression operator: ${s}`);a===void 0?Rr(s,l):Di(s,l,a);let c=l.map((u,d)=>Ui(u,{variableId:n,variableConfigs:t,dependencies:r,path:`${o}.${s}[${d}]`}));if(nu.has(s)&&c.forEach(u=>{if(u!==void 0&&u!=="number")throw new Error(`Computed expression operator "${s}" requires numeric operands`)}),eu.has(s))return"number";if(tu.has(s))return"boolean"},iu=(e,{variableId:n,variableConfigs:t,dependencies:r,path:o})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");try{be(e)}catch(s){throw new Error(`Computed variable "${n}" ${o} is invalid: ${s.message}`,{cause:s})}let i=(s,l)=>{if(s===null||typeof s!="object"||P(s,"literal"))return;if(P(s,"var")){Fi(s.var,{variableId:n,variableConfigs:t,dependencies:r,path:l});return}if(P(s,"call"))throw new Error(`Computed variable "${n}" ${l} function calls are not supported`);if(P(s,"not")){i(s.not,`${l}.not`);return}let a=Object.keys(s).find(c=>ru.has(c));s[a].forEach((c,u)=>{i(c,`${l}.${a}[${u}]`)})};i(e,o)},xr=(e,{variableId:n,variableConfig:t,variableConfigs:r,dependencies:o,path:i,allowedKeys:s=new Set(["expr","value"])})=>{if(Mi(e,`Computed variable "${n}" ${i}`),Et(e,s,i),P(e,"value")){Vi(n,t.type,e.value);return}let l=Ui(e.expr,{variableId:n,variableConfigs:r,dependencies:o,path:`${i}.expr`});ou(n,t.type,l,`${i}.expr`)},su=(e,n,t)=>{let r=n.computed;if(!ne(r))throw new Error(`Computed variable "${e}" computed must be an object`);let o=new Set,i=P(r,"expr"),s=P(r,"value");if(P(r,"branches")){if(Et(r,new Set(["branches","default"]),`Computed variable "${e}" computed`),i||s)throw new Error(`Computed variable "${e}" cannot combine branches with expr or value`);if(!Array.isArray(r.branches))throw new Error(`Computed variable "${e}" branches must be an array`);if(r.branches.length===0)throw new Error(`Computed variable "${e}" branches must not be empty`);if(!ne(r.default))throw new Error(`Computed variable "${e}" requires default`);return r.branches.forEach((a,c)=>{if(!ne(a))throw new Error(`Computed variable "${e}" branch ${c} must be an object`);if(Et(a,new Set(["when","expr","value"]),`Computed variable "${e}" branch ${c}`),!P(a,"when"))throw new Error(`Computed variable "${e}" branch ${c} requires when`);iu(a.when,{variableId:e,variableConfigs:t,dependencies:o,path:`computed.branches[${c}].when`}),xr(a,{variableId:e,variableConfig:n,variableConfigs:t,dependencies:o,path:`computed.branches[${c}]`,allowedKeys:new Set(["when","expr","value"])})}),xr(r.default,{variableId:e,variableConfig:n,variableConfigs:t,dependencies:o,path:"computed.default"}),o}if(Et(r,new Set(["expr","value"]),`Computed variable "${e}" computed`),i===s)throw new Error(`Computed variable "${e}" must contain exactly one of expr, value, or branches`);return xr(r,{variableId:e,variableConfig:n,variableConfigs:t,dependencies:o,path:"computed"}),o},an=(e={})=>{if(!ne(e))throw new Error("Variable configs must be an object");if(P(e,"__proto__"))throw new Error('Variable id "__proto__" is reserved');if(P(e,""))throw new Error("Variable ids must not be empty");let n=new Map;Object.entries(e).forEach(([i,s])=>{if(Se(s)){if(!ne(s))throw new Error(`Computed variable "${i}" must be an object`);if(!P(s,"type"))throw new Error(`Computed variable "${i}" requires type`);if(!P(s,"scope"))throw new Error(`Computed variable "${i}" requires scope`);if(P(s,"default"))throw new Error(`Computed variable "${i}" must not declare a top-level default`);if(Gn(s.scope,i),!["number","boolean","string","object"].includes(s.type))throw new Error(`Invalid variable type: ${s.type} for computed variable ${i}`);n.set(i,su(i,s,e))}});let t=new Set,r=[];n.forEach((i,s)=>{if(t.has(s))return;let l=[{variableId:s,dependencies:[...n.get(s)??[]],nextDependencyIndex:0}],a=new Map([[s,0]]);for(;l.length>0;){let c=l.at(-1);if(c.nextDependencyIndex>=c.dependencies.length){l.pop(),a.delete(c.variableId),t.add(c.variableId),r.push(c.variableId);continue}let u=c.dependencies[c.nextDependencyIndex];if(c.nextDependencyIndex+=1,t.has(u))continue;let d=a.get(u);if(d!==void 0){let f=[...l.slice(d).map(({variableId:p})=>p),u].join(" -> ");throw new Error(`Computed variable cycle detected: ${f}`)}a.set(u,l.length),l.push({variableId:u,dependencies:[...n.get(u)??[]],nextDependencyIndex:0})}});let o=Object.freeze({evaluationOrder:Object.freeze(r)});return ji.set(e,o),o},Bn=({variables:e={},runtime:n={},variableConfigs:t={},eager:r=!0}={})=>{let{evaluationOrder:o}=ji.get(t)??an(t),i=An(e,t),s=Object.entries(t).filter(([,b])=>Se(b)).map(([b])=>b),l=Object.create(null),a=[],c=new Map(o.map((b,I)=>[b,I])),u=-1,d=!1,f=b=>{if(P(l,b))return l[b];let I=t[b];if(!Se(I))return P(i,b)?i[b]:void 0;let E=a.indexOf(b);if(E>=0){let A=[...a.slice(E),b].join(" -> ");throw new Error(`Computed variable cycle detected: ${A}`)}a.push(b);try{let A=Xl(I.computed,h,b);return Vi(b,I.type,A),Sr(l,b,A),A}finally{a.pop()}},p=b=>{if(P(l,b))return l[b];let I=t[b];if(!Se(I))return P(i,b)?i[b]:void 0;let E=c.get(b);if(r&&!d&&E!==void 0&&E>u){d=!0;try{for(let A=u+1;A<=E;A+=1)f(o[A]),u=A}finally{d=!1}return l[b]}return f(b)},g=new Proxy({},{get:(b,I)=>{if(typeof I=="string")return p(I)},has:(b,I)=>typeof I=="string"&&(P(i,I)||s.includes(I)),ownKeys:()=>[...new Set([...Object.keys(i),...s])],getOwnPropertyDescriptor:(b,I)=>{if(!(typeof I!="string"||!P(i,I)&&!s.includes(I)))return{enumerable:!0,configurable:!0}}}),h={variables:g,runtime:n,resolveVariable:p};return r?(s.forEach(b=>{p(b)}),{...i,...l}):g},au=({variables:e={},runtime:n={},variableConfigs:t,projectData:r}={})=>{let o=t??r?.resources?.variables??{};return an(o),Bn({variables:e,runtime:n,variableConfigs:o,eager:!0})},Ct=e=>{let n={},t={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{if(Se(o))return;let i=Ml(o,r);o.scope==="context"?Sr(n,r,i):Sr(t,r,i)}),{contextVariableDefaultValues:n,globalVariablesDefaultValues:t}):{contextVariableDefaultValues:n,globalVariablesDefaultValues:t}},Gn=(e,n)=>{let t=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${n}`);if(!t.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${n}. Expected one of: ${t.join(", ")}`)},_t=(e,n,t)=>{let r={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=r[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${t}`);if(!Object.values(r).flat().includes(n))throw new Error(`Unknown operation: ${n}`);if(!o.includes(n))throw new Error(`Operation "${n}" is not valid for variable "${t}" of type "${e}". Valid operations: ${o.join(", ")}`)},cu=2,Ci=12,Bi=(e=cu)=>{if(!Number.isInteger(e)||e<0||e>Ci)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${Ci}.`);return e},lu=(e,n)=>{let t=10**n;return Math.round((e+Number.EPSILON)*t)/t},xt=e=>typeof e=="number"&&Number.isFinite(e),Or=(e,n,t,r,o={})=>{if(e==="number"){if(n==="set"&&!xt(t))throw new Error(`Operation "set" requires value to be a number for variable "${r}".`);if(n==="multiply"&&!xt(t))throw new Error(`Operation "multiply" requires value to be a number for variable "${r}".`);if(n==="divide"&&!xt(t))throw new Error(`Operation "divide" requires value to be a number for variable "${r}".`);if(n==="divide"){if(t===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${r}".`);Bi(o.roundTo)}}},kt=(e,n,t,r={})=>{let o=(s,l,a)=>{let c=s??l;if(!xt(c))throw new Error(`Operation "${n}" requires ${a} to be a number.`);return c},i=s=>{let l=o(s,void 0,"value");if(l===0)throw new Error(`Operation "${n}" requires value to be a non-zero number.`);return l};switch(n){case"set":return t;case"multiply":return o(e,1,"current value")*o(t,void 0,"value");case"divide":return lu(o(e,0,"current value")/i(t),Bi(r.roundTo));case"increment":return o(e,0,"current value")+o(t,1,"value");case"decrement":return o(e,0,"current value")-o(t,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${n}`)}};var $r=(e,n="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let t=new Date(e),r=s=>String(s).padStart(2,"0"),o=String(t.getFullYear()),i={DD:r(t.getDate()),MM:r(t.getMonth()+1),MMM:Dl[t.getMonth()],YYYY:o,YY:o.slice(-2),HH:r(t.getHours()),mm:r(t.getMinutes()),ss:r(t.getSeconds())};return n.replace(/YYYY|MMM|YY|MM|DD|HH|mm|ss/g,s=>i[s])},uu=(e,n)=>{let t=i=>i?.ui,r=t(e),o=t(n);return JSON.stringify(r)===JSON.stringify(o)?null:r&&!o?{changeType:"delete",data:e}:o&&!r?{changeType:"add",data:n}:o&&r?{changeType:"update",data:n}:null},Mn=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,du=(e,n)=>{let t=e?.character?.sprite,r=n?.character?.sprite,o=Mn(t)?t:void 0,i=Mn(r)?r:void 0;return JSON.stringify(o)===JSON.stringify(i)?null:o&&!i?{changeType:"delete",data:o}:i&&!o?{changeType:"add",data:i}:i&&o?{changeType:"update",data:i}:null},_i=e=>{if(e?.resourceId===void 0)return;let n={resourceId:e.resourceId};e.transformId!==void 0&&(n.transformId=e.transformId);for(let t of["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"])e[t]!==void 0&&(n[t]=e[t]);for(let t of["animationName","animationSpeed","loop"])e[t]!==void 0&&(n[t]=e[t]);return n},ki=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},Oi=(e,n)=>n&&!e?{changeType:"add",data:n}:e&&!n?{changeType:"delete",data:e}:e&&n&&JSON.stringify(e)!==JSON.stringify(n)?{changeType:"update",data:n}:null,fu=(e,n)=>{let t={},r=Oi(_i(e),_i(n)),o=Oi(ki(e),ki(n));return r&&(t.resource=r),o&&(t.color=o),Object.keys(t).length>0?t:null},Tr=(e={},n={})=>{let t={},r=["sfx","voice"],o=a=>{let c=e[a],u=n[a];u&&!c?t[a]={changeType:"add",data:u}:c&&!u?r.includes(a)||(t[a]={changeType:"delete",data:c}):c&&u&&JSON.stringify(c)!==JSON.stringify(u)&&(t[a]={changeType:"update",data:u})},i=fu(e.background,n.background);i&&(t.background=i),o("screen"),o("bgm"),o("voice");let s=uu(e.dialogue,n.dialogue);s&&(t.dialogue=s);let l=du(e.dialogue,n.dialogue);return l&&(t.dialogueSprite=l),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),t},Lr=(e={})=>{let n=structuredClone(e);n.background&&(n.background.animations?.playback?.continuity!=="persistent"&&delete n.background.animations,!n.background.resourceId&&!n.background.colorId&&delete n.background);let t=o=>{n[o]&&(delete n[o].animations,Object.keys(n[o]).length===0&&delete n[o])};t("layout"),t("choice"),t("form"),t("screen"),n.dialogue?.ui&&(delete n.dialogue.ui.animations,Object.keys(n.dialogue.ui).length===0&&delete n.dialogue.ui,Object.keys(n.dialogue).length===0&&delete n.dialogue),n.dialogue?.character?.sprite&&(delete n.dialogue.character.sprite.animations,Object.keys(n.dialogue.character.sprite).length===0&&delete n.dialogue.character.sprite,Object.keys(n.dialogue.character).length===0&&delete n.dialogue.character,Object.keys(n.dialogue).length===0&&delete n.dialogue);let r=(o,i)=>{let s=n[o]?.items;Array.isArray(s)&&(n[o].items=s.map(l=>{let a={...l};return delete a.animations,i(a)?a:null}).filter(Boolean),n[o].items.length===0&&delete n[o])};return r("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),r("visual",o=>o.resourceId||o.transformId),n},pu=(e,n)=>{if(!e||!n)return;let t=e;for(let r of n.split(".")){if(t==null||!(r in Object(t)))return;t=t[r]}return t},mu=(e,n)=>{if(typeof e!="string")return e;if(e==="_event"){if(n==null)throw new Error('Action template binding "_event" requires event context "_event".');return n}if(!e.startsWith("_event."))return e;if(n==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let t=e.slice(7),r=pu(n,t);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},gu={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"])},hu=(e,n)=>{let t=e[e.length-1];return t?gu[t]?.has(n)===!0:!1},_r=(e,n,t=[])=>Array.isArray(e)?e.map(r=>_r(r,n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,hu(t,r)?o:_r(o,n,[...t,r])])):typeof e=="string"?e==="_event"||e.startsWith("_event.")?mu(e,n._event):on(e,n):e,Pr=(e,n)=>{if(!n)return e;if(Object.prototype.hasOwnProperty.call(n,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');return _r(e,n)};var K=e=>structuredClone(ie(e)?Ue(e):e),U=(e,n)=>Object.prototype.hasOwnProperty.call(e,n),Gi=e=>e?.animations?.playback?.continuity==="persistent",j=(e,n)=>U(e??{},n)&&e[n]!==void 0,zn=(e,n)=>e?!n(e)&&e.animations?{animationsOnly:!0,state:{animations:K(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},yu=e=>j(e,"opacity")||j(e,"blur"),Ki=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Ji=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Nr=["animationName","animationSpeed","loop"],bu=e=>Ki.some(n=>j(e,n)),Xi=e=>e?.text&&j(e.text,"content")&&j(e.text,"textStyleId"),Qi=e=>j(e,"text"),Iu=(e,n)=>e.resourceId?!0:Xi(e)?!n?.text:!1,wu=(e,n)=>{let t={...K(e),...n};return n.text&&e.text&&(t.text={...K(e.text),...K(n.text)}),t},Au=(e,n)=>{if(Qi(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!Xi(e)&&!n?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},zi=e=>Ji.some(n=>j(e,n)),qi=e=>Nr.some(n=>j(e,n)),Eu=(e,n,{hasAuthoredTransformId:t=!1}={})=>{if(!n)return e;for(let r of Ji)!t&&!j(e,r)&&j(n,r)&&(e[r]=n[r]),U(e,r)&&e[r]===void 0&&delete e[r];return e},Zi=(e,n,t)=>{let r=e[t];return r?.id===n?.id?r:e.find(o=>o.id===n?.id)},xu=(e,n)=>{if(!n)return e;for(let t of Ki)!j(e,t)&&j(n,t)&&(e[t]=n[t]),U(e,t)&&e[t]===void 0&&delete e[t];return e},vu=(e,n)=>(n&&(!j(e,"opacity")&&j(n,"opacity")&&(e.opacity=n.opacity),!j(e,"blur")&&j(n,"blur")&&(e.blur=K(n.blur)),U(e,"opacity")&&e.opacity===void 0&&delete e.opacity,U(e,"blur")&&e.blur===void 0&&delete e.blur),e),es=(e,n,t=[],{hasPatchFn:r=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,l)=>{let a=Zi(t,s,l),c=n(s,a),u=yu(s),d=bu(s),f=r(s),p=U(s,"animations"),g=K(s);return!c&&(u||d||f)&&a&&(g=o?o(a,g):{...K(a),...g},p||delete g.animations),vu(xu(g,a),a)}).filter(s=>n(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},Su=e=>{if(e){if(e.character&&U(e.character,"name"))return e.character.name;if(U(e,"characterName"))return e.characterName}},ns=e=>!!e?.character&&U(e.character,"sprite"),Ru=e=>{let n={},t=!1,r=Su(e);return r!==void 0&&(n.name=r,t=!0),ns(e)&&(n.sprite=K(e.character.sprite),t=!0),t?n:void 0},Yi=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Hi=({dialogueState:e,dialogueAction:n,persistCharacter:t})=>U(n,"persistSprite")?n.persistSprite===!0:U(e,"persistSprite")?e.persistSprite===!0:t&&!U(n,"characterId"),Wi=({previousCharacter:e,characterFields:n,hasCharacterId:t,persistCharacter:r,persistSprite:o,hasExplicitPersistSprite:i,isAppendingAdvDialogueContent:s})=>{let l={},a=e??{},c=n??{},u=s&&!t,d=u&&!i;return U(c,"name")?l.name=c.name:(r&&!t||u)&&U(a,"name")&&(l.name=K(a.name)),U(c,"sprite")?l.sprite=K(c.sprite):(o||d)&&U(a,"sprite")&&(l.sprite=K(a.sprite)),Object.keys(l).length>0?l:void 0},Cu=({dialogueState:e,content:n,append:t=!1})=>{if(!t||!Array.isArray(n)){e.content=n,delete e.initialRevealedContent;return}let r=Array.isArray(e.content)?e.content:[];r.length>0?e.initialRevealedContent=r.map(o=>K(o)):delete e.initialRevealedContent,e.content=[...r,...n]},_u=()=>({}),ku=(e,n)=>{if(!n.screen)return;let t=j(n.screen,"opacity"),r=j(n.screen,"blur"),o=U(n.screen,"animations");if(!t&&!r){o||delete e.screen;return}let i=e.screen,s={};if(t?s.opacity=n.screen.opacity:j(i,"opacity")&&(s.opacity=i.opacity),r?s.blur=K(n.screen.blur):j(i,"blur")&&(s.blur=K(i.blur)),U(s,"opacity")&&s.opacity===void 0&&delete s.opacity,U(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},Ou=(e,n)=>{if(n.background){let t=j(n.background,"resourceId"),r=j(n.background,"colorId"),o=j(n.background,"opacity"),i=j(n.background,"blur"),s=j(n.background,"transformId"),l=zi(n.background),a=qi(n.background),{animationsOnly:c,state:u}=zn(n.background,p=>j(p,"resourceId")||j(p,"colorId")||j(p,"opacity")||j(p,"blur")||j(p,"transformId")||zi(p)||qi(p));if(c){e.background=e.background?{...K(e.background),...u}:u;return}if(!t&&!r&&!o&&!i&&!s&&!l&&!a){delete e.background;return}let d=e.background,f=K(n.background);if(!t&&d?.resourceId){f.resourceId=d.resourceId,!U(f,"transformId")&&d.transformId&&(f.transformId=d.transformId);for(let p of Nr)!j(f,p)&&j(d,p)&&(f[p]=d[p])}Eu(f,d,{hasAuthoredTransformId:s}),!r&&d?.colorId&&(f.colorId=d.colorId),!o&&j(d,"opacity")&&(f.opacity=d.opacity),!i&&j(d,"blur")&&(f.blur=K(d.blur)),U(f,"resourceId")&&f.resourceId===void 0&&delete f.resourceId,U(f,"colorId")&&f.colorId===void 0&&delete f.colorId,U(f,"animations")&&f.animations===void 0&&delete f.animations,U(f,"transformId")&&f.transformId===void 0&&delete f.transformId,U(f,"opacity")&&f.opacity===void 0&&delete f.opacity,U(f,"blur")&&f.blur===void 0&&delete f.blur;for(let p of Nr)U(f,p)&&f[p]===void 0&&delete f[p];if(!f.resourceId&&!f.colorId){delete e.background;return}d?.resourceId===f.resourceId&&d?.transformId===f.transformId&&!U(f,"animations")&&Gi(d)&&(f.animations=K(d.animations)),e.background=f}else e.background?.animations&&!Gi(e.background)&&(e.background.animations={})},$u=(e,n)=>{if(!n.dialogue){if(e.dialogue&&(Yi(e.dialogue),e.dialogue.mode==="adv")){e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,delete e.dialogue.textSpeed;let u=e.dialogue.persistCharacter===!0,d=Hi({dialogueState:e.dialogue,dialogueAction:{},persistCharacter:u});u||delete e.dialogue.characterId,e.dialogue.character=Wi({previousCharacter:e.dialogue.character,characterFields:{},hasCharacterId:!1,persistCharacter:u,persistSprite:d,hasExplicitPersistSprite:!1,isAppendingAdvDialogueContent:!1}),e.dialogue.character||delete e.dialogue.character}return}e.dialogue||(e.dialogue={});let t=e.dialogue.mode;if(n.dialogue.ui){let{animationsOnly:u,state:d}=zn(n.dialogue.ui,f=>!!f.resourceId);u?e.dialogue.ui={...e.dialogue.ui,...d}:e.dialogue.ui={...n.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});n.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),n.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let r=n.dialogue.append===!0&&t!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(n.dialogue.content);n.dialogue.content!==void 0&&Cu({dialogueState:e.dialogue,content:n.dialogue.content,append:r}),U(n.dialogue,"textSpeed")?e.dialogue.textSpeed=n.dialogue.textSpeed:delete e.dialogue.textSpeed;let o=U(n.dialogue,"persistCharacter")?n.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=Hi({dialogueState:e.dialogue,dialogueAction:n.dialogue,persistCharacter:o});U(n.dialogue,"persistSprite")&&(e.dialogue.persistSprite=i);let s=U(n.dialogue,"characterId"),l=Ru(n.dialogue),a=ns(n.dialogue);s?n.dialogue.characterId?e.dialogue.characterId=n.dialogue.characterId:delete e.dialogue.characterId:!o&&!r&&delete e.dialogue.characterId;let c=Wi({previousCharacter:e.dialogue.character,characterFields:l,hasCharacterId:s,persistCharacter:o,persistSprite:i,hasExplicitPersistSprite:U(n.dialogue,"persistSprite"),isAppendingAdvDialogueContent:r});if(c?e.dialogue.character=c:delete e.dialogue.character,a||Yi(e.dialogue),n.dialogue.clear){delete e.dialogue;return}if(n.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&n.dialogue.content!==void 0){let u={content:n.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.textSpeed!==void 0&&(u.textSpeed=e.dialogue.textSpeed),e.dialogue.character&&(u.character=K(e.dialogue.character)),e.dialogue.lines.push(u)}},Tu=(e,n)=>{if(n.sfx){let t=Array.isArray(n.sfx.items)&&n.sfx.items.length>0,r=Array.isArray(n.sfx.channels)&&n.sfx.channels.length>0;if(!t&&!r){delete e.sfx;return}e.sfx=K(n.sfx)}else e.sfx&&delete e.sfx},Lu=(e,n)=>{if(n.bgm){let t=Array.isArray(n.bgm.sounds);if(!n.bgm.resourceId&&!t||t&&n.bgm.sounds.length===0){e.bgm=void 0;return}e.bgm=K(n.bgm),n.bgm.resourceId&&(e.bgm.loop=n.bgm.loop??!0)}},Pu=(e,n)=>{if(n.visual){let t=e.visual?.items||[];n.visual.items?.forEach((i,s)=>{Au(i,Zi(t,i,s))});let{hasValidItems:r,processedItems:o}=es(n.visual.items,Iu,t,{hasPatchFn:Qi,mergeItemFn:wu});r?e.visual={items:o}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(t=>t.animations?{...t,animations:{}}:t))},Nu=(e,n)=>{if(!n.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:t,processedItems:r}=es(n.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);t?e.character={items:r}:delete e.character},Du=(e,n)=>{n.animation?e.animation=n.animation:e.animation&&delete e.animation},Mu=(e,n)=>{if(n.layout){let{animationsOnly:t,state:r}=zn(n.layout,o=>!!o.resourceId);if(t){e.layout=r;return}if(!n.layout.resourceId){delete e.layout;return}e.layout=n.layout}else e.layout&&delete e.layout},Vu=(e,n)=>{if(n.choice){let{animationsOnly:t,state:r}=zn(n.choice,o=>!!o.resourceId);if(t){e.choice={...e.choice,...r};return}if(!n.choice.resourceId){delete e.choice;return}e.choice=n.choice}else e.choice&&delete e.choice},ju=(e,n)=>{if(n.form){let{animationsOnly:t,state:r}=zn(n.form,o=>!!o.resourceId);if(t){e.form={...e.form,...r};return}if(!n.form.resourceId){delete e.form;return}e.form=K(n.form)}else e.form&&delete e.form},Fu=(e,n)=>{if(n.control){if(!n.control.resourceId){delete e.control;return}e.control=n.control}},Uu=(e,n)=>{if(n.voice){let t=Array.isArray(n.voice.sounds);if(!n.voice.resourceId&&!t||t&&n.voice.sounds.length===0){delete e.voice;return}e.voice=K(n.voice)}else e.voice&&delete e.voice},Bu=(e,n)=>{n.cleanAll&&Object.keys(e).forEach(t=>{delete e[t]})},cn=e=>St(_u,[Bu,ku,Ou,Tu,Lu,Pu,$u,Nu,Du,Mu,Vu,ju,Fu,Uu])(e);var En=(e,n)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let t=on(e,n);return t&&typeof t=="object"?e:t};var Gu=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},autoForwardSpeed:{source:"global.autoForwardSpeed"},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"}}),ln=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,autoForwardSpeed:1,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),qn=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),ts=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",autoForwardSpeed:"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"}),Dr=Object.freeze(["dialogueTextSpeed","autoForwardDelay","autoForwardSpeed","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Mr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),zu=(e,n)=>{if(n.startsWith("global.")){let t=n.slice(7);return e?.global?.[t]}if(n.startsWith("context.runtime.")){let t=n.slice(16),r=Array.isArray(e?.contexts)?e.contexts:[];return r[r.length-1]?.runtime?.[t]}},un=e=>Object.fromEntries(Object.entries(Gu).map(([n,t])=>{let r=zu(e,t.source),o=r!==void 0?r:ln[n]??qn[n];return[n,o]})),Ye=(e,n)=>un(e)[n],rs=(e={})=>Object.fromEntries(Dr.map(n=>[n,e[n]??ln[n]]));var xn=Object.freeze({VISUAL_BEHIND_BACKGROUND:10,BACKGROUND:20,VISUAL_BEHIND_CHARACTER:30,CHARACTER:40,VISUAL_BEHIND_DIALOGUE:50,DIALOGUE:60,VISUAL_BEHIND_CHOICE:70,CHOICE:80,VISUAL_FOREGROUND:90}),Ne=Object.freeze({BEHIND_BACKGROUND:xn.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:xn.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:xn.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:xn.VISUAL_BEHIND_CHOICE,FOREGROUND:xn.VISUAL_FOREGROUND}),Vr=Ne.BEHIND_DIALOGUE,jr=Object.freeze(Object.values(Ne).sort((e,n)=>e-n));var qu={__arrayOrEmpty:e=>Array.isArray(e)?e:[],objectValues:e=>Object.entries(e).map(([n,t])=>({id:n,...t})),formatDate:$r},Yu=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+?)(?::)?$/,Yn=e=>Array.isArray(e)?e.map(n=>{if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).length!==1)return Yn(n);let[t]=Object.keys(n),r=Yu.exec(t);if(!r)return Yn(n);let[,o,i,s]=r,l=`$for ${o}${i?`, ${i}`:""} in __arrayOrEmpty(${s.trim()})`,a=Array.isArray(n[t])?n[t]:[];return{[l]:Yn(a)}}):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).map(([n,t])=>[n,Yn(t)])),Me=(e,n)=>{let t={functions:qu};return on(Yn(e),n,t)},to=({animationType:e,animationId:n,animationPath:t})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${t}] Animation "${n}" has unsupported type "${e}". Use "update" or "transition".`)},Hu=({id:e,targetId:n,animation:t,playback:r,animationPath:o="animation"})=>{let i=structuredClone(t);if(to({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=n,r!==void 0){let s=Xu(r,`${o}.playback`);if(s!==void 0){let l=s.loop===!0?Is(i):null;if(s.loop===!0&&i.type!=="update")throw new Error(`[${o}.playback] playback.loop is only supported for type "update".`);if(s.loop===!0&&i.complete!==void 0)throw new Error(`[${o}.playback] animation.complete is not allowed when playback.loop is true because a loop never completes.`);if(s.loop===!0&&(!Number.isFinite(l)||l<=0))throw new Error(`[${o}.playback] playback.loop requires an animation with a finite duration greater than 0.`);i.playback=s}}return i},Wu=(e,{animationId:n="animation",animationPath:t="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return to({animationType:e.type,animationId:n,animationPath:t}),e.type},Ku=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Ju=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Xu=(e,n="animation.playback")=>{if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`[${n}] playback must be an object.`);if(e.continuity!==void 0&&e.continuity!=="render"&&e.continuity!=="persistent")throw new Error(`[${n}] playback.continuity must be "render" or "persistent".`);if(e.speed!==void 0&&(typeof e.speed!="number"||!Number.isFinite(e.speed)||e.speed<=0))throw new Error(`[${n}] playback.speed must be a finite number greater than 0.`);if(e.loop!==void 0&&typeof e.loop!="boolean")throw new Error(`[${n}] playback.loop must be a boolean.`);let t={};return e.continuity!==void 0&&(t.continuity=e.continuity),e.speed!==void 0&&e.speed!==1&&(t.speed=e.speed),e.loop===!0&&(t.loop=!0),Object.keys(t).length>0?t:void 0},Qu=e=>{let n=e?.playback?.speed;return typeof n=="number"&&Number.isFinite(n)&&n>0?n:1},dn=(e,n)=>Object.prototype.hasOwnProperty.call(e,n),hs=e=>e?.playback?.continuity==="persistent",Hr=e=>Array.isArray(e)?e.map(Hr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((n,t)=>(n[t]=Hr(e[t]),n),{}),Lt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let n=structuredClone(e);return n.playback&&(delete n.playback.continuity,n.playback.speed===1&&delete n.playback.speed,Object.keys(n.playback).length===0&&delete n.playback),JSON.stringify(Hr(n))},ys=(e=[])=>e.filter(n=>hs(n)).map(n=>structuredClone(n)),bs=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((n,t)=>{let r=typeof t?.duration=="number"&&Number.isFinite(t.duration)?t.duration:0;return n+r},0):0,Fr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((n,t)=>Math.max(n,bs(t)),0),Is=e=>Math.max(Fr(e?.tween),Fr(e?.prev?.tween),Fr(e?.next?.tween),bs(e?.mask?.progress)),ws=e=>!e||typeof e!="object"||Array.isArray(e)?0:e.playback?.loop===!0?Number.POSITIVE_INFINITY:Is(e)/Qu(e),Zu=e=>e.some(n=>n?.playback?.loop===!0),os=({animationInstances:e,activePersistentAnimations:n})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(n)||n.length===0)return!1;let t=new Set(n.map(Lt).filter(Boolean));return e.some(r=>{if(!hs(r))return!1;let o=Lt(r);return o?t.has(o):!1})},ke=({animationInstances:e,isLineCompleted:n,skipTransitionsAndAnimations:t,activePersistentAnimations:r,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||t?!1:Zu(e)||i&&!n||os({animationInstances:e,activePersistentAnimations:r})?!0:i?!1:os({animationInstances:e,activePersistentAnimations:o}),ed=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(n=>e[n]!==void 0),nd=(e,n)=>{if(ed(e))throw new Error(`[${n}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},td=({resources:e,animationId:n,playback:t,instanceId:r,targetId:o,animationPath:i="animation"})=>{if(!n||!o)return!1;let s=e?.animations?.[n];return s?Hu({id:r,targetId:o,animation:s,playback:t,animationPath:i}):null},rd=(e,{defaultTargetId:n,defaultId:t,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return to({animationType:o.type,animationId:o.id??t,animationPath:r}),o.id??=t,o.targetId??=n,o},ro=({animations:e,transitions:n,defaultTargetId:t,idPrefix:r,animationPathPrefix:o=r})=>{n.forEach((i,s)=>{e.push(rd(i,{defaultTargetId:t,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Wr=(e,n)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(t=>t===null||typeof t!="object"||Array.isArray(t)))throw new Error(`${n} must be an array of objects`);return e},od=({content:e,path:n,variables:t})=>Wr(e,n).reduce((r,o)=>{let i=En(o.text,{variables:t});return r+`${i??""}`.length},0),is=(e=[])=>{let n=new Map;for(let t of e)t?.id&&n.set(t.id,(n.get(t.id)??0)+1);return new Set(Array.from(n.entries()).filter(([,t])=>t>1).map(([t])=>t))},Ot=(e,n=0,t=new Set)=>{if(!t.has(e?.id))return`character-container-${e.id}`;let r=e?.sprites?.map(({resourceId:o})=>o)||[];return r.length===0?`character-container-${e.id}`:`character-container-${e.id}-${n}-${r.join("-")}`},Hn=(e,n)=>{if(!n.transformId)throw new Error(`Visual item "${n.id}" requires transformId`);let t=e.transforms?.[n.transformId];if(!t)throw new Error(`Transform "${n.transformId}" not found for visual item "${n.id}"`);return t},id=(e,n={})=>{if(!n?.transformId)return;let t=e.transforms?.[n.transformId];if(!t)throw new Error(`Transform "${n.transformId}" not found for background`);return t},sd=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],ad=(e={})=>sd.some(n=>dn(e,n)),As=(e={},n)=>{if(n){if(e.images?.[n])return"sprite";if(e.videos?.[n])return"video";if(e.spritesheets?.[n])return"spritesheet-animation";if(e.layouts?.[n])return"container"}},Tt=({resourceId:e,kind:n})=>{if(e)return n?`bg-cg-background-${n}`:`bg-cg-${e}`},cd=(e={})=>e.textStyles||{},ld=(e={})=>e.images||{},ud=.5,dd=(e={},n,t)=>{if(n){if(!e.animations?.[n])throw new Error(`Animation '${n}' not found in spritesheet resource '${t}'`);return n}return Object.keys(e.animations??{})[0]},Es=({id:e,resourceId:n,spritesheet:t,animationName:r,animationSpeed:o,loop:i,transform:s={}}={})=>{let l=dd(t,r,n),a=l?t.animations?.[l]:void 0;if(!a){console.warn(`Spritesheet animation not found: ${n}`);return}return{id:e,type:"spritesheet-animation",...s,width:t.width,height:t.height,src:t.fileId,atlas:t.jsonData,playback:{frames:a.frames,animationSpeed:o??a.animationSpeed??ud,loop:i??a.loop??!0}}},xs=({id:e,item:n,resources:t={}}={})=>{let r=t.images?.[n.resourceId];if(r)return{type:"sprite",id:e,src:r.fileId,width:r.width,height:r.height,x:0,y:0};let o=t.spritesheets?.[n.resourceId];if(o)return Es({id:e,resourceId:n.resourceId,spritesheet:o,animationName:n.animationName,animationSpeed:n.animationSpeed,loop:n.loop,transform:{x:0,y:0}});console.warn(`Character sprite resource not found: ${n.resourceId}`)},fd=(e={})=>e.colors||{},pd=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Kn=(e,n)=>e==="root"?`${n}`:`${e}.${n}`,Rn=(e,n,t)=>{if(typeof e!="string"||e.length===0)throw new Error(`${t} at "${n}" must resolve to a non-empty string`)},Ur=(e,n,t)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${n} for text style "${t}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${n} for text style "${t}" must be a number between 0 and 1`);return e},Br=(e,n,t,r,{minimum:o}={})=>{if(e===void 0)return r;if(typeof e!="number"||!Number.isFinite(e)||o!==void 0&&e<o){let i=o===void 0?"a finite number":`a finite number >= ${o}`;throw new Error(`shadow.${n} for text style "${t}" must be ${i}`)}return e},Dt=(e,n)=>{if(typeof e!="string"||!pd.test(e))throw new Error(`${n} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(t=>t.repeat(2)).join("")}`:e},ss=(e,n,t)=>{let r=Dt(e,t);if(n===1)return r;let o=Number.parseInt(r.slice(1,3),16),i=Number.parseInt(r.slice(3,5),16),s=Number.parseInt(r.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${n})`},md=(e={},n)=>{let t=cd(e)?.[n];if(!t)throw new Error(`Text style "${n}" not found`);let o=(Array.isArray(t.fontId)?t.fontId:[t.fontId]).map(a=>{let c=e.fonts?.[a];if(!c)throw new Error(`Font "${a}" not found for text style "${n}"`);return c.fileId}),i=e.colors?.[t.colorId];if(!i)throw new Error(`Color "${t.colorId}" not found for text style "${n}"`);let s=Ur(t.colorAlpha,"colorAlpha",n),l={fontFamily:Array.isArray(t.fontId)?o.join(", "):o[0],fontSize:t.fontSize??16,fontWeight:t.fontWeight??"400",fontStyle:t.fontStyle??"normal",lineHeight:t.lineHeight??1.2,fill:ss(i.hex,s,`Color "${t.colorId}" for text style "${n}"`)};if(t.align!==void 0&&(l.align=t.align),t.wordWrap!==void 0&&(l.wordWrap=t.wordWrap),t.breakWords!==void 0&&(l.breakWords=t.breakWords),t.wordWrapWidth!==void 0&&(l.wordWrapWidth=t.wordWrapWidth),t.strokeColorId){let a=e.colors?.[t.strokeColorId];if(!a)throw new Error(`Stroke color "${t.strokeColorId}" not found for text style "${n}"`);let c=Ur(t.strokeAlpha,"strokeAlpha",n);l.strokeColor=ss(a.hex,c,`Stroke color "${t.strokeColorId}" for text style "${n}"`)}else if(t.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${n}" requires strokeColorId`);if(t.strokeWidth!==void 0&&(l.strokeWidth=t.strokeWidth),t.shadow!==void 0){let a=e.colors?.[t.shadow.colorId];if(!a)throw new Error(`Shadow color "${t.shadow.colorId}" not found for text style "${n}"`);l.shadow={color:Dt(a.hex,`Shadow color "${t.shadow.colorId}" for text style "${n}"`),alpha:Ur(t.shadow.alpha,"shadow.alpha",n),blur:Br(t.shadow.blur,"blur",n,0,{minimum:0}),offsetX:Br(t.shadow.offsetX,"offsetX",n,2),offsetY:Br(t.shadow.offsetY,"offsetY",n,2)}}return l},Kr=(e,n={},t="root")=>{if(Array.isArray(e))return e.map((o,i)=>Kr(o,n,`${t}[${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 "${t}". Use textStyleId instead`);let r={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(r[o]=Kr(i,n,Kn(t,o)));return e.textStyleId!==void 0&&(Rn(e.textStyleId,t,"textStyleId"),r.textStyle=md(n,e.textStyleId)),r},oo=(e={},n)=>{let t=fd(e)?.[n];if(!t)throw new Error(`Color "${n}" not found`);return Dt(t.hex,`Color "${n}"`)},vs=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Gr=(e,n,t)=>{let r=e?.[n];if(!(!r||typeof r!="object"||Array.isArray(r))&&Object.prototype.hasOwnProperty.call(r,"fill"))throw new Error(`Inline ${n}.fill is not allowed in rect layout elements at "${t}". Use ${vs(`${n}.fill`)} instead`)},gd=(e,n={},t="root")=>{if(Array.isArray(e))return e.map((o,i)=>Jn(o,n,`${t}[${i}]`));if(!e||typeof e!="object")return e;let r={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(r[o]=Jn(i,n,Kn(t,o)));return e.colorId!==void 0&&(Rn(e.colorId,t,"colorId"),r.fill=oo(n,e.colorId)),r},Jn=(e,n={},t="root")=>{if(Array.isArray(e))return e.map((o,i)=>Jn(o,n,`${t}[${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 "${t}". Use ${vs("fill")} instead`);Gr(e,"hover",t),Gr(e,"click",t),Gr(e,"rightClick",t)}let r={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){r[o]=gd(i,n,Kn(t,o));continue}r[o]=Jn(i,n,Kn(t,o))}return e.type==="rect"&&e.colorId!==void 0&&(Rn(e.colorId,t,"colorId"),r.fill=oo(n,e.colorId)),r},zr=(e={},n)=>{let t=ld(e)?.[n];return t||null},Ss=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",as=(e,n,t,r)=>{let o=e?.[n];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,r))throw new Error(`Inline ${n}.${r} is not allowed in sprite layout elements at "${t}". Use ${Ss(`${n}.${r}`)} instead`)},cs=(e,n,t)=>{let r=e[n];e[n]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:t}},Jr=(e,n={},t="root")=>{if(Array.isArray(e))return e.map((o,i)=>Jr(o,n,`${t}[${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 "${t}". Use ${Ss(o)} instead`);as(e,"hover",t,"src"),as(e,"click",t,"src")}let r={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(r[o]=Jr(i,n,Kn(t,o)));if(e.type==="sprite"&&e.imageId!==void 0){Rn(e.imageId,t,"imageId");let o=zr(n,e.imageId),i=o?.fileId??e.imageId;r.src=i,r.width===void 0&&o?.width!==void 0&&(r.width=o.width),r.height===void 0&&o?.height!==void 0&&(r.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(Rn(e.hoverImageId,t,"hoverImageId"),cs(r,"hover",zr(n,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(Rn(e.clickImageId,t,"clickImageId"),cs(r,"click",zr(n,e.clickImageId)?.fileId??e.clickImageId)),r},io=(e,n={},t="root")=>Jr(Jn(Kr(e,n,t),n,t),n,t),Ve=io,fn=(e=[])=>e.find(n=>n.id==="story"),hd="#000000",Xr="bg-cg-background-color",yd=({resources:e={},background:n={},screen:t})=>n?.colorId===void 0?Dt(t?.backgroundColor??hd,"screen.backgroundColor"):oo(e,n.colorId),Rs=(e={})=>{if(dn(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},bd=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},ls=(e={},{includeDefaultAlpha:n=!1}={})=>{let t=Rs(e),r=bd(e),o={};return(n||t!==void 0)&&(o.alpha=t??1),r&&(o.blur=r),o},Id=(e={})=>{if(dn(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},wd=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Cs=(e={})=>{let n=Id(e),t=wd(e),r={};return n!==void 0&&(r.alpha=n),t&&(r.blur=t),r},Sn=(e={})=>Cs(e),De=(e={},n={})=>{let t={x:n.x??e.x,y:n.y??e.y,anchorX:n.anchorX??e.anchorX,anchorY:n.anchorY??e.anchorY,rotation:n.rotation??e.rotation,scaleX:n.scaleX??e.scaleX,scaleY:n.scaleY??e.scaleY},r=n.originX??e.originX,o=n.originY??e.originY;return r!==void 0&&(t.originX=r),o!==void 0&&(t.originY=o),t},Ad=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],so=(e={})=>e.text&&dn(e.text,"content")&&dn(e.text,"textStyleId"),us=(e={})=>{if(e.resourceId)return e.resourceId;if(so(e))return"text"},ds=(e,n={})=>typeof e=="string"?n.images?.[e]?.fileId??e:!e||typeof e!="object"||Array.isArray(e)?e:e.imageId?n.images?.[e.imageId]?.fileId??e.imageId:Array.isArray(e.items)?{...e,items:e.items.map(t=>{if(typeof t=="string")return n.images?.[t]?.fileId??t;if(!t||typeof t!="object"||Array.isArray(t))return t;if(t.imageId){let{imageId:r,...o}=t;return{...o,src:n.images?.[r]?.fileId??r}}return typeof t.src=="string"?{...t,src:n.images?.[t.src]?.fileId??t.src}:t})}:e,Ed=({item:e,particle:n,resources:t})=>{let r=Hn(t,e),o=structuredClone(n),i=o.modules?.appearance?.texture;i!==void 0&&(o.modules.appearance.texture=ds(i,t)),o.texture!==void 0&&(o.texture=ds(o.texture,t));let s={id:`visual-${e.id}`,type:"container",children:[{...o,id:`visual-${e.id}-particles`,type:"particles",x:0,y:0}],...De(r,e)};return Object.assign(s,Sn(e)),s},xd=e=>{if(e.text){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!so(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let n of Ad)if(dn(e.text,n))throw new Error(`Visual item "${e.id}" text.${n} is reserved for the visual item`)}},vd=({resources:e,background:n,screen:t={width:1920,height:1080},includeOpacity:r=!1})=>{let o={id:Xr,type:"rect",x:0,y:0,width:t?.width??1920,height:t?.height??1080,fill:yd({resources:e,background:n,screen:t})};if(r){let i=Rs(n);i!==void 0&&(o.alpha=i)}return o},Sd=(e={},n)=>n?!!(e.images?.[n]||e.videos?.[n]||e.spritesheets?.[n]||e.layouts?.[n]):!1,fs=({resources:e={},resourceId:n,colorId:t})=>{let r=As(e,n);return n&&(r||t===void 0)?{resourceId:n,targetId:Tt({resourceId:n,kind:r})}:t!==void 0?{resourceId:Xr,targetId:Xr}:{resourceId:void 0,targetId:void 0}},_s=100,He=_s,Rd="channel:bgm",Cd="channel:music-room",_d="music-room:player",kd="channel:voice",Od="default",$d=e=>String(e).replaceAll("%","%25").replaceAll(":","%3A"),Wn=(...e)=>e.map($d).join(":"),Pt=(e,n,t)=>{let r=new Set;e.forEach(({id:o})=>{if(r.has(o)){let i=t?` in ${t}`:"";throw new Error(`Duplicate ${n} id "${o}"${i}.`)}r.add(o)})},Td=(e,n)=>e*n/_s,ks=(e={},n)=>e?.[n]??ln[n],Mt=(e={},n,t=He)=>Td(t,ks(e,n)),Vt=({id:e,volume:n,muted:t,pan:r,loop:o,playback:i,interruption:s,children:l,runtime:a})=>{let c={id:e,type:"audio-channel",volume:n,muted:!!a?.muteAll||(t??!1),pan:r??0,children:l};return o!==void 0&&(c.loop=o),i!==void 0&&(c.playback=structuredClone(i)),s!==void 0&&(c.interruption=s),c},$t=(e,n,t,r)=>e[t]!==void 0?e[t]:n[t]!==void 0?n[t]:r,Ld=["muted","pan","playbackRate","startAt","endAt"],jt=({id:e,sound:n,resource:t,defaultLoop:r=!1})=>{let o={id:e,type:"sound",src:t.fileId,loop:$t(n,t,"loop",r),volume:$t(n,t,"volume",He),startDelayMs:$t(n,t,"startDelayMs",0)};Ld.forEach(s=>{let l=$t(n,t,s,void 0);l!==void 0&&(o[s]=l)}),n.playback!==void 0&&(o.playback=structuredClone(n.playback));let i=o.startAt??0;if(o.endAt!==void 0&&o.endAt!==null&&o.endAt<i)throw new Error(`Sound "${e}" endAt (${o.endAt}) must be greater than or equal to startAt (${i}).`);return o},Re=({variables:e,imageGallery:n,musicRoom:t,sceneReplay:r,runtime:o,saveSlots:i=[],dialogueState:s,includeInactiveAdvDialogue:l=!1,isLineCompleted:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,confirmDialog:g,form:h,historyDialogue:b=[],characters:I={},dialogueUIHidden:E,skipOnlyViewedLines:A,skipTransitionsAndAnimations:$}={})=>{let B={dialogueTextSpeed:o?.dialogueTextSpeed??50,autoForwardDelay:o?.autoForwardDelay??1e3,autoForwardSpeed:o?.autoForwardSpeed??1,skipUnseenText:o?.skipUnseenText??!1,skipTransitionsAndAnimations:o?.skipTransitionsAndAnimations??!1,soundVolume:o?.soundVolume??50,musicVolume:o?.musicVolume??50,muteAll:o?.muteAll??!1,saveLoadPagination:o?.saveLoadPagination??1,menuPage:o?.menuPage??"",menuEntryPoint:o?.menuEntryPoint??"",autoMode:o?.autoMode??c??!1,skipMode:o?.skipMode??u??!1,dialogueUIHidden:o?.dialogueUIHidden??E??!1,isLineCompleted:o?.isLineCompleted??a??!1},L=Vd({dialogueState:s,includeInactiveAdvDialogue:l,characters:I,variables:e,runtime:B}),T={variables:e,imageGallery:n,musicRoom:t,sceneReplay:r,runtime:B,saveSlots:i,isChoiceVisible:d,isFormVisible:f,canRollback:p,confirmDialog:g,form:h,historyDialogue:b,characters:I};return L&&(T.dialogue=L,T.dialogueLines=L.lines),T},ps=100,Nt=(e,n)=>{if(Array.isArray(e))return e.map(r=>Nt(r,n));if(!e||typeof e!="object")return e;let t={...e};return Object.keys(t).forEach(r=>{t[r]=Nt(t[r],n)}),t.type==="text-revealing"?n(t):t},Pd=e=>Nt(e,n=>({...n,revealEffect:"none"})),Nd=e=>Nt(e,n=>{let t=Number(n.speed??n.displaySpeed),r=Number.isFinite(t)?Math.max(t,ps):ps;return{...n,speed:r,...Object.prototype.hasOwnProperty.call(n,"displaySpeed")?{displaySpeed:r}:{}}}),We=(e,{isLineCompleted:n=!1,skipMode:t=!1,skipTransitionsAndAnimations:r=!1}={})=>n||r?Pd(e):t?Nd(e):e,Os=({id:e,screen:n={width:1920,height:1080}})=>({id:e,type:"rect",fill:"transparent",width:n.width,height:n.height,x:0,y:0,click:{payload:{actions:{}}}}),Qr=e=>{if(Array.isArray(e))return e.map(Qr);if(!e||typeof e!="object")return e;let n={};for(let[i,s]of Object.entries(e))n[i]=Qr(s);let t=n.click?.payload;if(!t||typeof t!="object"||Array.isArray(t))return n;let r=t.actions,o=r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"nextLine")?{...r.nextLine,bypassChoice:!0}:void 0;return{...n,click:{...n.click,payload:{...t,bypassChoice:!0,...o?{actions:{...r,nextLine:o}}:{}}}}},Dd=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),ms="submit",qr=(e,n,t={})=>{let r=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},o=r.actions&&typeof r.actions=="object"?r.actions:{},i=t.replaceActions===!0?n:{...o,...n};return{...e||{},payload:{...r,actions:i}}},Zr=(e,n,t={})=>{if(Array.isArray(e))return e.map(c=>Zr(c,n,t));if(!e||typeof e!="object")return e;let r=typeof e.type=="string",o=r&&e.formRole===ms,i=r&&t.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},l={};for(let[c,u]of Object.entries(e))l[c]=Zr(u,n,c==="children"?s:{});let a=l;if(a.type==="input"&&typeof a.field=="string"){let c=n?.fields?.[a.field];if(c){let u={updateFormField:{formKey:n.key,field:c.id,value:"_event.value"}};a={...a,value:c.value,placeholder:a.placeholder===void 0?c.placeholder:a.placeholder,multiline:a.multiline===void 0?c.multiline:a.multiline,...a.maxLength===void 0&&c.maxLength!==void 0?{maxLength:c.maxLength}:{},change:qr(a.change,u),submit:qr(a.submit,n.submitActions)}}}return a.formRole===ms||i?{...a,click:qr(a.click,n.submitActions,{replaceActions:!0})}:a},eo=(e,n)=>{if(Array.isArray(e))return e.map(r=>eo(r,n));if(!e||typeof e!="object")return e;let t={};for(let[r,o]of Object.entries(e))t[r]=eo(o,n);for(let r of Dd){let o=t[r]?.payload;!o||typeof o!="object"||Array.isArray(o)||(t[r]={...t[r],payload:{...o,_interactionSource:"form"}})}return t},no=({characterId:e,character:n,characterName:t,characters:r={},variables:o={}}={})=>{let i=e?r?.[e]:void 0,s=Rt({characterId:e,character:n,characterName:t,characters:r,variables:o});return{...i||{},...n||{},name:s}},$s=(e=[],n={},t={})=>e.map(r=>{let o=no({characterId:r.characterId,character:r.character,characterName:r.characterName,characters:n,variables:t}),i=typeof r.text=="string"?r.text:Array.isArray(r.content)?r.content.map(s=>s?.text??"").join(""):"";return{...r,text:i,character:o,characterName:o.name}}),Md=e=>!(!e||e.mode==="adv"&&e.content===void 0),Vd=({dialogueState:e,includeInactiveAdvDialogue:n=!1,characters:t={},variables:r,runtime:o}={})=>{if(!n&&!Md(e))return;let i=e.content===void 0?[{text:""}]:Wr(e.content,"dialogue.content"),s=e.content===void 0?0:od({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:r}),l=o?.dialogueTextSpeed??ln.dialogueTextSpeed,a=e.textSpeed??l,c=(e.lines||[]).map((d,f)=>{let p=Wr(d.content,`dialogue.lines[${f}].content`),g=no({characterId:d.characterId,character:d.character,characterName:d.characterName,characters:t,variables:r});return{...d,textSpeed:d.textSpeed??l,content:p.map(h=>({...h,text:En(h.text,{variables:r})})),character:g,characterName:g.name}}),u=no({characterId:e.characterId,character:e.character,characters:t,variables:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,persistSprite:e.persistSprite,character:u,textSpeed:a,content:i.map(d=>({...d,text:En(d.text,{variables:r})})),initialRevealedCharacters:s,lines:c}},Ts=({container:e,resources:n,templateData:t,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=Me(e,t);return Ve(We(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),n)},Yr=(e,n={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(n),gs=({renderStateKeyboard:e,keyboard:n,phase:t})=>{!n||typeof n!="object"||Array.isArray(n)||Object.entries(n).forEach(([r,o])=>{let i=e[r]??{},s=t==="keydown"?o?.keydown:o?.keyup;if(t==="keydown"&&s&&typeof s=="object"){e[r]={...i,keydown:{payload:Yr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[r].keyup={payload:Yr(o.keyup)});return}e[r]={...i,[t]:{payload:Yr(o)}}})},jd=(e={},n={})=>{let t={};return gs({renderStateKeyboard:t,keyboard:e,phase:"keydown"}),gs({renderStateKeyboard:t,keyboard:n,phase:"keyup"}),Object.keys(t).length>0?t:void 0},je=({animationsDef:e,resources:n,previousResourceId:t,currentResourceId:r,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l})=>{if(!e)return[];let a=[],c=({instanceId:I,targetId:E})=>{let A=td({resources:n,animationId:p,playback:g,instanceId:I,targetId:E,animationPath:s});A&&a.push(A)},u=t!=null&&t!==!1,d=r!=null&&r!==!1,f=o&&i&&o===i;nd(e,s);let p=Ku(e),g=Ju(e),h=n?.animations?.[p],b=Wu(h,{animationId:p,animationPath:s});if(b==="update")return d&&i?c({instanceId:`${l}-animation-update`,targetId:i}):u&&o&&c({instanceId:`${l}-animation-update`,targetId:o}),a;if(b==="transition"){let I=`${l}-animation-transition`,E=g?.continuity==="persistent"?I:`${l}-animation-in`;if(u&&d&&f)return c({instanceId:I,targetId:i}),a;u&&c({instanceId:`${l}-animation-out`,targetId:o}),d&&c({instanceId:E,targetId:i})}return a},Fd=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Ud=(e,{presentationState:n,previousPresentationState:t,currentLineActions:r,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:a,imageGallery:c,musicRoom:u,sceneReplay:d,runtime:f,activePersistentAnimations:p,restoredPersistentAnimations:g,autoMode:h,skipMode:b,isChoiceVisible:I,isFormVisible:E,canRollback:A,form:$,saveSlots:B=[]})=>{let{elements:L,animations:T}=e;if(n.background){let z=r===void 0?!0:dn(r?.background??{},"animations"),G=L.find(fe=>fe.id==="story");if(!G)return e;let S=id(o,n.background),q=S||ad(n.background),W=t?.background?.resourceId,me=t?.background?.colorId,Y=n.background.resourceId??(n.background.animations?W:void 0),ae=n.background.colorId??(n.background.animations?me:void 0),oe=Sd(o,Y),ge={...n.background,colorId:ae};if((ae!==void 0||oe)&&G.children.push(vd({resources:o,background:ge,screen:i,includeOpacity:!oe})),Y){let{images:fe={},videos:le={},spritesheets:x={}}=o,C=As(o,Y),O;if(C==="sprite"?O=fe[Y]:C==="video"?O=le[Y]:C==="spritesheet-animation"&&(O=x[Y]),O){let Q=C==="video",Ie=C==="spritesheet-animation",H={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...S},Te={...ls(n.background,{includeDefaultAlpha:!0}),...De(H,n.background)},he;Ie?he=Es({id:Tt({resourceId:Y,kind:C}),resourceId:Y,spritesheet:O,animationName:n.background.animationName,animationSpeed:n.background.animationSpeed,loop:n.background.loop,transform:Te}):he={id:Tt({resourceId:Y,kind:C}),type:Q?"video":"sprite",src:O.fileId,width:O.width,height:O.height,...Te},Q&&(he.loop=n.background.loop??!1,he.volume=O.volume??50),he&&G.children.push(he)}}if(Y){let{layouts:fe={}}=o,le=fe[Y];if(le){let x={id:Tt({resourceId:Y,kind:"container"}),type:"container",children:le.elements,...ls(n.background)};q&&Object.assign(x,De({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...S},n.background));let C=Me(x,Re({variables:a,imageGallery:c,musicRoom:u,sceneReplay:d,runtime:f,saveSlots:B,dialogueState:n.dialogue,isLineCompleted:s,autoMode:h,skipMode:b,isChoiceVisible:I,isFormVisible:E,canRollback:A,form:$,characters:o.characters||{},skipTransitionsAndAnimations:l}));G.children.push(Ve(We(C,{isLineCompleted:s,skipMode:b,skipTransitionsAndAnimations:l}),o))}}let $e=fs({resources:o,resourceId:W,colorId:me}),ce=fs({resources:o,resourceId:Y,colorId:ae}),te=je({animationsDef:n.background.animations,resources:o,previousResourceId:$e.resourceId,currentResourceId:ce.resourceId,previousTargetId:$e.targetId,currentTargetId:ce.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});ke({animationInstances:te,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:p,restoredPersistentAnimations:g,isAuthoredOnCurrentLine:z})&&T.push(...te)}return e},Bd=(e,{presentationState:n,previousPresentationState:t,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:a}=e;if(n.character&&r){let c=l.find(g=>g.id==="story");if(!c)return e;let u=n.character.items||[],d=t?.character?.items||[],f=is(u),p=is(d);for(let g=0;g<u.length;g++){let h=u[g],{transformId:b,sprites:I}=h,E=d.find(q=>q.id===h.id),A=d.findIndex(q=>q.id===h.id),$=E?.sprites&&E.sprites.length>0,B=I&&I.length>0,L=A>=0?Ot(E,A,p):void 0,T=je({animationsDef:h.animations,resources:r,previousResourceId:L,currentResourceId:B?Ot(h,g,f):void 0,previousTargetId:L,currentTargetId:B?Ot(h,g,f):void 0,animationPath:`character.items[${g}].animations`,idPrefix:"character"});if(h.animations&&!I&&!b&&$&&ke({animationInstances:T,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...T);continue}if(h.animations&&!I&&!b)continue;if(!I||I.length===0||!b){console.warn("Character item missing sprites or transformId:",h);continue}let z=Ot(h,g,f),G=r.transforms[b];if(!G){console.warn("Transform not found:",b);continue}let S={type:"container",id:z,...De(G,h),...Sn(h),children:[]};for(let q of I){let W=xs({id:`${z}-${q.id}`,item:q,resources:r});W&&S.children.push(W)}c.children.push(S),ke({animationInstances:T,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...T)}}return e},Ls=(e,n)=>{if(!jr.includes(e))throw new Error(`${n} must be one of: ${jr.join(", ")}.`)},Gd=(e,n)=>{let t=!!e.resourceId||so(e),r=e.layer??(t?void 0:n?.layer)??Vr;return Ls(r,`Visual item "${e.id}" layer`),r},zd=(e,{presentationState:n,previousPresentationState:t,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,imageGallery:l,musicRoom:a,sceneReplay:c,runtime:u,activePersistentAnimations:d,autoMode:f,skipMode:p,isChoiceVisible:g,isFormVisible:h,canRollback:b,form:I,saveSlots:E=[],visualLayer:A})=>{let{elements:$,animations:B}=e;if(n.visual&&r){let L=$.find(S=>S.id==="story");if(!L)return e;let T=n.visual.items,z=t?.visual?.items||[],G=Re({variables:s,imageGallery:l,musicRoom:a,sceneReplay:c,runtime:u,saveSlots:E,dialogueState:n.dialogue,isLineCompleted:o,autoMode:f,skipMode:p,isChoiceVisible:g,isFormVisible:h,canRollback:b,form:I,characters:r.characters||{},skipTransitionsAndAnimations:i});A!==void 0&&Ls(A,"visualLayer");for(let S of T){let q=z.find(oe=>oe.id===S.id),W=Gd(S,q);if(A!==void 0&&W!==A)continue;if(xd(S),S.text){let oe=Hn(r,S),ge={...structuredClone(S.text),id:`visual-${S.id}`,type:"text",...De(oe,S)};Object.assign(ge,Sn(S)),L.children.push(Ve(Me(ge,G),r))}if(S.resourceId){let{images:oe={},videos:ge={},spritesheets:$e={}}=r,ce=$e[S.resourceId];if(ce){let te=Hn(r,S),fe=S.animationName;if(fe){let le=ce.animations?.[fe];if(!le)throw new Error(`Animation '${fe}' not found in spritesheet resource '${S.resourceId}'`);let x=Sn(S),C={id:`visual-${S.id}`,type:"spritesheet-animation",...De(te,S),width:S.width??ce.width,height:S.height??ce.height,alpha:x.alpha??S.alpha??1,src:ce.fileId,atlas:ce.jsonData,playback:{frames:le.frames,animationSpeed:S.animationSpeed??le.animationSpeed??.5,loop:S.loop??le.loop??!0}};x.blur&&(C.blur=x.blur),L.children.push(structuredClone(C))}}else{let te=oe[S.resourceId]||ge[S.resourceId];if(te){let fe=ge[S.resourceId]!==void 0,le=Hn(r,S),x={id:`visual-${S.id}`,type:fe?"video":"sprite",src:te.fileId,width:te.width,height:te.height,...De(le,S)};Object.assign(x,Sn(S)),fe&&(x.loop=te.loop??!1,x.volume=te.volume??50),L.children.push(x)}}}if(S.resourceId){let oe=r.particles?.[S.resourceId];oe&&L.children.push(Ed({item:S,particle:oe,resources:r}))}if(S.resourceId){let{layouts:oe={}}=r,ge=oe[S.resourceId];if(ge){let $e=Hn(r,S),ce={id:`visual-${S.id}`,type:"container",children:structuredClone(ge.elements),...De($e,S)};Object.assign(ce,Sn(S));let te=Me(ce,G);L.children.push(Ve(We(te,{isLineCompleted:o,skipMode:p,skipTransitionsAndAnimations:i}),r))}}let me=us(q),Y=us(S),ae=je({animationsDef:S.animations,resources:r,previousResourceId:me,currentResourceId:Y,previousTargetId:me?`visual-${S.id}`:void 0,currentTargetId:Y?`visual-${S.id}`:void 0,animationPath:`visual.items[${S.id}].animations`,idPrefix:S.id});ke({animationInstances:ae,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:d})&&B.push(...ae)}}return e},vn="dialogue-character-sprite",qd=(e,{presentationState:n,previousPresentationState:t,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=fn(e.elements);if(!a)return e;let c=n.dialogue?.character?.sprite,u=t?.dialogue?.character?.sprite,d=Mn(c),f=Mn(u),p=je({animationsDef:c?.animations,resources:r,previousResourceId:f?vn:void 0,currentResourceId:d?vn:void 0,previousTargetId:f?vn:void 0,currentTargetId:d?vn:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!d)return c?.animations&&f&&ke({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e;let g=r.transforms?.[c.transformId];if(!g)return console.warn("Transform not found:",c.transformId),e;let h={type:"container",id:vn,...De(g),children:[]};for(let b of c.items){let I=xs({id:`${vn}-${b.id}`,item:b,resources:r});I&&h.children.push(I)}return a.children.push(h),ke({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e},Yd=(e,{presentationState:n,previousPresentationState:t,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,skipOnlyViewedLines:d,isLineCompleted:f,skipTransitionsAndAnimations:p,variables:g,imageGallery:h,musicRoom:b,sceneReplay:I,runtime:E,activePersistentAnimations:A,saveSlots:$=[]})=>{let{elements:B,animations:L}=e;if(!n.dialogue||o)return e;let T=B.find(G=>G.id==="story");if(!T)return e;if(n.dialogue.ui&&n.dialogue.ui.resourceId){let{layouts:G={}}=r,S=G[n.dialogue.ui.resourceId];if(S){let q={elements:S.elements},W=Re({variables:g,imageGallery:h,musicRoom:b,sceneReplay:I,runtime:E,saveSlots:$,dialogueState:n.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:f,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,characters:r.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:d,skipTransitionsAndAnimations:p}),me=Me(q,W),Y=Ve(We(me?.elements,{isLineCompleted:f,skipMode:s,skipTransitionsAndAnimations:p}),r);if(Array.isArray(Y))for(let ae of Y)T.children.push(ae);else Y&&T.children.push(Y)}}qd(e,{presentationState:n,previousPresentationState:t,resources:r,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:A});let z=je({animationsDef:n.dialogue.ui?.animations,resources:r,previousResourceId:t?.dialogue?.ui?.resourceId,currentResourceId:n.dialogue.ui?.resourceId,previousTargetId:t?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:n.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return ke({animationInstances:z,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:A})&&L.push(...z),e},Hd=(e,{presentationState:n,previousPresentationState:t,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,imageGallery:a,musicRoom:c,sceneReplay:u,runtime:d,autoMode:f,skipMode:p,isChoiceVisible:g,isFormVisible:h,canRollback:b,form:I,activePersistentAnimations:E,saveSlots:A=[]})=>{let{elements:$,animations:B}=e;if(n.choice&&r){let L=fn($);if(!L)return e;let T=r?.layouts[n.choice.resourceId];if(T&&T.elements){let G={elements:T.elements},S=Me(G,{...Re({variables:l,imageGallery:a,musicRoom:c,sceneReplay:u,runtime:d,saveSlots:A,dialogueState:n.dialogue,isLineCompleted:i,autoMode:f,skipMode:p,isChoiceVisible:g??!!n.choice,isFormVisible:h,canRollback:b,form:I,characters:r.characters||{},skipTransitionsAndAnimations:s}),choice:{items:n.choice?.items??[]}}),q=Qr(Ve(We(S?.elements,{isLineCompleted:i,skipMode:p,skipTransitionsAndAnimations:s}),r));if(Array.isArray(q))for(let W of q)L.children.push(W);else q&&L.children.push(q)}let z=je({animationsDef:n.choice.animations,resources:r,previousResourceId:t?.choice?.resourceId,currentResourceId:n.choice.resourceId,previousTargetId:t?.choice?.resourceId?"choice-container":void 0,currentTargetId:n.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});ke({animationInstances:z,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:E})&&B.push(...z)}return e},Wd=(e,{presentationState:n,previousPresentationState:t,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,imageGallery:a,musicRoom:c,sceneReplay:u,runtime:d,autoMode:f,skipMode:p,isChoiceVisible:g,isFormVisible:h,canRollback:b,activePersistentAnimations:I,saveSlots:E=[],form:A})=>{let{elements:$,animations:B}=e;if(!A?.resourceId||!r)return e;let L=fn($);if(!L)return e;let T=r?.layouts?.[A.resourceId];if(!T)return console.warn(`Form layout not found: ${A.resourceId}`),e;let z={id:"form-container",type:"container",x:0,y:0,children:T.elements||[]},G={...Re({variables:l,imageGallery:a,musicRoom:c,sceneReplay:u,runtime:d,saveSlots:E,dialogueState:n.dialogue,isLineCompleted:i,autoMode:f,skipMode:p,isChoiceVisible:g,isFormVisible:h,canRollback:b,characters:r.characters||{},skipTransitionsAndAnimations:s,form:A}),form:A},S=Me(z,G),q=eo(Ve(We(Zr(S,A),{isLineCompleted:i,skipMode:p,skipTransitionsAndAnimations:s}),r),A);q&&L.children.push(q);let W=je({animationsDef:A.animations,resources:r,previousResourceId:t?.form?.resourceId,currentResourceId:A.resourceId,previousTargetId:t?.form?.resourceId?"form-container":void 0,currentTargetId:A.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return ke({animationInstances:W,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:I})&&B.push(...W),e},Kd=(e,{presentationState:n,resources:t={},variables:r,imageGallery:o,musicRoom:i,sceneReplay:s,runtime:l,isLineCompleted:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:g,saveSlots:h=[],skipTransitionsAndAnimations:b})=>{if(!n.control?.resourceId)return e;let I=t.controls?.[n.control.resourceId];if(!I)return e;let E=jd(I.keyboard,I.keyup);if(E&&Object.keys(E).length>0&&(e.global.keyboard=E),!Array.isArray(I.elements)||I.elements.length===0)return e;let A=fn(e.elements);if(!A)return e;let $={id:`control-${n.control.resourceId}`,type:"container",x:0,y:0,children:I.elements};return A.children.push(Ts({container:$,resources:t,templateData:Re({variables:r,imageGallery:o,musicRoom:i,sceneReplay:s,runtime:l,saveSlots:h,dialogueState:n.dialogue,isLineCompleted:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:g,characters:t.characters||{},skipTransitionsAndAnimations:b}),isLineCompleted:a,skipMode:u,skipTransitionsAndAnimations:b})),e},Jd=(e,{presentationState:n,resources:t,runtime:r,variables:o,musicRoomPlayer:i})=>{let{elements:s,audio:l}=e;if(n.bgm&&t){if(!fn(s))return e;let c=n.bgm,u=!Array.isArray(c.sounds),d=u?c.resourceId?[{id:"default",resourceId:c.resourceId,loop:c.loop??!0,volume:c.volume,startDelayMs:c.startDelayMs??0}]:[]:c.sounds,f=!u&&c.loop===!0,p=[];if(u||Pt(d,"BGM sound"),f){let h=d.find(b=>b.loop===!0);if(h)throw new Error(`BGM sound "${h.id}" cannot loop inside a looping BGM channel.`)}if(d.forEach(h=>{let b=t.sounds?.[h.resourceId];if(!b)return;let I=f?{...h,loop:h.loop??!1}:h;p.push(jt({id:Wn("bgm",u?"default":h.id),sound:I,resource:b,defaultLoop:!f}))}),p.length===0)return e;let g=Re({variables:o,runtime:r}).runtime;l.push(Vt({id:Rd,volume:Mt(g,"musicVolume",u?He:c.volume??He),muted:c.muted,pan:c.pan,loop:u?void 0:c.loop,playback:i?.bgmPlayback,interruption:c.interruption,children:p,runtime:g}))}return e},Xd=(e,{resources:n={},runtime:t,variables:r,musicRoomPlayer:o})=>{let i=n.musicRoom;if(!i||!o?.trackId||!o.playback)return e;let s=i.tracks.find(u=>u.id===o.trackId),l=s?n.sounds?.[s.soundId]:void 0;if(!s||!l)return e;let a=Re({variables:r,runtime:t}).runtime,c=jt({id:_d,sound:{loop:!1,startDelayMs:0,playback:o.playback},resource:l});return e.audio.push(Vt({id:Cd,volume:Mt(a,"musicVolume",He),children:[c],runtime:a})),e},Qd=(e,{presentationState:n,resources:t,runtime:r})=>{let{audio:o}=e;if(n.sfx&&t){let i=n.sfx,s=!Array.isArray(i.channels),l=s?[{id:Od,sounds:i.items??[]}]:i.channels;s||Pt(l,"SFX channel"),l.forEach(a=>{let c=!s&&a.loop===!0,u=[];if(s||Pt(a.sounds,"SFX sound",`SFX channel "${a.id}"`),c){let d=a.sounds.find(f=>f.loop===!0);if(d)throw new Error(`SFX sound "${d.id}" cannot loop inside looping SFX channel "${a.id}".`)}a.sounds.forEach((d,f)=>{let p=t.sounds?.[d.resourceId];if(!p)return;let g=c?{...d,loop:d.loop??!1}:d;u.push(jt({id:s?Wn("sfx","default",f,d.id):Wn("sfx",a.id,d.id),sound:g,resource:p,defaultLoop:c?!1:void 0}))}),u.length!==0&&o.push(Vt({id:Wn("channel","sfx",a.id),volume:Mt(r,"soundVolume",a.volume??He),muted:a.muted,pan:a.pan,loop:s?void 0:a.loop,interruption:s?void 0:a.interruption,children:u,runtime:r}))})}return e},Zd=(e,n,t)=>{if(!(!n||!t))return e?.voices?.[n]?.[t]},ef=(e,{presentationState:n,resources:t,currentSceneId:r,runtime:o,variables:i})=>{let{audio:s}=e;if(!n?.voice)return e;let l=n.voice,a=!Array.isArray(l.sounds),c=a?l.resourceId?[{id:"default",resourceId:l.resourceId,loop:l.loop??!1,volume:He,startDelayMs:l.startDelayMs??0}]:[]:l.sounds,u=!a&&l.loop===!0,d=[];if(a||Pt(c,"Voice sound"),u){let p=c.find(g=>g.loop===!0);if(p)throw new Error(`Voice sound "${p.id}" cannot loop inside a looping Voice channel.`)}if(c.forEach(p=>{let g=Zd(t,r,p.resourceId);if(!g)return;let h=u?{...p,loop:p.loop??!1}:p;d.push(jt({id:Wn("voice",r,a?"default":p.id),sound:h,resource:g,defaultLoop:u?!1:void 0}))}),d.length===0)return e;let f=Re({variables:i,runtime:o}).runtime;return s.push(Vt({id:kd,volume:a?l.volume??ks(f,"soundVolume"):Mt(f,"soundVolume",l.volume??He),muted:l.muted,pan:l.pan,loop:a?void 0:l.loop,interruption:l.interruption,children:d,runtime:f})),e},nf=(e,{presentationState:n,previousPresentationState:t,resources:r={},variables:o,imageGallery:i,musicRoom:s,sceneReplay:l,runtime:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:g,saveSlots:h=[],isLineCompleted:b,skipTransitionsAndAnimations:I,activePersistentAnimations:E})=>{let{elements:A,animations:$}=e;if(n.layout){let z=fn(A);if(!z)return e;let G=r.layouts[n.layout.resourceId];if(!G)return e;Array.isArray(G.transitions)&&!b&&!I&&ro({animations:$,transitions:G.transitions,defaultTargetId:`layout-${n.layout.resourceId}`,idPrefix:`layout-${n.layout.resourceId}`,animationPathPrefix:"layout"});let S={id:`layout-${n.layout.resourceId}`,type:"container",x:0,y:0,children:G.elements||[]};z.children.push(Ts({container:S,resources:r,templateData:Re({variables:o,imageGallery:i,musicRoom:s,sceneReplay:l,runtime:a,saveSlots:h,dialogueState:n.dialogue,isLineCompleted:b,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:g,characters:r.characters||{},skipTransitionsAndAnimations:I}),isLineCompleted:b,skipMode:u,skipTransitionsAndAnimations:I}))}let B=t?.layout?.resourceId,L=n.layout?.resourceId,T=je({animationsDef:n.layout?.animations,resources:r,previousResourceId:B,currentResourceId:L,previousTargetId:B?`layout-${B}`:void 0,currentTargetId:L?`layout-${L}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return ke({animationInstances:T,isLineCompleted:b,skipTransitionsAndAnimations:I,activePersistentAnimations:E})&&$.push(...T),e},tf=(e,{currentLineActions:n,previousPresentationState:t,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=n?.screen?.animations;if(!a)return e;let c=t!=null,u=je({animationsDef:a,resources:r,previousResourceId:c?"story":void 0,currentResourceId:"story",previousTargetId:c?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return ke({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...u),e},rf=(e,{presentationState:n})=>{let t=fn(e.elements);return!t||!n?.screen||Object.assign(t,Cs(n.screen)),e},of=(e,{presentationState:n,resources:t={},variables:r,imageGallery:o,musicRoom:i,sceneReplay:s,runtime:l,autoMode:a,skipMode:c,isChoiceVisible:u,isFormVisible:d,canRollback:f,form:p,overlayStack:g=[],dialogueHistory:h=[],saveSlots:b=[],screen:I,isLineCompleted:E,skipTransitionsAndAnimations:A})=>{let{elements:$,animations:B}=e;return g&&g.length>0&&g.forEach((L,T)=>{let z=t.layouts[L.resourceId];if(!z){console.warn(`Overlay layout not found: ${L.resourceId}`);return}Array.isArray(z.transitions)&&(A||ro({animations:B,transitions:z.transitions,defaultTargetId:`overlayStack-${T}`,idPrefix:`overlayStack-${T}`,animationPathPrefix:`overlayStack[${T}]`}));let G={id:`overlayStack-${T}`,type:"container",x:0,y:0,children:[Os({id:`overlayStack-${T}-blocker`,screen:I}),...z.elements||[]]},S=$s(h,t.characters,r),q=Re({variables:r,imageGallery:o,musicRoom:i,sceneReplay:s,runtime:l,saveSlots:b,dialogueState:n?.dialogue,isLineCompleted:E,autoMode:a,skipMode:c,isChoiceVisible:u,isFormVisible:d,canRollback:f,form:p,historyDialogue:S,characters:t.characters||{},skipTransitionsAndAnimations:A}),W=Me(G,q),[me,...Y]=W.children||[],ae=Ve(We({...W,children:Y},{isLineCompleted:E,skipMode:c,skipTransitionsAndAnimations:A}),t);$.push({...ae,children:me?[me,...ae.children||[]]:ae.children})}),e},sf=(e,{presentationState:n,resources:t={},variables:r,imageGallery:o,musicRoom:i,sceneReplay:s,runtime:l,saveSlots:a=[],autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:g,confirmDialog:h,dialogueHistory:b=[],screen:I,isLineCompleted:E,skipTransitionsAndAnimations:A})=>{let{elements:$,animations:B}=e;if(!h?.resourceId)return e;let L=t.layouts?.[h.resourceId];if(!L)return console.warn(`ConfirmDialog layout not found: ${h.resourceId}`),e;Array.isArray(L.transitions)&&!A&&ro({animations:B,transitions:L.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let T={id:"confirmDialog",type:"container",x:0,y:0,children:[Os({id:"confirmDialog-blocker",screen:I}),...L.elements||[]]},z=$s(b,t.characters,r),G=Me(T,Re({variables:r,imageGallery:o,musicRoom:i,sceneReplay:s,runtime:l,saveSlots:a,dialogueState:n?.dialogue,isLineCompleted:E,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:g,confirmDialog:h,historyDialogue:z,characters:t.characters||{},skipTransitionsAndAnimations:A})),[S,...q]=G.children||[],W=Ve(We({...G,children:q},{isLineCompleted:E,skipMode:u,skipTransitionsAndAnimations:A}),t);return $.push({...W,children:S?[S,...W.children||[]]:W.children}),e},Xn=e=>(n,t)=>zd(n,{...t,visualLayer:e}),af=Xn(Ne.BEHIND_BACKGROUND),cf=Xn(Ne.BEHIND_CHARACTER),lf=Xn(Ne.BEHIND_DIALOGUE),uf=Xn(Ne.BEHIND_CHOICE),df=Xn(Ne.FOREGROUND),Ps=e=>St(Fd,[Kd,af,Ud,cf,Bd,lf,Yd,uf,Hd,Wd,nf,df,rf,tf,Jd,Xd,Qd,ef,of,sf])(e);function Ns(e,n=""){let t=[],r=e.length,o=0,i=0,s=-1,l=()=>{let a=0,c=0,u;do u=parseInt(e[o++],36),a+=(u&15)<<c,c+=4;while(u&16);return a};for(;o<r;){let a=s+1+l();s=a+l(),t.push([a,s,n?parseInt(n[i++],36):0])}return t}function Ds(e,n,t){let r=0,o=n.length-1;for(;r<=o;){let i=r+o>>>1,s=t[i];if(e<n[i])o=i-1;else if(e>s>>>5)r=i+1;else return s&31}return 0}var Ms="090001000h1v5g2903000hl2v6jh16ng1s210111110o35aa10u2k1g10l6600152113h2010u1q1r5aq3890o13181214r22k3158q2n1000v100h1k20000001207030001160721k171001h1j11610332010010321210090411021c1c02100o301201412230u1130b100h1j116111420120411001100k11l10051001h1j11611142011000321210072411021d0g10r3000000132120090o200200g1j11f2012031213711271t1001o301001000001121371b1f0c101h1l2011001031212000080a1t1001m40400102101600i11t301006c7i601008b6p41r10101041h3d0004115a1j290p3q223000511010100g1501010302003172030c0010016000e0i6v50n40n5tl12ir33s12t11u11cj30100060700010a90t220000l71i20m7203010241000502rd101004k300000006101027050920g3t22bk1300616g209030207u18c1000t10003010501b2o20000102000004g37070101o921c000640602001mcv3rg20000001o16d0c0m1fg6g2h30m10q55f1vm11c0ma0p1a42nc0ne1a090q3314902021204020112030318250105bb1201110i1021i15101131502141b15120511011k1155132040202510201010603060a1f02040104210b1g3290e0e0kn11vs12j11j3040pp12t80g6v1vmo7319g21g51gh103040n11010040j51i3f01q1h1d0m27p1a0000cs13200523j200010301010100v140018a4q2501010101c08000i1f12601011g3012215110u1a0001015000pcq181000100011000iji5fvc0u91g5bhg20ie0l94lo6002115303121s12240la1tj23h44tj11t45m4ah33q700000l3ep2021a200t220301012040a0i320j2040007f00100r20c100g3208000011531000s520201036020t900207l1101n311000000321210090a12634b910201l22001051020120011020000e1i520701020000n10h5001050000010000010001re0010323010001r11i520701000001q6000000107l600000230004gg12080001lc62027111n1000411230000000000t820321030030r10090n205001380800501020n2050c0001mc00002000000nc006150000i5l1100600010001q753011160000i441111000000rl11019100000c1h201043102n10ltk1f006eoss2b0202gs94r36si2033ku101m373h50b1rqs4113sli1t22m1uh2435070726u13k92rr7m34h380e0m141egl561g1261114k60ga6nn10t33sv13uf1jf0207150qt16t66pr60n23k6bf1f0e1l29g71c1e029j1n30p11ea0k1028139m16rb2v621122i52213040tf1u3b51n17127c0232041d120819052c28220104060306l5g3l4572g130152cqdl2c3o37a5o27u11c32d9m2cu2191obo57eh9gg1tv3",Vs="262122424333333393233393339333333333393393bf3b3b3b3b3f3f3bffff33b3bb33ff3f33b3b3333333bffff3b33bb33f33bffff33b3bb33ff3f33b3bbb333b3ff33b333f33b3b3b3b3333b3bf33b3bb39333b33b33b3b3b333b333333b3b33333f3b33b3ffb3f3fff3f3b33f35dc33333f3b3b3b33323333b3bb3b33b3fb3b3333b33333bff3b3f33bfb3b3ff3b3b3b3b3b333b333b3323e22442344444444444444444444444444444444444444444444444444444444444444444444444444444443333333333b3b3bb33333b353bff3b3b3b3f3ff3b3b333bfff3f33333fb3bb3fb3b3bb33232333f333fff333333333b3b3333bb3b39393f3b3fbf33bb3b393b3b3b3333b33b33b3bbb33b33ffff3b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b3fffff3bb39b9b3b33b3bf3f3b33f3b3f93b33b3b3bb33b33b3b3b3333393b3b3b33b39bffb3b332333b333dd3b3333233332333333333333333333333333333444444444444a4444444444444344444444444444444444444444444444444444444444",js="0001000000010010000000100000000000000000000000000001000000010014000100000001001000010101100101100000000000000000000100000001111000010000000110101001110111111111000100000021001000010000000100100001000000011010000100000001111000013000000100140001000000010010";var Fs=65535,ao=40960,Ft=126976,Gs=new Uint8Array(12288),zs=new Uint8Array(3072),qs=new Uint8Array(2816),Ys,Hs;{let e=(o,i,s,l,a)=>{let c=i+o.length-1;for(let u=s<i?i:s,d=l>c?c:l;u<=d;u++)o[u-i]=a},n=new Uint32Array(320),t=new Uint32Array(320),r=0;for(let[o,i,s]of Ns(Ms,Vs))e(Gs,0,o,i,s),e(zs,ao,o,i,s),e(qs,Ft,o,i,s),i>=65040&&!(o>=Ft&&i<=129791)&&(n[r]=o,t[r++]=i<<5|s);Ys=n.slice(0,r),Hs=t.slice(0,r)}function Us(e){return e<12288?Gs[e]:e<ao?e<12336?e>=12330?3:0:e<12443?e===12336||e===12349?4:e>=12441?3:0:e===12951||e===12953?4:0:e<44032?zs[e-ao]:e<55204?(e-44032)%28?8:7:e<57344?e<=55238?e>=55216?13:0:e>=55243&&e<=55291?12:0:e<65024?e===64286?3:0:e<65040?3:e>=Ft&&e<129792?qs[e-Ft]:e>=917504?e>921599?0:e>=917536&&e<917632||e>=917760&&e<918e3?3:2:Ds(e,Ys,Hs)}var Ws=Uint8Array.from(js,Number);function ff(e){return e===2381||e===2509||e===2637||e===2765||e===2893||e===3149||e===3405||e===4153||e===6098||e===6752||e===6980||e===7083||e===43456||e===43766||e===68159||e===69939||e===70608||e===71998||e===72263||e===72345||e===73538}function Bs(e,n,t){switch(n){case 3:return e&24?t===8204?e&6:(e&24)===16||ff(t)?e&6|16:e&6|8:e&6;case 4:return 2;case 10:return e&1^1;case 14:return(e&2)<<1|e&24;default:return 8}}function*Ks(e){let n=e.length;if(n===0)return;let t=e.codePointAt(0),r=t>Fs?2:1,o=Us(t),i=50200>>o&1?Bs(0,o,t):0,s=0,l=t,a=o;for(;r<n;){t=e.codePointAt(r);let c=t>Fs?2:1,u=Us(t),d=Ws[o<<4|u],f;d===0?f=!0:d===1?f=!1:d===2?f=!(i&1):d===3?f=!(i&4):f=(i&24)!==16,i=50200>>u&1&&(i!==0||u!==3)?Bs(i,u,t):0,f&&(yield{segment:e.slice(s,r),index:s,input:e,_hd:l,_catBegin:a===15?0:a,_catEnd:o===15?0:o},s=r,l=t,a=u),r+=c,o=u}yield{segment:e.slice(s),index:s,input:e,_hd:l,_catBegin:a===15?0:a,_catEnd:o===15?0:o}}function*Js(e){for(let n of Ks(e))yield n.segment}{let e=Ks("_");Ws._keep=[e,e.next()]}var Xs=1e3,pf=1,mf=60,gf=3,hf=.5,yf=2e4,bf=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,If=/^\s+$/u,Qs,wf=e=>{let n=`${e??""}`.normalize("NFC"),t=globalThis.Intl?.Segmenter;return typeof t!="function"?Array.from(Js(n)):(Qs??=new t(void 0,{granularity:"grapheme"}),Array.from(Qs.segment(n),({segment:r})=>r))},Af=e=>wf(e).reduce((n,t)=>If.test(t)?n+hf:bf.test(t)?n+gf:n+1,0),Zs=({text:e="",baseDelay:n=Xs,speed:t=pf}={})=>{let r=Number.isFinite(n)?Math.max(0,n):Xs,o=Number.isFinite(t)&&t>0?t:1,i=Af(e)*mf/o,s=Math.max(r,yf);return Math.min(r+i,s)};var Ut={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},sa=1,fo=1,_n="choice",Ke="form",et=()=>({manual:{...Ut.manual},auto:{...Ut.auto},applyMode:Ut.applyMode}),po=()=>({groupId:null,variantId:null,pageIndex:0}),Ef="music-room:player",xf=new Set(["asset-unavailable","decode-failed","invalid-segment","invalid-position","playback-failed"]),zt=({bgmPlayback:e={commandId:0,operation:"resume"}}={})=>({trackId:null,pageIndex:0,status:"stopped",readiness:"idle",positionMs:0,durationMs:null,playback:null,seekFallback:null,bgmPlayback:e}),mo=new Set,vf=new Set(["groupId","variantId"]),Sf=new Set(["pageIndex"]),kn=new Set,Rf=new Set(["trackId"]),Cf=new Set(["positionMs"]),_f=new Set(["pageIndex"]),go=new Set,kf=new Set(["replayId"]),Of=new Set(["pageIndex"]),ho=()=>({pageIndex:0}),yo=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let t=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...et()},t&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},k=e=>{let n=ie(e)?Ue(e):e;return structuredClone(n)},N=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),qt=e=>{let n=e.global.audioCommandId;if(!Number.isSafeInteger(n)||n<0)throw new Error("Internal audio command counter is invalid");if(n===Number.MAX_SAFE_INTEGER)throw new Error("Audio command counter is exhausted");return e.global.audioCommandId=n+1,e.global.audioCommandId},aa=e=>{let n=e.global.sceneReplayEntryId;if(!Number.isSafeInteger(n)||n<0)throw new Error("Internal scene replay entry counter is invalid");if(n===Number.MAX_SAFE_INTEGER)throw new Error("Scene replay entry counter is exhausted");return e.global.sceneReplayEntryId=n+1,e.global.sceneReplayEntryId},nt=(e,n,t)=>({commandId:qt(e),operation:n,...t===void 0?{}:{positionMs:t}}),bo=e=>{if(!Object.prototype.hasOwnProperty.call(e.global??{},"musicRoomPlayer"))return;let n=e.global.musicRoomPlayer,t=n.bgmPlayback;n.trackId!==null&&(t={commandId:qt(e),operation:"resume"}),e.global.musicRoomPlayer=zt({bgmPlayback:t})},ca=(e,n)=>{if(typeof n!="string"||n.length===0)throw new Error("Achievement action requires a non-empty resourceId");let t=e.projectData.resources?.achievements?.[n];if(!t)throw new Error(`Achievement resource "${n}" not found`);if(t.type!=="boolean"&&t.type!=="number")throw new Error(`Achievement resource "${n}" has invalid type "${t.type}"`);return t},tt=e=>String(e),la=()=>({sections:[],resources:[]}),$f=e=>N(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):la(),Tf=e=>Array.isArray(e)?e.map(n=>n?.text??"").join(""):"",Lf=({sectionId:e,lineId:n,content:t,dialogueState:r,characterName:o})=>({sectionId:e,lineId:n,content:t,text:Tf(t),characterId:r.characterId,character:{...r.character||{},name:o},characterName:o}),Pf=()=>({resourceId:void 0}),Nf=e=>{if(!N(e))return e;let n={...e};return Object.prototype.hasOwnProperty.call(n,"requireComplete")&&!Object.prototype.hasOwnProperty.call(n,"requireLineCompleted")&&(n.requireLineCompleted=n.requireComplete),delete n.requireComplete,n},hn=(e,n)=>{let t=e?.story?.scenes??{};for(let[r,o]of Object.entries(t))if(o?.sections?.[n])return{sceneId:r,section:o.sections[n]};return{sceneId:void 0,section:void 0}},ua=e=>{let n=e?.story?.scenes??{},t=new Map;for(let[r,o]of Object.entries(n)){let i=o?.sections??{};for(let s of Object.keys(i)){let l=t.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${r}". Section IDs must be globally unique.`);t.set(s,r)}}},da=e=>{if(typeof e=="number"||typeof e!="string")return e;let n=Number(e);return Number.isFinite(n)?n:e},fa=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==sa)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Df=(e,n={})=>{let t;try{t=fa(n.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...n,formatVersion:t,slotId:da(n.slotId??n.slotKey??e),savedAt:typeof n.savedAt=="number"?n.savedAt:n.date};return delete r.slotKey,delete r.date,r},Mf=(e={})=>Object.fromEntries(Object.entries(e).map(([n,t])=>[n,Df(n,t)])),pa=e=>{if(!Array.isArray(e))return;let n=e.filter(({type:t})=>xg(t));return n.length>0?n:void 0},Vf=e=>{!N(e)||!Array.isArray(e.timeline)||(e.returnabilityVersion=fo,e.timeline.forEach(n=>{if(!N(n))return;typeof n.returnable!="boolean"&&delete n.returnable;let t=pa(n.executedActions);if(t){n.executedActions=t;return}delete n.executedActions}))},ea=(e,n,t,r="viewedRegistry")=>{let o=n==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!N(e))throw new Error(`Malformed ${r}.${n}[${t}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${r}.${n}[${t}] entry: missing ${o}.`);if(n==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${r}.sections[${t}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},jf=(e,n="viewedRegistry")=>{if(e===void 0)return la();if(!N(e))throw new Error(`Malformed ${n}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${n}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${n}.resources.`);let t=e.sections??[],r=e.resources??[];return{sections:Object.values(Object.fromEntries(t.map((o,i)=>{let s=ea(o,"sections",i,n);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(r.map((o,i)=>{let s=ea(o,"resources",i,n);return[s.resourceId,s]})))}},ma=(e,n,t)=>{if(!N(e))throw new Error(`Malformed save slot ${t}.`);let{sectionId:r,lineId:o}=e;if(typeof r!="string"||r.length===0)throw new Error(`Malformed save slot ${t}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${t}: missing lineId.`);let{sceneId:i,section:s}=hn(n,r);if(!s)throw new Error(`Malformed save slot ${t}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(a=>a.id===o))throw new Error(`Malformed save slot ${t}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},ga=(e,n)=>e?.sectionId===n?.sectionId&&e?.lineId===n?.lineId,Ff=(e,n)=>{let{section:t}=hn(e,n?.sectionId);return t?.lines?.find(r=>r.id===n?.lineId)},Uf=(e,n)=>{let{section:t}=hn(e,n?.sectionId),r=t?.lines?.findIndex(i=>i.id===n?.lineId);if(typeof r!="number"||r<0)return null;let o=t.lines[r+1];return o?{sectionId:n.sectionId,lineId:o.id}:null},ha=(e,n,t)=>{if(typeof n?.sectionId!="string")return!1;let{section:r}=hn(e,n.sectionId);return ga({sectionId:n.sectionId,lineId:r?.lines?.[0]?.id},t)},Bf=new Set(["jumpToLine","rollbackByOffset","rollbackToLine","sectionTransition","resetStoryAtSection"]),Cn={always:"always",maybe:"maybe",never:"never"},Gf=e=>{if(!Object.prototype.hasOwnProperty.call(e??{},"when"))return Cn.always;let n=e.when,t;if(n===null||typeof n=="boolean"||typeof n=="number")t=n;else if(N(n)&&Object.keys(n).length===1&&Object.prototype.hasOwnProperty.call(n,"literal"))t=n.literal;else return Cn.maybe;return t?Cn.always:Cn.never},ya=(e,n)=>{if(!Array.isArray(e?.branches))return!1;for(let t of e.branches){let r=Gf(t);if(r!==Cn.never){if(n(t))return!0;if(r===Cn.always)return!1}}return!1},ba=e=>ya(e,n=>Object.entries(n?.actions??{}).some(([t,r])=>t==="conditional"?ba(r):Bf.has(t))),Ia=(e,n,t)=>ya(n,r=>Object.entries(r?.actions??{}).some(([o,i])=>o==="sectionTransition"?ha(e,i,t):o==="conditional"?Ia(e,i,t):!1)),zf=(e,n,t)=>{if(!n)return!0;let r=Ff(t,e)?.actions;if(!N(r))return!0;if(ha(t,r.sectionTransition,n))return!1;let o=r.conditional;return o?!(Ia(t,o,n)||!(r.choice?.resourceId||r.form?.resourceId)&&!ba(o)&&ga(Uf(t,e),n)):!0},qf=(e,n,t)=>{if(!N(e)||!Array.isArray(e.timeline))return Zn({pointer:n,replayStartIndex:1});let r=new WeakSet,o=e.timeline.flatMap((c,u)=>{if(!N(c))return[];try{let d=ma(c,t,`rollback.timeline[${u}]`),f=Gt({sectionId:d.sectionId,lineId:d.lineId,rollbackPolicy:c.rollbackPolicy,returnable:c.returnable});typeof c.returnable=="boolean"&&r.add(f);let p=pa(k(c.executedActions));return p&&(f.executedActions=p),[f]}catch{return[]}});if(o.length===0)return Zn({pointer:n,replayStartIndex:1});e.returnabilityVersion!==fo&&o.forEach((c,u)=>{!r.has(c)&&!zf(c,o[u+1],t)&&(c.returnable=!1)});let s=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):o.length-1;(s<0||s>=o.length)&&(s=o.length-1);let l=o[s];if(l?.sectionId!==n.sectionId||l?.lineId!==n.lineId){let c=o.findLastIndex(u=>u.sectionId===n.sectionId&&u.lineId===n.lineId);c>=0?s=c:(o.push(Gt({sectionId:n.sectionId,lineId:n.lineId})),s=o.length-1)}let a=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),s):0;return{currentIndex:s,isRestoring:!1,replayStartIndex:a,timeline:o}},Yf=(e,n,t)=>{if(!N(e))throw new Error(`Malformed save slot contexts[${t}] entry.`);let r=Ao(n),o=ma(e.pointers?.read,n,`contexts[${t}].pointers.read`);if(e.variables!==void 0&&!N(e.variables))throw new Error(`Malformed save slot contexts[${t}].variables entry.`);if(e.runtime!==void 0&&!N(e.runtime))throw new Error(`Malformed save slot contexts[${t}].runtime entry.`);let i=e.variables?An(k(e.variables),n.resources?.variables??{}):{},s=ip({loadedContextRuntime:N(e.runtime)?k(e.runtime):{}}),l={currentPointerMode:"read",pointers:{read:o},configuration:N(e.configuration)?k(e.configuration):{},views:Array.isArray(e.views)?k(e.views):[],bgm:N(e.bgm)?k(e.bgm):{resourceId:void 0},variables:{...r,...i},rollback:qf(e.rollback,o,n)};return s&&(l.runtime=s),l},Hf=(e,n)=>{if(!N(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((t,r)=>Yf(t,n,r))}},Wf=(e,n)=>{if(!N(e))throw new Error("Malformed save slot.");let t=fa(e.formatVersion);return{...e,formatVersion:t,state:Hf(e.state,n)}},na=(e,n,{required:t=!1}={})=>{if(e===void 0){if(t)throw new Error(`showConfirmDialog requires ${n}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${n} must be an action object`);let r=k(e),o=r.hideConfirmDialog??{};return delete r.hideConfirmDialog,{hideConfirmDialog:o,...r}},Kf=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:na(e.confirmActions,"confirmActions",{required:!0}),cancelActions:na(e.cancelActions,"cancelActions")}},On=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Jf=e=>(N(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),$n=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},wa=e=>{if(!(!N(e)||!e.animations))return{animations:k(e.animations)}},Xf=(e,n)=>{let t=wa(n);if(t){e.global.pendingScreenTransition=t;return}delete e.global.pendingScreenTransition},Qf=e=>{let n=e?.id??e?.resourceId;return typeof n=="string"&&n.length>0?n:void 0},Zf=(e,n)=>{let t=e?.sectionId,r=e?.lineId;if(!(!t||!r||!n))return`${t}:${r}:${n}`},Bt=e=>String(e??""),Aa=(e,n)=>{let t=Bt(n);return e?.trim===!0?t.trim():t},ep=e=>N(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,n])=>N(n)).map(([n,t])=>[n,{id:n,...k(t)}])):{},np=(e,n)=>{if(!n||!N(e.global.formDrafts))return;let t=e.global.formDrafts[n];return N(t)?t:void 0},Ea=(e,n)=>{let t=Jf(e);N(t[n])||(t[n]={values:{},touched:{},errors:{},submitted:!1});let r=t[n];return N(r.values)||(r.values={}),N(r.touched)||(r.touched={}),N(r.errors)||(r.errors={}),typeof r.submitted!="boolean"&&(r.submitted=!1),r},Io=(e,n)=>{let t=Aa(e,n);return e?.required===!0&&t.length===0?"required":null},tp=({state:e,pointer:n})=>{if(!n?.sectionId||!n?.lineId)return{};let r=de({state:e},{sectionId:n.sectionId})?.lines||[],o=r.findIndex(i=>i.id===n.lineId);return o<0?{}:cn(r.slice(0,o+1).map(i=>i.actions||{}))},rp=({state:e,form:n,pointer:t})=>{if(!n?.resourceId)return null;let r=Qf(n),o=Zf(t,r);if(!r||!o)return null;let i=np(e,o),s=ep(n),l=Yt({state:e}),a={},c=[],u={},d=!0;return Object.entries(s).forEach(([f,p])=>{let g=Bt(l?.[p.variableId]),h=Object.prototype.hasOwnProperty.call(i?.values??{},f)?Bt(i.values[f]):g,b=i?.touched?.[f]===!0,I=Io(p,h),E=i?.submitted||b?I:null,A=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,$={id:f,variableId:p.variableId,value:h,initialValue:g,valid:!I,error:E,touched:b,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...A!==void 0?{maxLength:A}:{}};I&&(d=!1),a[f]=$,c.push($),u[f]=h}),{id:r,key:o,resourceId:n.resourceId,animations:n.animations,valid:d,submitted:i?.submitted===!0,fields:a,fieldList:c,values:u,submitActions:{submitForm:{formKey:o,actions:k(n.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:k(n.cancelActions??{})}}}},mn=[],ta="line",wo="interaction",Gt=({sectionId:e,lineId:n,rollbackPolicy:t,returnable:r})=>({sectionId:e,lineId:n,rollbackPolicy:t??"free",...typeof r=="boolean"?{returnable:r}:{}}),Ao=e=>{let n=ie(e)?Ue(e):e,{contextVariableDefaultValues:t}=Ct(n??{});return k(t)},xa=()=>({...k(qn)}),va=({loadedRuntime:e,runtimeIds:n,defaults:t={},path:r})=>{if(e===void 0)return{runtimeState:k(t),hasLoadedValues:!1};if(!N(e))throw new Error(`Malformed ${r}.`);let o=k(t),i=!1;return n.forEach(s=>{e[s]!==void 0&&(o[s]=Ra(s,k(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},op=({loadedGlobalRuntime:e={}})=>va({loadedRuntime:e,runtimeIds:Dr,defaults:ln,path:"global.runtime"}).runtimeState,ip=({loadedContextRuntime:e={}})=>{let{runtimeState:n,hasLoadedValues:t}=va({loadedRuntime:e,runtimeIds:Mr,defaults:xa(),path:"context.runtime"});return t?n:void 0},rt=e=>{let n=Array.isArray(e?.contexts)?e.contexts:[];return n[n.length-1]},J=e=>{let n=rt(e);return n?.kind==="sceneReplay"&&N(n.sceneReplay)?n:null},Sa=(e,n)=>{let t=n?.sceneReplay?.replayId,r=e.projectData?.resources?.sceneReplay?.replays?.find(o=>o.id===t);Object.entries(r?.initialVariables??{}).forEach(([o,i])=>{n.variables[o]=k(i)})},sp=e=>({autoMode:e.global.autoMode,skipMode:e.global.skipMode,dialogueUIHidden:e.global.dialogueUIHidden,nextLineConfig:k(e.global.nextLineConfig),overlayStack:k(e.global.overlayStack),confirmDialog:k(e.global.confirmDialog),formDrafts:k(e.global.formDrafts),isLineCompleted:e.global.isLineCompleted,...e.global.isDialogueHistoryShowing===void 0?{}:{isDialogueHistoryShowing:e.global.isDialogueHistoryShowing},...e.global.pendingScreenTransition===void 0?{}:{pendingScreenTransition:k(e.global.pendingScreenTransition)}}),ap=e=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,delete e.global.pendingScreenTransition,e.global.nextLineConfig=et(),e.global.overlayStack=[],e.global.confirmDialog=null,e.global.formDrafts={},e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"})},cp=(e,n)=>{e.global.autoMode=n.autoMode,e.global.skipMode=n.skipMode,e.global.dialogueUIHidden=n.dialogueUIHidden,e.global.nextLineConfig=k(n.nextLineConfig),e.global.overlayStack=k(n.overlayStack),e.global.confirmDialog=k(n.confirmDialog),e.global.formDrafts=k(n.formDrafts),e.global.isLineCompleted=n.isLineCompleted,n.isDialogueHistoryShowing===void 0?delete e.global.isDialogueHistoryShowing:e.global.isDialogueHistoryShowing=n.isDialogueHistoryShowing,n.pendingScreenTransition===void 0?delete e.global.pendingScreenTransition:e.global.pendingScreenTransition=k(n.pendingScreenTransition),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"});let t=Ae({state:e});e.global.autoMode&&e.global.isLineCompleted&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:it({state:e})}}),e.global.skipMode&&!t&&e.global.pendingEffects.push({name:"startSkipNextTimer"}),e.global.nextLineConfig.auto?.enabled&&!t&&(e.global.nextLineConfig.auto.trigger==="fromStart"||e.global.isLineCompleted)&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})},lp=e=>e.runtime?(Mr.forEach(n=>{e.runtime[n]===void 0&&(e.runtime[n]=k(qn[n]))}),e.runtime):(e.runtime=xa(),e.runtime),up=e=>rs(e.global),dp=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:up(e)}})},fp=e=>ts[e],pp=(e,n)=>{let t=fp(e);if(t==="number"){if(typeof n!="number"||!Number.isFinite(n))throw new Error(`${e} requires a finite numeric value`);return}if(t==="boolean"){if(typeof n!="boolean")throw new Error(`${e} requires a boolean value`);return}if(t==="string"){if(typeof n!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},Ra=(e,n)=>{if(pp(e,n),e==="autoForwardSpeed"&&n<=0)throw new Error("autoForwardSpeed requires a value greater than 0");return e==="saveLoadPagination"?Math.max(1,Math.trunc(n)):n},Ca=(e,n,t)=>{let r=Ra(n,t);if(n in qn){let o=rt(e);if(!o)return r;let i=lp(o);return i[n]=r,r}return e.global[n]=r,r},Eo=({pointer:e,projectData:n,kind:t,sceneReplay:r})=>({...t===void 0?{}:{kind:t},...r===void 0?{}:{sceneReplay:k(r)},currentPointerMode:"read",pointers:{read:k(e)},configuration:{},views:[],bgm:Pf(),variables:Ao(n),rollback:Zn({pointer:e})}),Tn=e=>e?(e.currentPointerMode="read",N(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,mp=(e,{queueRender:n=!0}={})=>{let t=e.contexts?.[e.contexts.length-1],r=t?.pointers?.read;if(!t||!r?.sectionId||!r?.lineId)return null;let o=Eo({pointer:r,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,gp(e,{queueRender:n}),o},gp=(e,{queueRender:n=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,On(e),$n(e),e.global.nextLineConfig=et(),e.global.overlayStack=[],e.global.isLineCompleted=!0,bo(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),n&&e.global.pendingEffects.push({name:"render"})},_a=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},Zn=({pointer:e,replayStartIndex:n=0})=>{let t=e?.sectionId&&e?.lineId;return{currentIndex:t?0:-1,isRestoring:!1,replayStartIndex:n,timeline:t?[Gt({sectionId:e.sectionId,lineId:e.lineId})]:[]}},yn=(e,n={})=>{if(e?.rollback)return _a(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 t=e?.pointers?.read;return e.rollback=Zn({pointer:t,replayStartIndex:n.compatibilityAnchor?1:0}),e.rollback},xo=(e,n)=>{let t=e.contexts?.[e.contexts.length-1];if(!t)return;let r=yn(t);r.isRestoring||(r.currentIndex<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,r.currentIndex+1)),r.timeline.push(Gt(n)),r.currentIndex=r.timeline.length-1)},hp=({state:e})=>{let t=e.contexts?.[e.contexts.length-1]?.rollback;return!Array.isArray(t?.timeline)||typeof t.currentIndex!="number"?null:{checkpointIndex:t.currentIndex,checkpoint:t.timeline[t.currentIndex]??null}},yp=({state:e},n={})=>{let{checkpointIndex:t,checkpointIdentity:r,sectionId:o,lineId:i}=n,l=e.contexts?.[e.contexts.length-1]?.rollback;if(!Number.isInteger(t)||!Array.isArray(l?.timeline)||typeof l.currentIndex!="number")return e;let a=l.timeline[t];return(ie(a)?ur(a):a)!==r||a?.sectionId!==o||a?.lineId!==i||(a.returnable=!1),e},bp=({state:e},n={})=>{let{slotId:t,saveSlotIdentity:r,checkpointIndex:o,sectionId:i,lineId:s}=n,l=tt(t),a=e.global.saveSlots?.[l],c=ie(a)?ur(a):a;if(!a||c!==r)return e;let u=a.state?.contexts,d=Array.isArray(u)?u.at(-1):null,f=d?.rollback,p=f?.timeline?.[o];return!Number.isInteger(o)||f?.currentIndex!==o||d?.pointers?.read?.sectionId!==i||d?.pointers?.read?.lineId!==s||p?.sectionId!==i||p?.lineId!==s||(p.returnable=!1,f.returnabilityVersion=fo,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}})),e},Ip=e=>{let t=e.contexts?.[e.contexts.length-1]?.rollback;if(!t||t.isRestoring||!Array.isArray(t.timeline)||typeof t.currentIndex!="number")return null;let r=mn[mn.length-1],o=typeof r?.checkpointIndex=="number"?r.checkpointIndex:t.currentIndex;return o<0||o>=t.timeline.length?null:(typeof r?.checkpointIndex!="number"&&o<t.timeline.length-1&&(t.timeline=t.timeline.slice(0,o+1)),t.timeline[o]??null)},wp=({state:e},n={})=>{let t=n?.source===ta?ta:wo,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?(mn.push({checkpointIndex:null,source:t}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),mn.push({checkpointIndex:o.currentIndex,source:t}),e)},Ap=({state:e})=>(mn.pop(),e),Le=(e,n,t)=>{let o=mn[mn.length-1]?.source??wo;if(!vg(n,o))return;let i=Ip(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:n,payload:k(t)}))},ra=(e,n)=>{let t=e.contexts?.[e.contexts.length-1];if(!t)return;let r=n?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:l}of r){let a=e.projectData.resources?.variables?.[o],c=a?.scope,u=a?.type;if(Se(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Gn(c,o),_t(u,i,o),Or(u,i,s,o,{roundTo:l}),c==="context"&&(t.variables[o]=kt(t.variables[o],i,s,{roundTo:l}))}},Ep=(e,n)=>{Array.isArray(n?.executedActions)&&n.executedActions.forEach(({type:t,payload:r})=>{Sg(e,t,r)})},xp=(e,n)=>{let{sectionId:t,lineId:r}=n,s=de({state:e},{sectionId:t})?.lines?.find(l=>l.id===r)?.actions;s&&Object.entries(s).forEach(([l,a])=>{sc(e,l,a)})},ka=(e,n)=>{let t=e.contexts?.[e.contexts.length-1];if(!t)return e;let r=yn(t),o=r.timeline[n];if(!o)return e;e.global.autoMode&&at({state:e}),e.global.skipMode&&Je({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=n;try{t.variables=Ao(e.projectData),t.kind==="sceneReplay"&&(Sa(e,t),t.sceneReplay.finishOnNextAdvance=!1,t.sceneReplay.exitOnLineCompleted=!1),delete t.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=k(Ut),e.global.overlayStack=[],On(e),$n(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let l=i;l<=n;l++)l>i&&yo(e),xp(e,r.timeline[l]),Ep(e,r.timeline[l]);let s=Tn(t);s.read={sectionId:o.sectionId,lineId:o.lineId},t.kind==="sceneReplay"&&(t.sceneReplay.entryId=aa(e)),e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},vp=e=>{let{projectData:n}=e,t=e.global??{},{saveSlots:r={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=t;ua(n),jn(n),Fn(n),Un(n),an(n?.resources?.variables??{});let l=n.story.initialSceneId,a=n.story.scenes[l],c=a.initialSectionId,u=a.sections[c],d={sceneId:l,sectionId:c,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:f}=Ct(n),p={...f,...An(o,n.resources?.variables??{})};return{projectData:n,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:jf(s,"accountViewedRegistry"),nextLineConfig:et(),imageGalleryNavigation:po(),sceneReplayNavigation:ho(),sceneReplayEntryId:0,audioCommandId:0,musicRoomPlayer:zt(),saveSlots:Mf(r),overlayStack:[],variables:p,...op({loadedGlobalRuntime:i})},contexts:[Eo({pointer:d,projectData:n})]}},Sp=({state:e})=>e.global.overlayStack||[],Rp=({state:e})=>e.global.pendingEffects,Oa=({state:e})=>e.global.skipMode,Cp=({state:e})=>e.global.autoMode,$a=({state:e})=>e.global.dialogueUIHidden,Ta=({state:e})=>{let n=Array.isArray(e.contexts)?e.contexts:[],t=n[n.length-1];if(!t)return[];let{sectionId:r,lineId:o}=t.pointers.read,i=de({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(d=>d.id===o),l=i.lines.slice(0,s+1),a=[],c={},u=Bn({variables:{...e.global?.variables??{},...rt(e)?.variables??{}},runtime:un(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let d of l){let f=d.actions||{};if(c=cn([c,f]),!f.dialogue)continue;let p=c.dialogue||{},g=Rt({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:u}),h=Lf({sectionId:r,lineId:d.id,content:f.dialogue.append===!0?p.content:f.dialogue.content,dialogueState:p,characterName:g});if(f.dialogue.append===!0&&a.length>0){a[a.length-1]={...a[a.length-1],content:h.content,text:h.text,characterId:h.characterId,character:h.character,characterName:h.characterName};continue}a.push(h)}return a},_p=({state:e})=>e.global.confirmDialog??null,ot=({state:e},{pointer:n}={})=>{let t=n??Ce({state:e})?.pointer,r=tp({state:e,pointer:t});return rp({state:e,form:r.form,pointer:t})},kp=({state:e},{pointer:n}={})=>!!ot({state:e},{pointer:n}),Ae=({state:e},{pointer:n}={})=>{let t=ot({state:e},{pointer:n});if(t)return{source:Ke,formId:t.id,formKey:t.key};let r=Ma({state:e,pointer:n});return r?{source:_n,resourceId:r}:null},Op=({state:e,registry:n},t)=>{let{sectionId:r,lineId:o}=t,s=(Array.isArray(n?.sections)?n.sections:[]).find(u=>u.sectionId===r);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let l=de({state:e},{sectionId:r});if(!l||!l.lines||!Array.isArray(l.lines))return s.lastLineId===o;let a=l.lines.findIndex(u=>u.id===s.lastLineId),c=l.lines.findIndex(u=>u.id===o);return a===-1||c===-1?s.lastLineId===o:c<=a},vo=({registry:e},n)=>{let{resourceId:t}=n;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===t)},So=({state:e},n)=>Op({state:e,registry:e.global.accountViewedRegistry},n),$p=({state:e},n)=>vo({registry:e.global.accountViewedRegistry},n),Qn=(e,n)=>!vo({registry:e.global.accountViewedRegistry},{resourceId:n.imageId}),Ro=e=>e.groups.length===0?0:Math.ceil(e.groups.length/e.pageSize),Co=(e,n)=>{let t=Ro(e);if(t===0)return 0;let r=Number.isInteger(n?.pageIndex)?n.pageIndex:0;return Math.min(Math.max(r,0),t-1)},co=(e,n,t,r)=>{for(let o=t+r;o>=0&&o<n.length;o+=r)if(!Qn(e,n[o]))return n[o]},Tp=({state:e})=>{let n=e.projectData?.resources?.imageGallery;return n===void 0?void 0:k(n)},La=({state:e})=>{let n=e.projectData?.resources?.imageGallery;if(n===void 0)return null;let t=e.global.imageGalleryNavigation??po(),r=Ro(n),o=Co(n,t),i=o*n.pageSize,s=n.groups.slice(i,i+n.pageSize).map(a=>({groupId:a.id,locked:Qn(e,a.variants[0]),variants:a.variants.map(c=>({variantId:c.id,imageId:c.imageId,locked:Qn(e,c)}))})),l=null;if(typeof t.groupId=="string"&&typeof t.variantId=="string"){let a=n.groups.findIndex(p=>p.id===t.groupId),c=n.groups[a],u=c?.variants.findIndex(p=>p.id===t.variantId),d=u===void 0||u<0?void 0:c.variants[u],f=a<0?-1:Math.floor(a/n.pageSize);d&&f===o&&!Qn(e,d)&&(l={groupId:c.id,variantId:d.id,imageId:d.imageId,canMoveToPreviousVariant:co(e,c.variants,u,-1)!==void 0,canMoveToNextVariant:co(e,c.variants,u,1)!==void 0})}return{pageGroups:s,selection:l,pagination:{pageIndex:o,pageCount:r,canMoveToPreviousPage:o>0,canMoveToNextPage:o+1<r}}},_o=(e,n)=>!vo({registry:e.global.accountViewedRegistry},{resourceId:n.soundId}),ko=e=>e.tracks.length===0?0:Math.ceil(e.tracks.length/e.pageSize),Oo=(e,n)=>{let t=ko(e);if(t===0)return 0;let r=Number.isInteger(n?.pageIndex)?n.pageIndex:0;return Math.min(Math.max(r,0),t-1)},lo=(e,n,t,r)=>{for(let o=t+r;o>=0&&o<n.length;o+=r)if(!_o(e,n[o]))return n[o]},Pa=e=>({trackId:e.id,soundId:e.soundId,title:e.title,artist:e.artist??null,album:e.album??null,description:e.description??null,coverImageId:e.coverImageId??null}),Lp=(e,n)=>({...Pa(n),locked:_o(e,n)}),oa=e=>{let n=Math.floor(e/1e3),t=n%60,r=Math.floor(n/60);if(r<60)return`${r}:${String(t).padStart(2,"0")}`;let o=Math.floor(r/60),i=r%60;return`${o}:${String(i).padStart(2,"0")}:${String(t).padStart(2,"0")}`},Pp=({state:e})=>{let n=e.projectData?.resources?.musicRoom;return n===void 0?void 0:k(n)},Na=({state:e})=>{let n=e.projectData?.resources?.musicRoom;if(n===void 0)return null;let t=e.global.musicRoomPlayer??zt(),r=ko(n),o=Oo(n,t),i=o*n.pageSize,s=n.tracks.slice(i,i+n.pageSize).map(u=>Lp(e,u)),l=n.tracks.findIndex(u=>u.id===t.trackId),a=n.tracks[l],c=a?{...Pa(a),canPlayPreviousTrack:lo(e,n.tracks,l,-1)!==void 0,canPlayNextTrack:lo(e,n.tracks,l,1)!==void 0}:null;return{pageTracks:s,selection:c,playback:c?{status:t.status,readiness:t.readiness,positionMs:t.positionMs,durationMs:t.durationMs,positionText:oa(t.positionMs),durationText:t.durationMs===null?null:oa(t.durationMs),canPlay:t.status!=="playing",canPause:t.status==="playing",canSeek:t.readiness==="ready"&&t.durationMs!==null}:null,pagination:{pageIndex:o,pageCount:r,canMoveToPreviousPage:o>0,canMoveToNextPage:o+1<r}}},$o=e=>e.replays.length===0?0:Math.ceil(e.replays.length/e.pageSize),To=(e,n)=>{let t=$o(e);if(t===0)return 0;let r=Number.isInteger(n?.pageIndex)?n.pageIndex:0;return Math.min(Math.max(r,0),t-1)},Np=({state:e})=>{let n=e.projectData?.resources?.sceneReplay;return n===void 0?void 0:k(n)},Dp=({state:e})=>J(e)!==null,Mp=({state:e})=>{let n=J(e);return n?{replayId:n.sceneReplay.replayId,entryId:n.sceneReplay.entryId}:null},Da=({state:e})=>{let n=e.projectData?.resources?.sceneReplay;if(n===void 0)return null;let t=e.global.sceneReplayNavigation??ho(),r=$o(n),o=To(n,t),i=o*n.pageSize,s=n.replays.slice(i,i+n.pageSize).map(a=>({replayId:a.id,title:a.title,thumbnailImageId:a.thumbnailImageId})),l=J(e);return{isActive:l!==null,activeReplayId:l?.sceneReplay.replayId??null,pageReplays:s,pagination:{pageIndex:o,pageCount:r,canMoveToPreviousPage:o>0,canMoveToNextPage:o+1<r}}},Vp=({state:e})=>e.global.nextLineConfig,Ma=({state:e,pointer:n}={})=>{let t=n??Ce({state:e})?.pointer;if(!t)return;let r=t?.sectionId,o=t?.lineId,s=de({state:e},{sectionId:r})?.lines||[],l=s.findIndex(c=>c.id===o);if(l<0)return;let a;for(let c of s.slice(0,l+1)){let u=c?.actions;if(u?.cleanAll&&(a=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){a=void 0;continue}let d=u.choice;if(d?.resourceId){a=d.resourceId;continue}d?.animations||(a=void 0)}return a},Va=({state:e})=>!!Ma({state:e}),jp=({state:e})=>structuredClone(e),Fp=({state:e})=>k(e.projectData.resources?.achievements??{}),Up=({state:e},n)=>{let t=e.projectData.resources?.achievements?.[n?.resourceId];return t===void 0?void 0:k(t)},ja=({state:e})=>e.global.saveSlots,Bp=({state:e},n)=>{let t=n?.slotId,r=tt(t);return e.global.saveSlots[r]},Lo=({state:e})=>un(e),Gp=({state:e},n)=>Ye(e,n?.runtimeId),Yt=({state:e})=>{let n={...e.global?.variables??{},...rt(e)?.variables??{}};return Bn({variables:n,runtime:un(e),variableConfigs:e.projectData.resources?.variables??{}})},Ce=({state:e})=>{let n=Array.isArray(e.contexts)?e.contexts:[],t=n[n.length-1];if(t)return{currentPointerMode:"read",pointer:t.pointers?.read}},de=({state:e},n)=>{let{sectionId:t}=n;return hn(e.projectData,t).section},Ht=({state:e})=>{let n=Ce({state:e});if(!n?.pointer)return;let{sectionId:t,lineId:r}=n.pointer,o=de({state:e},{sectionId:t});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},Fa=({state:e})=>{let{sectionId:n,lineId:t}=Ce({state:e}).pointer,o=de({state:e},{sectionId:n})?.lines||[],i=o.findIndex(c=>c.id===t),l=o.slice(0,i+1).map(c=>{let u=c.actions||{},d={};return Object.keys(u).forEach(f=>{d[f]=u[f]}),d});return cn(l)},zp=e=>{let n=Ht({state:e})?.actions?.dialogue;if(n?.clear===!0||!Array.isArray(n?.content))return"";let t=Yt({state:e});return n.content.map(r=>`${En(r?.text,{variables:t})??""}`).join("")},it=({state:e})=>Zs({text:zp(e),baseDelay:Ye(e,"autoForwardDelay"),speed:Ye(e,"autoForwardSpeed")}),qp=({state:e})=>{let n=Ua({state:e}),r=Ht({state:e})?.actions??{},o=cn([n??{},r]);return Tr(n??{},o??{})},Yp=({state:e},{sectionId:n})=>{let t=de({state:e},{sectionId:n});if(!t?.lines)return[];let r=[],o={};for(let i of t.lines){let s=i.actions||{},l=cn([o,s]),a=Tr(o,l);r.push({id:i.id,changes:a,presentationState:l}),o=Lr(l)}return r},Hp=({state:e},{sectionId:n,includePresentationState:t=!1})=>{let r=Yp({state:e},{sectionId:n});return t?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},Ua=({state:e})=>{let{sectionId:n,lineId:t}=Ce({state:e}).pointer,o=de({state:e},{sectionId:n})?.lines||[],i=o.findIndex(a=>a.id===t);if(i<=0)return null;let l=o.slice(0,i).map(a=>{let c=a.actions||{},u={};return Object.keys(c).forEach(d=>{u[d]=c[d]}),u});return Lr(cn(l))},Po=({state:e},{slotsPerPage:n=6}={})=>{let o=((Lo({state:e}).saveLoadPagination??1)-1)*n+1,i=[];for(let s=0;s<n;s++){let l=o+s,a=e.global.saveSlots&&e.global.saveSlots[tt(l)]||{};i.push({...a,slotId:l})}return{saveSlots:i}},Wp=ja,Kp=Po,Jp=e=>{let t=e.contexts?.[e.contexts.length-1]?.rollback;return!t||!Array.isArray(t.timeline)||typeof t.currentIndex!="number"?!1:t.currentIndex>=0&&t.currentIndex<t.timeline.length-1},Xp=({state:e},n={})=>{let t=Fa({state:e}),r=Ua({state:e}),o=Ht({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:k(i)}:o,l=i?.animations&&r===null?{}:r,{sectionId:a}=Ce({state:e}).pointer,{sceneId:c}=hn(e.projectData,a),u=Lo({state:e}),d=n?.activePersistentAnimations??[],f=n?.restoredPersistentAnimations??[],p=ot({state:e}),g=Va({state:e}),h=La({state:e}),b=Na({state:e}),I=Da({state:e}),E=Yt({state:e}),{saveSlots:A}=Po({state:e}),$=Jp(e);return Ps({presentationState:t,previousPresentationState:l,currentLineActions:s,resources:e.projectData.resources,currentSceneId:c,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:g,isFormVisible:!!p,canRollback:lc({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||$,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:Ta({state:e}),saveSlots:A,variables:E,runtime:u,activePersistentAnimations:d,restoredPersistentAnimations:f,imageGallery:h,musicRoom:b,sceneReplay:I,musicRoomPlayer:k(e.global.musicRoomPlayer)})},Qp=({state:e},n)=>(e.global.confirmDialog=Kf(n),e.global.pendingEffects.push({name:"render"}),e),Zp=({state:e})=>(e.global.confirmDialog&&(On(e),e.global.pendingEffects.push({name:"render"})),e),em=({state:e},n)=>(e.global.overlayStack.push(n),e.global.pendingEffects.push({name:"render"}),Le(e,"pushOverlay",n),e),nm=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Le(e,"popOverlay",void 0),e),tm=({state:e},n)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=n),e.global.pendingEffects.push({name:"render"}),Le(e,"replaceLastOverlay",n),e),rm=({state:e})=>(e.global.overlayStack=[],On(e),$n(e),e.global.pendingEffects.push({name:"render"}),Le(e,"clearOverlays",void 0),e),om=(e,{activeInteraction:n})=>{e.global.autoMode&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),n&&e.global.skipMode&&e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},st=(e,n,{screenTransition:t}={})=>{e.global.isLineCompleted=!1,Xf(e,t),$n(e);let r=Ae({state:e},{pointer:n}),o=r?.source===_n,i=r?.source===Ke;om(e,{activeInteraction:r});let s=J(e),l={name:"handleLineActions"};if(typeof s?.sceneReplay?.replayId=="string"){let a=aa(e);s.sceneReplay.entryId=a,l.payload={sceneReplayId:s.sceneReplay.replayId,entryId:a}}return e.global.pendingEffects.push(l),{isChoiceVisible:o,isFormVisible:i,activeInteraction:r}},Wt=(e,n,t)=>{!(n?.source===_n||n?.source===Ke)||t||!e.global.skipMode||e.global.pendingEffects.push({name:"startSkipNextTimer"})},Ba=({state:e})=>(Ae({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:it({state:e})}}),e.global.pendingEffects.push({name:"render"})),e),at=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),im=({state:e})=>{let n=e.global.autoMode;return Ae({state:e})&&!n||(n?at({state:e}):Ba({state:e})),e},Ga=({state:e})=>(Ae({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),sm=({state:e})=>{let n=Oa({state:e});return Ae({state:e})&&!n||(n?Je({state:e}):Ga({state:e})),e},Kt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Le(e,"showDialogueUI",void 0),e),za=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Le(e,"hideDialogueUI",void 0),e),am=({state:e})=>($a({state:e})?Kt({state:e}):za({state:e}),e),Xe=(e,n,t)=>(Ca(e,n,t),dp(e),e.global.pendingEffects.push({name:"render"}),e),ct=(e,n,t,r)=>{let o=Ca(e,n,t);return e.global.pendingEffects.push({name:"render"}),Le(e,r,{value:o}),e},cm=({state:e},n)=>Xe(e,"dialogueTextSpeed",n?.value),lm=({state:e},n)=>Xe(e,"autoForwardDelay",n?.value),um=({state:e},n)=>Xe(e,"autoForwardSpeed",n?.value),dm=({state:e},n)=>Xe(e,"skipUnseenText",n?.value),fm=({state:e},n)=>Xe(e,"skipTransitionsAndAnimations",n?.value),pm=({state:e},n)=>Xe(e,"soundVolume",n?.value),mm=({state:e},n)=>Xe(e,"musicVolume",n?.value),gm=({state:e},n)=>Xe(e,"muteAll",n?.value),hm=({state:e},n)=>ct(e,"saveLoadPagination",n?.value,"setSaveLoadPagination"),ym=({state:e})=>{let n=Ye(e,"saveLoadPagination")+1;return ct(e,"saveLoadPagination",n,"incrementSaveLoadPagination"),e},bm=({state:e})=>{let n=Ye(e,"saveLoadPagination")-1;return ct(e,"saveLoadPagination",n,"decrementSaveLoadPagination"),e},Im=({state:e},n)=>ct(e,"menuPage",n?.value,"setMenuPage"),wm=({state:e},n)=>ct(e,"menuEntryPoint",n?.value,"setMenuEntryPoint"),Am=({state:e})=>(e.global.pendingEffects=[],e),Em=({state:e},n)=>(e.global.pendingEffects.push(n),e),xm=({state:e},n)=>{if(J(e))return e;let t=n?.resourceId;return ca(e,t),e.global.pendingEffects.push({name:"completeAchievement",payload:{resourceId:t}}),e},vm=({state:e},n)=>{if(J(e))return e;let t=n?.resourceId,r=ca(e,t);if(r.type!=="number")throw new Error(`Achievement resource "${t}" does not support numeric progress`);let o=n?.current;if(!Number.isInteger(o)||o<0)throw new Error(`Achievement progress for "${t}" must be a non-negative integer`);if(!Number.isInteger(r.target)||r.target<1)throw new Error(`Achievement resource "${t}" must have a positive integer target`);let i=Math.min(o,r.target);return e.global.pendingEffects.push({name:"setAchievementProgress",payload:{resourceId:t,current:i,target:r.target,completed:i>=r.target}}),e},qa=(e,{sectionId:n,resetStoryState:t=!1,screen:r})=>{let o=!!wa(r),i=de({state:e},{sectionId:n});if(!i)return console.warn(`Section not found: ${n}`),e;let s=i.lines?.[0];if(!s)return console.warn(`Section ${n} has no lines`),e;if(t&&!mp(e,{queueRender:!o}))return e;let l=Ae({state:e});t&&e.global.skipMode&&Je({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let u=Tn(a),d=u.read;t||gn(e,{sectionId:d?.sectionId,lineId:d?.lineId}),a.rollback||yn(a,{compatibilityAnchor:!0}),u.read={sectionId:n,lineId:s.id},t?a.rollback=Zn({pointer:u.read}):xo(e,{sectionId:n,lineId:s.id})}let{activeInteraction:c}=st(e,a?.pointers?.read,{screenTransition:r});return Wt(e,l,c),e},Sm=({state:e},n)=>{if(J(e))throw new Error("Cannot reset the story while a scene replay is active");return qa(e,{sectionId:n?.sectionId,resetStoryState:!0,screen:n?.screen})},Ya=e=>(e.global.accountViewedRegistry=$f(e.global.accountViewedRegistry),e.global.accountViewedRegistry),No=(e,n)=>{!Array.isArray(n)||n.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:n.map(t=>({scope:t.scope,path:t.path,op:t.op,value:k(t.value)}))}})},Ha=(e,n)=>{No(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(n?.sections)?n.sections:[]).map(t=>({sectionId:t.sectionId,...t.lastLineId===void 0?{}:{lineId:t.lastLineId}})),resources:Array.isArray(n?.resources)?n.resources:[]}}])},Rm=(e,n,{sectionId:t,lineId:r})=>{if(!t||!r)return!1;let o=N(n)?n:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===t);if(i){if(i.lastLineId===void 0)return!1;let s=de({state:e},{sectionId:t});if(s?.lines){let l=s.lines.findIndex(c=>c.id===i.lastLineId),a=s.lines.findIndex(c=>c.id===r);if(l===-1||a>l)return i.lastLineId===r?!1:(i.lastLineId=r,!0)}else return i.lastLineId===r?!1:(i.lastLineId=r,!0);return!1}else return o.sections.push({sectionId:t,lastLineId:r}),!0},gn=(e,n)=>{if(J(e)||e.global.accountViewedRegistry===void 0)return;Rm(e,Ya(e),n)&&Ha(e,{sections:[{sectionId:n.sectionId,lastLineId:n.lineId}],resources:[]})},Cm=({state:e},n)=>(gn(e,n),e.global.pendingEffects.push({name:"render"}),e),_m=({state:e},n)=>{if(J(e))return e;let{resourceId:t}=n;if(e.global.accountViewedRegistry!==void 0){let r=Ya(e);r.resources.find(i=>i.resourceId===t)||(r.resources.push({resourceId:t}),Ha(e,{sections:[],resources:[{resourceId:t}]}))}return e.global.pendingEffects.push({name:"render"}),e},Pe=(e,n,t)=>{if(!N(n))throw new Error(`${e} payload must be an object`);Object.keys(n).forEach(r=>{if(!t.has(r))throw new Error(`${e} payload contains unsupported property "${r}"`)})},uo=(e,n,t)=>{if(typeof t!="string"||t.length===0)throw new Error(`${e} requires a non-empty ${n}`)},Jt=(e,n)=>{let t=e.global.imageGalleryNavigation;t.groupId===n.groupId&&t.variantId===n.variantId&&t.pageIndex===n.pageIndex||(e.global.imageGalleryNavigation=n,e.global.pendingEffects.push({name:"render"}))},km=({state:e},n)=>{let t="showImageGalleryVariant";Pe(t,n,vf),uo(t,"groupId",n.groupId),Object.prototype.hasOwnProperty.call(n,"variantId")&&uo(t,"variantId",n.variantId);let r=e.projectData?.resources?.imageGallery;if(r===void 0)return e;let o=r.groups.findIndex(l=>l.id===n.groupId),i=r.groups[o];if(!i)return e;let s=n.variantId===void 0?i.variants[0]:i.variants.find(l=>l.id===n.variantId);return!s||Qn(e,s)||Jt(e,{groupId:i.id,variantId:s.id,pageIndex:Math.floor(o/r.pageSize)}),e},Wa=(e,n,t,r)=>{Pe(r,n,mo);let o=e.projectData?.resources?.imageGallery;if(o===void 0)return e;let i=e.global.imageGalleryNavigation;if(typeof i.groupId!="string"||typeof i.variantId!="string")return e;let s=o.groups.find(c=>c.id===i.groupId),l=s?.variants.findIndex(c=>c.id===i.variantId);if(!s||l===void 0||l<0)return e;let a=co(e,s.variants,l,t);return a&&Jt(e,{...i,variantId:a.id}),e},Om=({state:e},n)=>Wa(e,n,-1,"moveToPreviousImageGalleryVariant"),$m=({state:e},n)=>Wa(e,n,1,"moveToNextImageGalleryVariant"),Tm=({state:e},n)=>{if(Pe("clearImageGallerySelection",n,mo),e.projectData?.resources?.imageGallery===void 0)return e;let r=e.global.imageGalleryNavigation;return Jt(e,{groupId:null,variantId:null,pageIndex:r.pageIndex}),e},Ka=(e,n)=>{let t=e.projectData?.resources?.imageGallery;if(t===void 0)return e;let r=Ro(t);if(n>=r)return e;let o=e.global.imageGalleryNavigation,i=Co(t,o);return n===i||Jt(e,{groupId:null,variantId:null,pageIndex:n}),e},Lm=({state:e},n)=>{if(Pe("moveToImageGalleryPage",n,Sf),!Number.isInteger(n.pageIndex)||n.pageIndex<0)throw new Error("moveToImageGalleryPage requires a non-negative integer pageIndex");return Ka(e,n.pageIndex)},Ja=(e,n,t,r)=>{Pe(r,n,mo);let o=e.projectData?.resources?.imageGallery;if(o===void 0)return e;let s=Co(o,e.global.imageGalleryNavigation)+t;return s<0?e:Ka(e,s)},Pm=({state:e},n)=>Ja(e,n,1,"moveToNextImageGalleryPage"),Nm=({state:e},n)=>Ja(e,n,-1,"moveToPreviousImageGalleryPage"),Fe=(e,n,t)=>{if(!N(n))throw new Error(`${e} payload must be an object`);Object.keys(n).forEach(r=>{if(!t.has(r))throw new Error(`${e} payload contains unsupported property "${r}"`)})},Dm=(e,n)=>{if(typeof n!="string"||n.length===0)throw new Error(`${e} requires a non-empty trackId`)},Oe=e=>{e.global.pendingEffects.push({name:"render"})},Xa=(e,n)=>{let t=e.projectData.resources.musicRoom,r=e.global.musicRoomPlayer,o=r.trackId!==null,i=r.trackId===n.id,s=r.bgmPlayback;o||(s={commandId:qt(e),operation:"pause"});let l=nt(e,"play",0),a=t.tracks.indexOf(n),c=i?r.durationMs:null;e.global.musicRoomPlayer={trackId:n.id,pageIndex:Math.floor(a/t.pageSize),status:"playing",readiness:c===null?"loading":"ready",positionMs:0,durationMs:c,playback:l,seekFallback:null,bgmPlayback:s},Oe(e)},Mm=({state:e},n)=>{let t="playMusicRoomTrack";Fe(t,n,Rf),Dm(t,n.trackId);let o=e.projectData?.resources?.musicRoom?.tracks.find(i=>i.id===n.trackId);return!o||_o(e,o)||Xa(e,o),e},Vm=({state:e},n)=>{Fe("playMusicRoom",n,kn);let r=e.global.musicRoomPlayer;if(r.trackId===null||r.status==="playing")return e;let o=r.status==="ended",i=r.readiness==="error",s=r.status==="paused"&&!i?"resume":"play",l=o?0:r.positionMs;return r.playback=nt(e,s,s==="play"?l:void 0),r.seekFallback=null,r.status="playing",r.positionMs=l,i&&(r.readiness=r.durationMs===null?"loading":"ready"),Oe(e),e},jm=({state:e},n)=>{Fe("pauseMusicRoom",n,kn);let r=e.global.musicRoomPlayer;return r.trackId===null||r.status!=="playing"||(r.playback=nt(e,"pause"),r.seekFallback=null,r.status="paused",Oe(e)),e},Fm=({state:e},n)=>{Fe("stopMusicRoom",n,kn);let r=e.global.musicRoomPlayer;return r.trackId===null||r.status==="stopped"&&r.positionMs===0||(r.playback=nt(e,"stop"),r.seekFallback=null,r.status="stopped",r.positionMs=0,Oe(e)),e},Um=({state:e},n)=>{if(Fe("seekMusicRoom",n,Cf),typeof n.positionMs!="number"||!Number.isFinite(n.positionMs)||n.positionMs<0)throw new Error("seekMusicRoom requires a finite non-negative positionMs");let r=e.global.musicRoomPlayer;if(r.trackId===null||r.readiness!=="ready"||r.durationMs===null||n.positionMs>r.durationMs)return e;let o=nt(e,"seek",n.positionMs);return r.seekFallback={commandId:o.commandId,status:r.status,positionMs:r.positionMs},r.playback=o,r.positionMs=n.positionMs,n.positionMs===r.durationMs?r.status="ended":r.status==="ended"&&(r.status="stopped"),Oe(e),e},Qa=(e,n,t,r)=>{Fe(r,n,kn);let o=e.projectData?.resources?.musicRoom,i=e.global.musicRoomPlayer;if(!o||i.trackId===null)return e;let s=o.tracks.findIndex(a=>a.id===i.trackId);if(s<0)return e;let l=lo(e,o.tracks,s,t);return l&&Xa(e,l),e},Bm=({state:e},n)=>Qa(e,n,-1,"playPreviousMusicRoomTrack"),Gm=({state:e},n)=>Qa(e,n,1,"playNextMusicRoomTrack"),zm=({state:e},n)=>{Fe("clearMusicRoomSelection",n,kn);let r=e.global.musicRoomPlayer;if(r.trackId===null)return e;let o=r.pageIndex,i={commandId:qt(e),operation:"resume"};return e.global.musicRoomPlayer={...zt({bgmPlayback:i}),pageIndex:o},Oe(e),e},Za=(e,n)=>{let t=e.projectData?.resources?.musicRoom;if(!t||n>=ko(t))return e;let r=e.global.musicRoomPlayer,o=Oo(t,r);return n===o||(r.pageIndex=n,Oe(e)),e},qm=({state:e},n)=>{if(Fe("moveToMusicRoomPage",n,_f),!Number.isInteger(n.pageIndex)||n.pageIndex<0)throw new Error("moveToMusicRoomPage requires a non-negative integer pageIndex");return Za(e,n.pageIndex)},ec=(e,n,t,r)=>{Fe(r,n,kn);let o=e.projectData?.resources?.musicRoom;if(!o)return e;let i=Oo(o,e.global.musicRoomPlayer)+t;return i<0?e:Za(e,i)},Ym=({state:e},n)=>ec(e,n,1,"moveToNextMusicRoomPage"),Hm=({state:e},n)=>ec(e,n,-1,"moveToPreviousMusicRoomPage"),pn=e=>{let n=J(e);if(!n)return!1;if(e.contexts.length<2)throw new Error("Scene replay context has no caller context to restore");let t=k(n.sceneReplay.returnState),r=n.sceneReplay.replayId;return e.global.pendingEffects=e.global.pendingEffects.filter(o=>o?.name!=="handleLineActions"||o?.payload?.sceneReplayId!==r),e.contexts.pop(),cp(e,t),e.global.pendingEffects.push({name:"render"}),!0},Wm=({state:e},n)=>{let t="startSceneReplay";if(Pe(t,n,kf),uo(t,"replayId",n.replayId),J(e))throw new Error("Cannot start a scene replay while another replay is active");let o=e.projectData?.resources?.sceneReplay?.replays.find(u=>u.id===n.replayId);if(!o)return e;let{sceneId:i,section:s}=hn(e.projectData,o.startSectionId),l=s?.initialLineId??s?.lines?.[0]?.id;if(!s||!l||!s.lines.some(u=>u.id===l))throw new Error(`Scene replay "${o.id}" has an invalid start section`);let a=sp(e);ap(e);let c=Eo({pointer:{sceneId:i,sectionId:o.startSectionId,lineId:l},projectData:e.projectData,kind:"sceneReplay",sceneReplay:{replayId:o.id,entryId:0,finishOnNextAdvance:!1,exitOnLineCompleted:!1,returnState:a}});return Sa(e,c),e.contexts.push(c),st(e,c.pointers.read),e},nc=({state:e},n)=>{Pe("finishSceneReplay",n,go);let r=J(e);return r&&(r.sceneReplay.finishOnNextAdvance=!0),e},Km=({state:e},n)=>(Pe("exitSceneReplay",n,go),pn(e),e),tc=(e,n)=>{let t=e.projectData?.resources?.sceneReplay;if(!t||n>=$o(t))return e;let r=To(t,e.global.sceneReplayNavigation);return n===r||(e.global.sceneReplayNavigation.pageIndex=n,e.global.pendingEffects.push({name:"render"})),e},Jm=({state:e},n)=>{if(Pe("moveToSceneReplayPage",n,Of),!Number.isInteger(n.pageIndex)||n.pageIndex<0)throw new Error("moveToSceneReplayPage requires a non-negative integer pageIndex");return tc(e,n.pageIndex)},rc=(e,n,t,r)=>{Pe(r,n,go);let o=e.projectData?.resources?.sceneReplay;if(!o)return e;let i=To(o,e.global.sceneReplayNavigation)+t;return i<0?e:tc(e,i)},Xm=({state:e},n)=>rc(e,n,1,"moveToNextSceneReplayPage"),Qm=({state:e},n)=>rc(e,n,-1,"moveToPreviousSceneReplayPage"),Xt=(e,n)=>{let t=e.global.musicRoomPlayer;return!N(n)||n.id!==Ef||t.trackId===null||!t.playback||n.commandId!==t.playback.commandId?null:t},Do=e=>typeof e.positionMs=="number"&&Number.isFinite(e.positionMs)&&e.positionMs>=0&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>0&&e.positionMs<=e.durationMs,oc=(e,n,t,{readiness:r=n.readiness}={})=>((n.readiness!==r||n.positionMs!==t.positionMs||n.durationMs!==t.durationMs||n.seekFallback!==null)&&(n.readiness=r,n.positionMs=t.positionMs,n.durationMs=t.durationMs,n.seekFallback=null,Oe(e)),e),Zm=({state:e},n)=>{let t=Xt(e,n);return!t||t.readiness!=="loading"||!Do(n)?e:oc(e,t,n,{readiness:"ready"})},eg=({state:e},n)=>{let t=Xt(e,n);return!t||t.readiness!=="ready"||!Do(n)||t.status==="stopped"&&n.positionMs!==0||t.status==="ended"&&n.positionMs!==n.durationMs?e:oc(e,t,n)},ng=({state:e},n)=>{let t=Xt(e,n);return!t||t.readiness!=="ready"||t.status!=="playing"||!Do(n)||n.positionMs!==n.durationMs||(t.status="ended",t.positionMs=n.positionMs,t.durationMs=n.durationMs,t.seekFallback=null,Oe(e)),e},tg=({state:e},n)=>{let t=Xt(e,n);if(!t||typeof n.errorCode!="string"||!xf.has(n.errorCode)||t.readiness==="error"&&t.status==="stopped")return e;if(n.errorCode==="invalid-position"){let r=t.seekFallback;if(t.playback.operation!=="seek"||r?.commandId!==n.commandId)return e;let o=t.status!==r.status||t.positionMs!==r.positionMs;return t.status=r.status,t.positionMs=r.positionMs,t.seekFallback=null,o&&Oe(e),e}return t.readiness="error",t.status="stopped",t.positionMs=0,t.seekFallback=null,Oe(e),e},ic=({state:e},n)=>{let t=Nf(n.manual),{auto:r,applyMode:o}=n,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;t&&r?(e.global.nextLineConfig={manual:t,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(t&&(e.global.nextLineConfig.manual=t),r&&(e.global.nextLineConfig.auto=r),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let a=e.global.nextLineConfig.auto?.enabled,c=Ae({state:e});return!l&&!c&&a===!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&&a===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),Le(e,"setNextLineConfig",n),e},rg=({state:e},n)=>{if(J(e))throw new Error("Cannot save while a scene replay is active");let t=n?.slotId;if(t==null||t==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:r}=n,o=n?.savedAt,i=tt(t),s=k(e.contexts);s?.forEach(c=>{Tn(c),_a(c.rollback),Vf(c.rollback)});let l={contexts:s},a={formatVersion:sa,slotId:da(t),savedAt:typeof o=="number"?o:Date.now(),image:r,state:l};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},og=({state:e},n)=>{if(J(e))throw new Error("Cannot load while a scene replay is active");let t=n?.slotId;if(t==null||t==="")throw new Error("loadSlot requires slotId");let r=tt(t),o=e.global.saveSlots[r];if(o){let i=Wf(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=et(),e.global.overlayStack=[],e.global.isLineCompleted=!0,On(e),$n(e),bo(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},ig=({state:e},n)=>{if(J(e))throw new Error("Cannot update project data while a scene replay is active");let{projectData:t}=n;ua(t),jn(t),Fn(t),Un(t),an(t?.resources?.variables??{}),e.projectData=t,e.global.imageGalleryNavigation=po(),e.global.sceneReplayNavigation=ho(),bo(e);let r=t?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=Ct(t??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...An(e.global.variables,r)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...An(s.variables,r)})}),On(e),$n(e),e.global.pendingEffects.push({name:"render"}),e},sg=({state:e},n)=>{let{sectionId:t,lineId:r}=n;if(!r)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=t||o.pointers.read?.sectionId;if(t&&!de({state:e},{sectionId:t}))return console.warn(`Section not found: ${t}`),e;let s=de({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(d=>d.id===r))return console.warn(`Line not found: ${r} in section ${i}`),e;let a=Ae({state:e}),c=Tn(o);c.read={sectionId:i,lineId:r};let{activeInteraction:u}=st(e,c.read);return Wt(e,a,u),e},ag=({state:e},n)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return Kt({state:e}),e;let t=Ae({state:e});if(t?.source===_n&&n?.bypassChoice!==!0||t?.source===Ke&&n?._interactionSource!==Ke)return e;if(!e.global.isLineCompleted){if(e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition,J(e)?.sceneReplay.exitOnLineCompleted)return pn(e),e;let f=Ce({state:e})?.pointer,p=f?.sectionId,g=f?.lineId;p&&g&&gn(e,{sectionId:p,lineId:g}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:it({state:e})}});let h=e.global.nextLineConfig;return h?.auto?.enabled&&!t&&h.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:h.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}if(J(e)?.sceneReplay.finishOnNextAdvance)return pn(e),e;let o=Ce({state:e})?.pointer,i=o?.sectionId,s=de({state:e},{sectionId:i}),l=e.contexts[e.contexts.length-1],a=s?.lines||[],u=a.findIndex(d=>d.id===o?.lineId)+1;if(u<a.length){let d=a[u],f=!Ye(e,"skipUnseenText");if(e.global.skipMode&&f&&!So({state:e},{sectionId:i,lineId:d.id}))return Je({state:e}),e;if(l&&!l.rollback&&yn(l,{compatibilityAnchor:!0}),l){let g=Tn(l),h=g.read?.lineId;h&&i&&gn(e,{sectionId:i,lineId:h}),g.read={sectionId:i,lineId:d.id}}xo(e,{sectionId:i,lineId:d.id}),yo(e);let{activeInteraction:p}=st(e,{sectionId:i,lineId:d.id});Wt(e,t,p)}else{if(J(e))return console.warn("Scene replay reached the end of a section without finishSceneReplay; exiting replay."),pn(e),e;e.global.autoMode&&at({state:e}),e.global.skipMode&&Je({state:e})}return e},cg=({state:e})=>{if(e.global.isLineCompleted)return e;if(e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition,J(e)?.sceneReplay.exitOnLineCompleted)return pn(e),e;let t=Ae({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:it({state:e})}});let r=Ce({state:e})?.pointer,o=r?.sectionId,i=r?.lineId;o&&i&&gn(e,{sectionId:o,lineId:i});let s=e.global.nextLineConfig;return s?.auto?.enabled&&!t&&s.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:s.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},lg=({state:e},n)=>qa(e,{sectionId:n?.sectionId,screen:n?.screen}),ug=({state:e},n)=>{let t=n?._conditionalContinuation===!0;if(e.global.dialogueUIHidden&&!t)return Kt({state:e}),e;let r=Ae({state:e});if(r?.source===_n&&n?.bypassChoice!==!0||r?.source===Ke&&n?._interactionSource!==Ke||r&&r.source!==_n&&r.source!==Ke)return e;let o=J(e);if(o?.sceneReplay.finishOnNextAdvance)return e.global.isLineCompleted?(pn(e),e):(o.sceneReplay.exitOnLineCompleted=!0,e);let i=Ce({state:e})?.pointer,s=i?.sectionId,l=de({state:e},{sectionId:s}),a=e.contexts[e.contexts.length-1],c=l?.lines||[],d=c.findIndex(f=>f.id===i?.lineId)+1;if(d<c.length){let f=c[d],p=!Ye(e,"skipUnseenText");if(e.global.skipMode&&p&&!So({state:e},{sectionId:s,lineId:f.id})&&(Je({state:e}),!t))return e;if(a&&!a.rollback&&yn(a,{compatibilityAnchor:!0}),a){let h=Tn(a),b=h.read?.lineId;b&&s&&gn(e,{sectionId:s,lineId:b}),h.read={sectionId:s,lineId:f.id}}xo(e,{sectionId:s,lineId:f.id}),yo(e);let{activeInteraction:g}=st(e,{sectionId:s,lineId:f.id});Wt(e,r,g)}else{if(J(e))return console.warn("Scene replay reached the end of a section without finishSceneReplay; exiting replay."),pn(e),e;e.global.autoMode&&at({state:e}),e.global.skipMode&&Je({state:e}),e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}))}return e},Mo=(e,n={})=>{let t=ot({state:e});return!t||n.formKey&&n.formKey!==t.key||n.formId&&n.formId!==t.id?null:t},dg=(e,n)=>{if(!n.variableId)throw new Error(`form field "${n.id}" requires variableId`);let t=e.projectData.resources?.variables?.[n.variableId],r=t?.scope,o=t?.type;if(Se(t))throw new Error(`Cannot update computed variable: ${n.variableId}`);if(t?.readonly===!0)throw new Error(`Cannot update readonly variable: ${n.variableId}`);if(Gn(r,n.variableId),_t(o,"set",n.variableId),J(e)&&r!=="context")throw new Error(`Cannot update ${r}-scoped variable "${n.variableId}" while a scene replay is active`);return{variableConfig:t,scope:r}},fg=(e,n)=>({id:e.id,key:e.key,valid:!0,values:k(n),fields:k(e.fields),fieldList:k(e.fieldList)}),pg=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let n=Ce({state:e})?.pointer,t=n?.sectionId,r=n?.lineId;t&&r&&gn(e,{sectionId:t,lineId:r})},mg=({state:e},n={})=>{let t=Mo(e,n),r=n.field;if(!t?.fields?.[r])return e;let o=Ea(e,t.key),i=Bt(n.value),s=t.fields[r],l=Io(s,i);return o.values[r]=i,o.touched[r]=!0,l?o.errors[r]=l:delete o.errors[r],e.global.pendingEffects.push({name:"render"}),e},gg=({state:e},n={})=>{let t=Mo(e,n);if(!t)return{submitted:!1,valid:!1,reason:"inactive"};let r=Ea(e,t.key);r.submitted=!0;let o={},i={};if(Object.entries(t.fields).forEach(([d,f])=>{let p=Object.prototype.hasOwnProperty.call(r.values,d)?r.values[d]:f.value,g=Io(f,p);r.touched[d]=!0,g&&(i[d]=g),o[d]=Aa(f,p)}),r.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:k(i),form:{id:t.id,key:t.key,values:k(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let l=!1,a=[],c=[];Object.entries(t.fields).forEach(([d,f])=>{let{scope:p}=dg(e,f),g=p==="context"?s.variables:e.global.variables,h=o[d];g[f.variableId]=kt(g[f.variableId],"set",h),p==="context"&&(l=!0,c.push({variableId:f.variableId,op:"set",value:h})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${f.variableId}`,op:"set",value:k(g[f.variableId])})}),l&&Le(e,"updateVariable",{id:"submitForm",operations:c}),No(e,a);let u=fg(t,o);return pg(e),delete e.global.formDrafts[t.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},hg=({state:e},n={})=>{let t=Mo(e,n);return t?(delete e.global.formDrafts?.[t.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:t.id,key:t.key,values:k(t.values),fields:k(t.fields),fieldList:k(t.fieldList)}}):{cancelled:!1,reason:"inactive"}},yg=({state:e},n)=>{let{id:t,operations:r=[]}=n;if(!t)throw new Error("updateVariable requires an id field");if(typeof t!="string"||!/^[a-zA-Z0-9]+$/.test(t))throw new Error(`updateVariable id must be alphanumeric, got: "${t}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],l=[];return r.forEach(({variableId:a,op:c,value:u,roundTo:d})=>{let f=e.projectData.resources?.variables?.[a],p=f?.scope,g=f?.type;if(Se(f))throw new Error(`Cannot update computed variable: ${a}`);if(f?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);if(Gn(p,a),_t(g,c,a),Or(g,c,u,a,{roundTo:d}),J(e)&&p!=="context")throw new Error(`Cannot update ${p}-scoped variable "${a}" while a scene replay is active`);let h=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let b={variableId:a,op:c,value:u};d!==void 0&&(b.roundTo=d),l.push(b)}h[a]=kt(h[a],c,u,{roundTo:d}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:k(h[a])})}),i&&Le(e,"updateVariable",{id:t,operations:l}),No(e,s),e.global.pendingEffects.push({name:"render"}),e},ia=e=>(n,t)=>e({state:n},t),bg=e=>({variables:Bn({variables:{...e.global?.variables??{},...rt(e)?.variables??{}},runtime:un(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:un(e)}),Ig=e=>{if(!N(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")},wg=(e,n,t)=>{if(!N(e))throw new Error(`conditional branch at index ${n} must be an object`);if(!N(e.actions))throw new Error(`conditional branch at index ${n} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&n!==t-1)throw new Error("conditional else branch must be the last branch")},Ag=(e,n)=>{Ig(n);for(let t=0;t<n.branches.length;t+=1){let r=n.branches[t];if(wg(r,t,n.branches.length),!(Object.prototype.hasOwnProperty.call(r,"when")&&!Vn(r.when,bg(e)))){Object.entries(r.actions).forEach(([i,s])=>{sc(e,i,s)});return}}},Eg={conditional:{replayLine:Ag},updateVariable:{recordSources:[wo],replayLine:ra,replayRecorded:ra,persistInSaveSlot:!0},setNextLineConfig:{replayLine:ia(ic)},finishSceneReplay:{replayLine:ia(nc)}},Qt=e=>Eg[e]??null,xg=e=>Qt(e)?.persistInSaveSlot===!0,vg=(e,n)=>{let t=Qt(e)?.recordSources;return Array.isArray(t)&&t.includes(n)},Sg=(e,n,t)=>{Qt(n)?.replayRecorded?.(e,t)},sc=(e,n,t)=>{Qt(n)?.replayLine?.(e,t)},Rg=e=>e?.returnable!==!1,ac=(e,n)=>{if(n>=0)return e.currentIndex+n;let t=Math.abs(n);for(let r=e.currentIndex-1;r>=0;r-=1)if(Rg(e.timeline[r])&&(t-=1,t===0))return r;return-1},cc=({state:e},n)=>{let{offset:t}=n;if(t===void 0||typeof t!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let r=e.contexts[e.contexts.length-1];if(!r)return null;let o=r.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=ac(o,t);if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},lc=({state:e})=>cc({state:e},{offset:-1})!==null,Cg=({state:e},n)=>{let{offset:t=-1}=n;if(t>=0)throw new Error("rollbackByOffset requires a negative offset");let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let o=yn(r,{compatibilityAnchor:!r.rollback}),i=ac(o,t);return i<0||i>=o.timeline.length?e:ka(e,i)},_g=({state:e},n)=>{let{sectionId:t,lineId:r}=n,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=yn(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===t&&a.lineId===r);if(l===-1)throw new Error(`Line ${r} not found in section ${t} rollback timeline`);return l===i.currentIndex?e:ka(e,l)},uc=e=>{let n=vp(e);return Ti(n,{selectPendingEffects:Rp,selectSkipMode:Oa,selectAutoMode:Cp,selectIsChoiceVisible:Va,selectIsFormVisible:kp,selectActiveInteraction:Ae,selectActiveForm:ot,selectDialogueUIHidden:$a,selectDialogueHistory:Ta,selectConfirmDialog:_p,selectIsLineAccountViewed:So,selectIsResourceAccountViewed:$p,selectImageGalleryConfig:Tp,selectImageGallery:La,selectMusicRoomConfig:Pp,selectMusicRoom:Na,selectSceneReplayConfig:Np,selectSceneReplay:Da,selectIsSceneReplayActive:Dp,selectActiveSceneReplayEntry:Mp,selectNextLineConfig:Vp,selectSystemState:jp,selectAchievements:Fp,selectAchievement:Up,selectSaveSlotMap:ja,selectSaveSlots:Wp,selectSaveSlot:Bp,selectRuntime:Lo,selectRuntimeValue:Gp,selectAllVariables:Yt,selectCurrentPointer:Ce,selectSection:de,selectCurrentLine:Ht,selectPresentationState:Fa,selectAutoForwardTimerDelay:it,selectPresentationChanges:qp,selectSectionLineChanges:Hp,selectSaveSlotPage:Po,selectCurrentPageSlots:Kp,selectRenderState:Xp,selectOverlayStack:Sp,selectLineIdByOffset:cc,selectCanRollback:lc,selectRollbackCursor:hp,startAutoMode:Ba,stopAutoMode:at,toggleAutoMode:im,startSkipMode:Ga,stopSkipMode:Je,toggleSkipMode:sm,showDialogueUI:Kt,hideDialogueUI:za,toggleDialogueUI:am,setDialogueTextSpeed:cm,setAutoForwardDelay:lm,setAutoForwardSpeed:um,setSkipUnseenText:dm,setSkipTransitionsAndAnimations:fm,setSoundVolume:pm,setMusicVolume:mm,setMuteAll:gm,setSaveLoadPagination:hm,incrementSaveLoadPagination:ym,decrementSaveLoadPagination:bm,setMenuPage:Im,setMenuEntryPoint:wm,showConfirmDialog:Qp,hideConfirmDialog:Zp,resetStoryAtSection:Sm,clearPendingEffects:Am,appendPendingEffect:Em,completeAchievement:xm,setAchievementProgress:vm,beginRollbackActionBatch:wp,endRollbackActionBatch:Ap,markRollbackCheckpointTransient:yp,markSavedRollbackCheckpointTransient:bp,addViewedLine:Cm,addViewedResource:_m,showImageGalleryVariant:km,moveToPreviousImageGalleryVariant:Om,moveToNextImageGalleryVariant:$m,clearImageGallerySelection:Tm,moveToImageGalleryPage:Lm,moveToNextImageGalleryPage:Pm,moveToPreviousImageGalleryPage:Nm,playMusicRoomTrack:Mm,playMusicRoom:Vm,pauseMusicRoom:jm,stopMusicRoom:Fm,seekMusicRoom:Um,playPreviousMusicRoomTrack:Bm,playNextMusicRoomTrack:Gm,clearMusicRoomSelection:zm,moveToMusicRoomPage:qm,moveToNextMusicRoomPage:Ym,moveToPreviousMusicRoomPage:Hm,musicRoomSoundReady:Zm,musicRoomSoundProgress:eg,musicRoomSoundComplete:ng,musicRoomSoundError:tg,startSceneReplay:Wm,finishSceneReplay:nc,exitSceneReplay:Km,moveToSceneReplayPage:Jm,moveToNextSceneReplayPage:Xm,moveToPreviousSceneReplayPage:Qm,setNextLineConfig:ic,saveSlot:rg,loadSlot:og,updateProjectData:ig,sectionTransition:lg,jumpToLine:sg,nextLine:ag,markLineCompleted:cg,rollbackToLine:_g,rollbackByOffset:Cg,pushOverlay:em,popOverlay:nm,replaceLastOverlay:tm,clearOverlays:rm,updateFormField:mg,submitForm:gg,cancelForm:hg,updateVariable:yg,nextLineFromSystem:ug},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var kg="route-engine",Og="projectPersistence";var fc=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),se=e=>Object.prototype.toString.call(e)==="[object Object]",dc="variables.",$g=(e={})=>{let n=se(e)?e:{};return{sections:(Array.isArray(n.sections)?n.sections:[]).map(t=>typeof t=="string"||typeof t=="number"?{sectionId:String(t)}:!se(t)||typeof t.sectionId!="string"||t.sectionId.length===0?null:{sectionId:t.sectionId,...typeof t.lineId=="string"?{lineId:t.lineId}:{}}).filter(Boolean),resources:(Array.isArray(n.resources)?n.resources:[]).map(t=>typeof t=="string"||typeof t=="number"?{resourceId:String(t)}:!se(t)||typeof t.resourceId!="string"||t.resourceId.length===0?null:{resourceId:t.resourceId}).filter(Boolean)}},Tg=(e={})=>{let n=se(e)?e:{};return{sections:(Array.isArray(n.sections)?n.sections:[]).map(t=>typeof t=="string"||typeof t=="number"?{sectionId:String(t)}:!se(t)||typeof t.sectionId!="string"||t.sectionId.length===0?null:{sectionId:t.sectionId,...typeof t.lastLineId=="string"?{lastLineId:t.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(n.resources)?n.resources:[]).map(t=>typeof t=="string"||typeof t=="number"?{resourceId:String(t)}:!se(t)||typeof t.resourceId!="string"||t.resourceId.length===0?null:{resourceId:t.resourceId}).filter(Boolean)}},Lg=(e,n)=>{let t=Tg(e),r=$g(n),o=t.sections.map(s=>({...s})),i=t.resources.map(s=>({...s}));return r.sections.forEach(s=>{let l=o.find(a=>a.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}}),r.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},pc=(e={})=>{let n=se(e)?e:{};return{saveSlots:se(n.saveSlots)?n.saveSlots:{},globalDeviceVariables:se(n.globalDeviceVariables)?n.globalDeviceVariables:{},globalAccountVariables:se(n.globalAccountVariables)?n.globalAccountVariables:{},globalRuntime:se(n.globalRuntime)?n.globalRuntime:{},accountViewedRegistry:se(n.accountViewedRegistry)?n.accountViewedRegistry:{}}},Pg=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((n,t)=>{if(!se(n))throw new Error(`Malformed applyScopedDataUpdates.updates[${t}] entry.`);let r=n.path?.startsWith(dc)?n.path.slice(dc.length):null;if(r!==null){if(!["device","account"].includes(n.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${n.scope}" at updates[${t}].`);if(r.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${n.path}" at updates[${t}].`);if(n.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${n.op}" at updates[${t}].`);return{scope:n.scope,path:n.path,op:n.op,value:n.value,variableId:r}}if(n.path==="viewedRegistry"){if(n.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${n.scope}" at updates[${t}].`);if(n.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${n.op}" at updates[${t}].`);return n}throw typeof n.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${t}].`):new Error(`Unsupported applyScopedDataUpdates path "${n.path}" at updates[${t}].`)})},Ng=(e,n)=>{let t={};return Pg(n).forEach(r=>{if(r.path==="viewedRegistry"){t.accountViewedRegistry=Lg(t.accountViewedRegistry??e.accountViewedRegistry,r.value);return}let o=r.scope==="device"?"globalDeviceVariables":"globalAccountVariables";t[o]={...e[o],...t[o],[r.variableId]:r.value}}),t},Vo=e=>{if(typeof e!="string")return null;let n=e.trim();return n.length>0?n:null},Dg=e=>{let n=Vo(e);if(!n)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return n},Mg=e=>{let n=e??globalThis.indexedDB;if(!n)throw new Error("IndexedDB is not available in this environment.");return n},Vg=({indexedDB:e,databaseName:n,objectStoreName:t})=>new Promise((r,o)=>{let i=e.open(n,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(t)||s.createObjectStore(t,{keyPath:"namespace"})},i.onsuccess=()=>{r(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${n}".`))}}),jg=async({databasePromise:e,objectStoreName:n,namespace:t})=>{let r=await e;return new Promise((o,i)=>{let a=r.transaction(n,"readonly").objectStore(n).get(t);a.onsuccess=()=>{o(a.result??null)},a.onerror=()=>{i(a.error??new Error(`Failed to read persisted namespace "${t}" from IndexedDB.`))}})},lt=async({databasePromise:e,objectStoreName:n,namespace:t,patch:r})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(n,"readwrite"),a=l.objectStore(n),c=a.get(t),u=!1,d=p=>{u||(u=!0,s(p))},f=()=>{u||(u=!0,i())};c.onerror=()=>{d(c.error??new Error(`Failed to read persisted namespace "${t}" before updating IndexedDB.`))},c.onsuccess=()=>{let p=pc(c.result),g=typeof r=="function"?r(p):r,h={namespace:t,version:1,...fc(),...p,...g},b=a.put(h);b.onerror=()=>{d(b.error??new Error(`Failed to persist namespace "${t}" to IndexedDB.`))}},l.oncomplete=()=>{f()},l.onerror=()=>{d(l.error??new Error(`IndexedDB transaction failed while updating namespace "${t}".`))},l.onabort=()=>{d(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${t}".`))}})},Fg=async({databasePromise:e,objectStoreName:n,namespace:t})=>{let r=await e;return new Promise((o,i)=>{let s=r.transaction(n,"readwrite"),a=s.objectStore(n).delete(t),c=!1,u=f=>{c||(c=!0,i(f))},d=()=>{c||(c=!0,o())};a.onerror=()=>{u(a.error??new Error(`Failed to clear persisted namespace "${t}" from IndexedDB.`))},s.oncomplete=()=>{d()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${t}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${t}".`))}})},jo=(e={})=>{let{indexedDB:n,databaseName:t=kg,objectStoreName:r=Og,namespace:o}=e,i=Mg(n),s=Dg(o),l=Vg({indexedDB:i,databaseName:t,objectStoreName:r});return{namespace:s,load:async()=>{let a=await jg({databasePromise:l,objectStoreName:r,namespace:s});return{...fc(),...pc(a)}},clear:async()=>Fg({databasePromise:l,objectStoreName:r,namespace:s}),saveSlots:async a=>lt({databasePromise:l,objectStoreName:r,namespace:s,patch:{saveSlots:se(a)?a:{}}}),saveGlobalDeviceVariables:async a=>lt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:se(a)?a:{}}}),saveGlobalAccountVariables:async a=>lt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalAccountVariables:se(a)?a:{}}}),saveGlobalRuntime:async a=>lt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalRuntime:se(a)?a:{}}}),applyScopedDataUpdates:async a=>lt({databasePromise:l,objectStoreName:r,namespace:s,patch:c=>Ng(c,a)})}},Ug=jo;var Bg=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Gg=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),mc="conditional",Bo=Symbol("conditionalAutoContinue"),zg=new Set(["sectionTransition","resetStoryAtSection"]),qg=new Set(["nextLine","nextLineFromSystem","resetStoryAtSection","sectionTransition"]),Yg=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),Fo="form",Hg=new Set(["submitForm","cancelForm"]),Wg="showImageGalleryVariant",Kg="playMusicRoomTrack",Jg="startSceneReplay",Qe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Zt=e=>e?.type===Bo,Uo=(e,n)=>e?.sectionId===n?.sectionId&&e?.lineId===n?.lineId;function Go(e){let n,t=0,r=null,o=0,i=!1,s=0,l=[],a=null,c=new Map,u=new Map,d=new Map,{handlePendingEffects:f}=e,p=(m=new Map,w=Date.now())=>new Map(Array.from(m.entries()).filter(([,v])=>w<v.expiresAt).map(([v,_])=>[v,{animation:structuredClone(_.animation),startedAt:_.startedAt,expiresAt:_.expiresAt}])),g=(m=new Map)=>Array.from(m.values()).map(w=>structuredClone(w.animation)),h=(m=Date.now())=>{c=new Map(Array.from(c.entries()).filter(([,w])=>m<w.expiresAt))},b=()=>{if(!(o>0||i)){i=!0;try{for(;n.selectPendingEffects().length>0;){let m=[...n.selectPendingEffects()];n.clearPendingEffects();try{f(m)}catch(w){throw n.clearPendingEffects(),m.forEach(v=>{n.appendPendingEffect(v)}),w}}}finally{i=!1}}},I=m=>{o+=1;let w=!1;try{let v=m();return w=!0,v}finally{o-=1,w&&b()}},E=({initialState:m,namespace:w})=>{n=uc(m),t=0,r=Vo(w),o=0,i=!1,s=0,l=[],a=null,c=new Map,u=new Map,d=new Map,n.appendPendingEffect({name:"handleLineActions"}),b()},A=()=>r,$=()=>n.selectPresentationState(),B=()=>n.selectPresentationChanges(),L=m=>n.selectSectionLineChanges(m),T=(m={})=>{t+=1;let w=Date.now();h(w);let v=u.size>0,_=p(c,w),D=v?p(u,w):new Map,X={...n.selectRenderState({activePersistentAnimations:g(_),restoredPersistentAnimations:g(D)}),id:`render-${t}`};return d.set(X.id,{builtAt:w,persistentAnimationSessions:new Map([...D.entries(),..._.entries()]),usedRestoredPersistentAnimationSessions:v}),X},z=(m={})=>T(m),G=(m={})=>T(m),S=m=>{let w=typeof m?.id=="string"&&m.id.length>0?m.id:null,v=w?d.get(w):null;w&&d.delete(w);let _=new Map;ys(m?.animations).forEach(D=>{let F=Lt(D);if(!F)return;let X=v?.persistentAnimationSessions?.get(F)??c.get(F),Z=Math.max(0,ws(D)),Ze=X?.startedAt??v?.builtAt??Date.now();_.set(F,{animation:structuredClone(D),startedAt:Ze,expiresAt:Ze+Z})}),c=_,v?.usedRestoredPersistentAnimationSessions&&(u=new Map)},q=()=>n.selectSystemState(),W=()=>n.selectAchievements(),me=m=>n.selectAchievement(m),Y=()=>n.selectSaveSlotMap(),ae=m=>n.selectSaveSlot(m),oe=m=>n.selectSaveSlotPage(m),ge=()=>n.selectImageGallery(),$e=()=>n.selectMusicRoom(),ce=()=>n.selectSceneReplay(),te=()=>n.selectIsSceneReplayActive(),fe=()=>n.selectSkipMode(),le=()=>n.selectAutoMode(),x=()=>n.selectRuntime(),C=()=>n.selectIsChoiceVisible(),O=()=>n.selectIsFormVisible(),Q=()=>n.selectActiveInteraction(),Ie=()=>n.selectPendingEffects().some(m=>m?.name==="handleLineActions"||m?.name==="render"),H=(m,w,v={})=>!Qe(w)||m!=="nextLine"?w:v.bypassChoice===!0?{...w,bypassChoice:!0}:v.interactionSource===Fo?{...w,_interactionSource:Fo}:w,Te=(m={})=>({type:Bo,payload:H("nextLine",{_conditionalContinuation:!0},m)}),he=(m,w)=>Zt(m)?{type:Bo,payload:{...m.payload,...w.payload}}:w,Ic=m=>{m.savedCheckpointOccurrences.forEach(w=>{n.markSavedRollbackCheckpointTransient(w)}),m.savedCheckpointOccurrences=[]},wc=(m,w)=>{let v=a;return a=null,!v||!Uo(v.pointer,m)||v.checkpointIndex!==w?.checkpointIndex||v.checkpointIdentity!==w?.checkpoint?[]:v.savedCheckpointOccurrences},qo=m=>{m.markCurrentCheckpointTransient&&(n.markRollbackCheckpointTransient({checkpointIndex:m.rollbackCursor?.checkpointIndex,checkpointIdentity:m.rollbackCursor?.checkpoint,sectionId:m.pointer?.sectionId,lineId:m.pointer?.lineId}),Ic(m))},Ac=(m,w,v)=>qg.has(m)?m==="resetStoryAtSection"?v?.checkpoint!==w?.checkpoint:v?.checkpoint!==w?.checkpoint&&v?.checkpointIndex>w?.checkpointIndex:!1,Ec=m=>{let w=l.at(-1);if(!w?.markCurrentCheckpointTransient)return;let v=n.selectSaveSlot({slotId:m?.slotId});v&&w.savedCheckpointOccurrences.push({slotId:m.slotId,saveSlotIdentity:v,checkpointIndex:w.rollbackCursor?.checkpointIndex,sectionId:w.pointer?.sectionId,lineId:w.pointer?.lineId})},xc=(m,w,v)=>{let _=l.at(-1);if(!_)return;let D=n.selectCurrentPointer()?.pointer,F=Ac(m,w,v);if(Uo(_.pointer,D)){let X=v?.checkpoint!==w?.checkpoint||v?.checkpointIndex!==w?.checkpointIndex;(F||X&&Yg.has(m))&&(qo(_),_.pointer=D,_.rollbackCursor=v,_.markCurrentCheckpointTransient=F,_.savedCheckpointOccurrences=[]);return}qo(_),_.pointer=D,_.rollbackCursor=n.selectRollbackCursor?.()??null,_.markCurrentCheckpointTransient=F,_.savedCheckpointOccurrences=[]},dt=(m,w)=>{if(!n[m])return;m==="updateProjectData"&&vc(w),zg.has(m)&&(s+=1);let v=n.selectIsSceneReplayActive?.()===!0,_=Gg.has(m)?p(c):null,D=n.selectRollbackCursor?.()??null,F=n[m](w);Bg.has(m)&&(u=_??new Map,c=new Map);let X=n.selectIsSceneReplayActive?.()===!0;v!==X&&(c=new Map,u=new Map);let Z=n.selectRollbackCursor?.()??null;return m==="saveSlot"&&Ec(w),xc(m,D,Z),b(),F},vc=m=>{if(!Object.prototype.hasOwnProperty.call(m??{},"projectData"))throw new Error("updateProjectData requires projectData");an(m?.projectData?.resources?.variables??{}),jn(m.projectData),Fn(m.projectData),Un(m.projectData)},Sc=(m,w,v)=>{let _=n.selectCurrentPointer()?.pointer;w!==_||v!==s||(n.appendPendingEffect({name:"clearAutoNextTimer"}),n.appendPendingEffect({name:"clearNextLineConfigTimer"}),dt("nextLineFromSystem",m.payload))},Rc=()=>({renderSequence:t,conditionalRoutingSequence:s,rollbackNavigationContexts:l.slice(),pendingRollbackLineEntrySaveHandoff:a,persistentAnimationSessions:new Map(c),restoredPersistentAnimationSessions:new Map(u),renderPersistentAnimationMetadata:new Map(d)}),Cc=m=>{t=m.renderSequence,s=m.conditionalRoutingSequence,l=m.rollbackNavigationContexts.slice(),a=m.pendingRollbackLineEntrySaveHandoff,c=new Map(m.persistentAnimationSessions),u=new Map(m.restoredPersistentAnimationSessions),d=new Map(m.renderPersistentAnimationMetadata)},Yo=(m,w={})=>I(()=>{let v=Rc();try{return n[kr](()=>{let _,D=n.selectCurrentPointer()?.pointer??null,F=n.selectRollbackCursor?.()??null,X=s,Z={pointer:D,rollbackCursor:F,markCurrentCheckpointTransient:w.rollbackSource==="line",savedCheckpointOccurrences:w.savedCheckpointOccurrences?.slice()??[]};l.push(Z);try{n.beginRollbackActionBatch({source:w.rollbackSource});try{_=m()}finally{n.endRollbackActionBatch({})}Zt(_)&&Sc(_,D,X)}finally{l.pop(),(!Uo(D,Z.pointer)||F?.checkpoint!==Z.rollbackCursor?.checkpoint)&&Z.markCurrentCheckpointTransient&&Z.savedCheckpointOccurrences.length>0&&(a={pointer:Z.pointer,checkpointIndex:Z.rollbackCursor?.checkpointIndex,checkpointIdentity:Z.rollbackCursor?.checkpoint,savedCheckpointOccurrences:Z.savedCheckpointOccurrences})}})}catch(_){throw Cc(v),_}}),Ho=(m,w,v,_={})=>{if(m===mc)return Yo(()=>{let D=er(v),F=Pr({[m]:w},D);return Wo(F[m],v,_)},_);dt(m,w)},_c=(m,w)=>{Ho(m,w)},er=m=>{if(!m)return{variables:n.selectAllVariables?n.selectAllVariables():void 0,runtime:n.selectRuntime?n.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(m,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:w,...v}=m,_=n.selectAllVariables?n.selectAllVariables():void 0;return{...v,_event:w,variables:_,runtime:n.selectRuntime?n.selectRuntime():{}}},kc=m=>{if(!Qe(m))return{templatePayload:m,literalTargetIds:null};let w=n.selectImageGalleryConfig();if(!Array.isArray(w?.groups))return{templatePayload:m,literalTargetIds:null};let v=typeof m.groupId=="string"?w.groups.find(D=>D.id===m.groupId):void 0;if(!v)return{templatePayload:m,literalTargetIds:null};let _=typeof m.variantId=="string"&&v.variants.some(D=>D.id===m.variantId);return{templatePayload:{...m,groupId:null,..._?{variantId:null}:{}},literalTargetIds:{groupId:m.groupId,..._?{variantId:m.variantId}:{}}}},Oc=m=>!Qe(m)||typeof m.trackId!="string"?{templatePayload:m,literalTargetIds:null}:n.selectMusicRoomConfig()?.tracks?.some(_=>_.id===m.trackId)?{templatePayload:{...m,trackId:null},literalTargetIds:{trackId:m.trackId}}:{templatePayload:m,literalTargetIds:null},$c=m=>!Qe(m)||typeof m.replayId!="string"?{templatePayload:m,literalTargetIds:null}:n.selectSceneReplayConfig()?.replays?.some(_=>_.id===m.replayId)?{templatePayload:{...m,replayId:null},literalTargetIds:{replayId:m.replayId}}:{templatePayload:m,literalTargetIds:null},Tc=m=>{if(!Qe(m))throw new Error("conditional action payload must be an object");if(!Array.isArray(m.branches))throw new Error("conditional action requires branches array");if(m.branches.length===0)throw new Error("conditional action requires at least one branch")},Lc=(m,w,v)=>{if(!Qe(m))throw new Error(`conditional branch at index ${w} must be an object`);if(!Qe(m.actions))throw new Error(`conditional branch at index ${w} requires actions object`);if(!Object.prototype.hasOwnProperty.call(m,"when")&&w!==v-1)throw new Error("conditional else branch must be the last branch")},Wo=(m,w,v)=>{Tc(m);let _=Te(v);for(let D=0;D<m.branches.length;D+=1){let F=m.branches[D];Lc(F,D,m.branches.length);let X=er(w);if(Object.prototype.hasOwnProperty.call(F,"when")&&!Vn(F.when,X))continue;let Ze=nr(F.actions,w,v);return Zt(Ze)?he(_,Ze):_}return _},Pc=(m,w)=>({...m??{},_form:w}),Nc=(m,w,v,_)=>{let D=dt(m,w),F=D?.submitted===!0&&D.valid===!0,X=D?.cancelled===!0;if(!(!F&&!X)&&Qe(w.actions))return nr(w.actions,Pc(v,D.form),{..._,interactionSource:Fo})},Dc=(m,w,v,_)=>{let D=er(v),F={templatePayload:w,literalTargetIds:null};m===Wg?F=kc(w):m===Kg?F=Oc(w):m===Jg&&(F=$c(w));let{templatePayload:X,literalTargetIds:Z}=F,Jo=Pr({[m]:X},D)[m],Xo=Z?{...Jo,...Z}:Jo;if(m===mc)return Wo(Xo,v,_);let Qo=H(m,Xo,_);if(Hg.has(m))return Nc(m,Qo,v,_);dt(m,Qo)},nr=(m,w,v)=>{let _;return Object.entries(m).forEach(([D,F])=>{let X=Dc(D,F,w,v);Zt(X)&&(_=he(_,X))}),_},Ko=(m,w,v={})=>Yo(()=>nr(m,w,v),v),Mc=m=>{let w=n.selectCurrentPointer()?.pointer;if(m!==w||n.selectActiveInteraction())return;let v=n.selectNextLineConfig();v?.auto?.enabled&&v.auto.trigger==="fromStart"&&n.appendPendingEffect({name:"nextLineConfigTimer",payload:{delay:v.auto.delay}})};return{init:E,handleAction:Ho,handleInternalAction:_c,handleActions:Ko,selectRenderState:z,prepareRenderState:G,commitRenderState:S,selectPresentationState:$,selectPresentationChanges:B,selectSectionLineChanges:L,selectSystemState:q,selectAchievements:W,selectAchievement:me,selectSaveSlotMap:Y,selectSaveSlot:ae,selectSaveSlotPage:oe,selectSaveSlots:Y,selectImageGallery:ge,selectMusicRoom:$e,selectSceneReplay:ce,selectIsSceneReplayActive:te,selectRuntime:x,selectIsChoiceVisible:C,selectIsFormVisible:O,selectActiveInteraction:Q,selectHasPendingRenderWork:Ie,handleLineActions:m=>{if(typeof m?.sceneReplayId=="string"){let w=n.selectActiveSceneReplayEntry?.();if(w?.replayId!==m.sceneReplayId||w?.entryId!==m.entryId)return!1}return I(()=>{let w=n.selectCurrentPointer()?.pointer,v=n.selectRollbackCursor?.()??null,_=a,D=wc(w,v),F=n.selectCurrentLine(),X=!1;if(F?.actions){try{Ko(F.actions,void 0,{rollbackSource:"line",savedCheckpointOccurrences:D})}catch(Z){throw a=_,Z}X=!0}return Mc(w),X})},getNamespace:A}}var zo=()=>{let e=0,n=null;return{getElapsed:()=>e,setElapsed:t=>{e=t},addElapsed:t=>{e+=t},getCallback:()=>n,setCallback:t=>{n=t}}},Xg=80,Qg="music-room:player",yc=new Map([["soundReady","musicRoomSoundReady"],["soundProgress","musicRoomSoundProgress"],["soundComplete","musicRoomSoundComplete"],["soundError","musicRoomSoundError"]]),gc=(e,n)=>yc.has(e)&&n?._event?.id===Qg,bc=({engine:e,routeGraphics:n,trackRenderDispatch:t},r)=>{if(e.selectHasPendingRenderWork?.())return;let o=e.prepareRenderState?.(r)??e.selectRenderState(r);t?.(o),n.render(o),e.commitRenderState?.(o)},Zg=({engine:e,routeGraphics:n,trackRenderDispatch:t,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions(o);(r?.()??0)===i&&bc({engine:e,routeGraphics:n,trackRenderDispatch:t},o)},eh=({engine:e,ticker:n,autoTimer:t},r)=>{let o=t.getCallback();o&&n.remove(o),t.setElapsed(0);let i=s=>{t.addElapsed(s.deltaMS);let l=r.delay??1e3;t.getElapsed()>=l&&(n.remove(i),t.setCallback(null),t.setElapsed(0),ut(e,"nextLineFromSystem",{}))};t.setCallback(i),n.add(i)},nh=({ticker:e,autoTimer:n},t)=>{let r=n.getCallback();r&&(e.remove(r),n.setCallback(null)),n.setElapsed(0)},th=({engine:e,ticker:n,skipTimer:t},r)=>{let o=t.getCallback();o&&n.remove(o),t.setElapsed(0);let i=s=>{t.addElapsed(s.deltaMS);let l=r?.delay??Xg;t.getElapsed()>=l&&(t.setElapsed(0),ut(e,"nextLineFromSystem",{}))};t.setCallback(i),n.add(i)},rh=({ticker:e,skipTimer:n},t)=>{let r=n.getCallback();r&&(e.remove(r),n.setCallback(null)),n.setElapsed(0)},oh=({engine:e,ticker:n,nextLineConfigTimerState:t},r)=>{let o=t.getCallback();o&&n.remove(o),t.setElapsed(0);let i=s=>{t.addElapsed(s.deltaMS);let l=r.delay??1e3;t.getElapsed()>=l&&(t.setElapsed(0),ut(e,"nextLineFromSystem",{}),n.remove(i),t.getCallback()===i&&t.setCallback(null))};t.setCallback(i),n.add(i)},ih=({ticker:e,nextLineConfigTimerState:n},t)=>{let r=n.getCallback();r&&(e.remove(r),n.setCallback(null)),n.setElapsed(0)},sh=({enqueuePersistenceWrite:e},n)=>{e(t=>t.saveSlots(n?.saveSlots))},ah=({enqueuePersistenceWrite:e},n)=>{e(t=>t.saveGlobalDeviceVariables(n?.globalDeviceVariables))},ch=({enqueuePersistenceWrite:e},n)=>{e(t=>t.saveGlobalAccountVariables(n?.globalAccountVariables))},lh=({enqueuePersistenceWrite:e},n)=>{e(t=>t.saveGlobalRuntime(n?.globalRuntime))},uh=({enqueuePersistenceWrite:e},n)=>{e(t=>{if(typeof t.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return t.applyScopedDataUpdates(n?.updates)})},hc={render:bc,saveSlots:sh,saveGlobalDeviceVariables:ah,saveGlobalAccountVariables:ch,saveGlobalRuntime:lh,applyScopedDataUpdates:uh,handleLineActions:Zg,startAutoNextTimer:eh,clearAutoNextTimer:nh,startSkipNextTimer:th,clearSkipNextTimer:rh,nextLineConfigTimer:oh,clearNextLineConfigTimer:ih},dh=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),ut=(e,n,t)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(n,t)},fh=(e=[])=>{let n=new Set,t=[];for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!dh.has(o.name)){t.unshift(o);continue}n.has(o.name)||(n.add(o.name),t.unshift(o))}return t},ph=({getEngine:e,routeGraphics:n,ticker:t,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let a=zo(),c=zo(),u=zo(),d=s??null,f=Promise.resolve(),p=null,g=null,h=!1,b=0,I=x=>{if(o){o(x);return}console.error("RouteEngine persistence write failed.",x)},E=()=>{if(d)return d;let x=e();return d=jo({indexedDB:i,namespace:l??x?.getNamespace?.()}),d},A=x=>{f=f.catch(()=>{}).then(()=>{let C=E();return x(C)}).catch(C=>{I(C)})},$=x=>{let C=typeof x?.id=="string"&&x.id.length>0?x.id:null;b+=1,p=C,h=!1},B=()=>b,L=(x={})=>{if(x?.aborted===!0)return!1;let C=typeof x?.id=="string"&&x.id.length>0?x.id:null;return C?C!==p||C===g?!1:(g=C,!0):p!==null||h?!1:(h=!0,!0)},T=(x,C={})=>{if(gc(x,C)){let Q=yc.get(x),Ie=e();return ut(Ie,Q,C?._event),!0}if(x!=="renderComplete"||!L(C))return!1;let O=e();return ut(O,"markLineCompleted",{}),!0},z=new Set(["updateFormField","submitForm","cancelForm"]),G=new Set(["updateVariable"]),S=x=>typeof x?.selectActiveInteraction=="function"?x.selectActiveInteraction():typeof x?.selectIsChoiceVisible=="function"&&x.selectIsChoiceVisible()?{source:"choice"}:null,q=x=>x?._formKey??x?.formKey,W=(x,C)=>q(x)===C?.formKey,me=(x,C)=>!x||typeof x!="object"||Array.isArray(x)?!1:x._interactionSource===C?.source,Y=(x,C)=>me(x,C)?C.source==="form"?W(x,C):!0:!1,ae=(x,C)=>!x||typeof x!="object"||Array.isArray(x)||C?.source!=="form"?!1:W(x,C),oe=(x={})=>Object.keys(x).some(C=>z.has(C)),ge=(x={},C)=>Object.entries(x).some(([O,Q])=>z.has(O)&&ae(Q,C)),$e=(x={})=>Object.keys(x).length>0&&Object.keys(x).every(C=>G.has(C)),ce=(x={},C)=>{let O=x?.actions;return C?.source==="form"?!O||typeof O!="object"||Array.isArray(O)?!1:ge(O,C)?!0:oe(O)?!1:$e(O):Y(x,C)?!0:!O||typeof O!="object"||Array.isArray(O)?!1:Object.values(O).some(Q=>Y(Q,C))},te=(x,C={})=>{if(!C?.actions)return!1;let O=S(x);return!O||O.source==="choice"?!1:!ce(C,O)},fe=({preprocessPayload:x,onEvent:C}={})=>async(O,Q={})=>{if(gc(O,Q))return T(O,Q),C?.(O,Q);let Ie=e();if(te(Ie,Q))return C?.(O,Q);let H=await x?.(O,Q)??Q;if(te(Ie,H))return C?.(O,H);if(T(O,H),H?.actions){let Te=H?._event?{_event:H._event}:H?.event?{_event:H.event}:void 0,he;H?.bypassChoice===!0?he={bypassChoice:!0}:H?._interactionSource&&(he={interactionSource:H._interactionSource}),he?Ie.handleActions(H.actions,Te,he):Ie.handleActions(H.actions,Te)}return C?.(O,H)},le=x=>{let C=e(),O=fh(x),Q=O.some(H=>H.name==="handleLineActions");O.forEach(H=>{if(!hc[H.name]&&!r)throw new Error(`Unhandled pending effect "${H.name}".`)});let Ie={engine:C,routeGraphics:n,ticker:t,autoTimer:a,skipTimer:c,nextLineConfigTimerState:u,trackRenderDispatch:$,getRenderDispatchCount:B,enqueuePersistenceWrite:A};for(let H of O){if(Q&&H.name==="render")continue;let Te=hc[H.name];if(Te){Te(Ie,H.payload);continue}r(H,Ie)}};return le.handleRouteGraphicsEvent=T,le.createRouteGraphicsEventHandler=fe,le},mh=ph;var gh=(e,n={})=>{let{resources:t={}}=n;return io(e,t)};var Hy=Go;export{Vr as DEFAULT_VISUAL_LAYER,xn as RENDER_LAYER,Ne as VISUAL_LAYER,mh as createEffectsHandler,Ug as createIndexedDbPersistence,Hy as default,$r as formatDate,au as resolveComputedVariables,gh as resolveLayoutReferences};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "route-engine-js",
3
- "version": "1.31.5",
3
+ "version": "1.33.0",
4
4
  "description": "A lightweight Visual Novel engine built in JavaScript for creating interactive narrative games with branching storylines",
5
5
  "repository": {
6
6
  "type": "git",
@@ -59,7 +59,7 @@
59
59
  "ajv": "^8.18.0",
60
60
  "husky": "^9.1.7",
61
61
  "prettier": "^3.7.4",
62
- "route-graphics": "1.30.1",
62
+ "route-graphics": "1.33.0",
63
63
  "vitest": "4.0.16"
64
64
  }
65
65
  }