route-engine-js 1.31.5 → 1.32.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/RouteEngine.js +2 -2
- package/package.json +2 -2
package/dist/RouteEngine.js
CHANGED
|
@@ -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 Wa=Object.defineProperty;var Ka=(e,t)=>{for(var r in t)Wa(e,r,{get:t[r],enumerable:!0})};var To=Symbol.for("immer-nothing"),Oo=Symbol.for("immer-draftable"),pe=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 se(e){return!!e&&!!e[pe]}function We(e){return e?No(e)||Array.isArray(e)||!!e[Oo]||!!e.constructor?.[Oo]||Zt(e)||er(e):!1}var Ja=Object.prototype.constructor.toString();function No(e){if(!e||typeof e!="object")return!1;let t=lt(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===Ja}function Hr(e){return se(e)||Ie(15,e),e[pe].base_}function Kt(e,t){Qt(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function Qt(e){let t=e[pe];return t?t.type_:Array.isArray(e)?1:Zt(e)?2:er(e)?3:0}function Ur(e,t){return Qt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Po(e,t,r){let n=Qt(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function Xa(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Zt(e){return e instanceof Map}function er(e){return e instanceof Set}function He(e){return e.copy_||e.base_}function Br(e,t){if(Zt(e))return new Map(e);if(er(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=No(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[pe];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],l=n[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(n[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(lt(e),n)}else{let n=lt(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function Wr(e,t=!1){return tr(e)||se(e)||!We(e)||(Qt(e)>1&&(e.set=e.add=e.clear=e.delete=Qa),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>Wr(n,!0))),e}function Qa(){Ie(2)}function tr(e){return Object.isFrozen(e)}var Za={};function Ke(e){let t=Za[e];return t||Ie(0,e),t}var xt;function Do(){return xt}function ec(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Ro(e,t){t&&(Ke("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Gr(e){zr(e),e.drafts_.forEach(tc),e.drafts_=null}function zr(e){e===xt&&(xt=e.parent_)}function $o(e){return xt=ec(xt,e)}function tc(e){let t=e[pe];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function ko(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[pe].modified_&&(Gr(t),Ie(4)),We(e)&&(e=Jt(t,e),t.parent_||Xt(t,e)),t.patches_&&Ke("Patches").generateReplacementPatches_(r[pe].base_,e,t.patches_,t.inversePatches_)):e=Jt(t,r,[]),Gr(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==To?e:void 0}function Jt(e,t,r){if(tr(t))return t;let n=t[pe];if(!n)return Kt(t,(o,i)=>Lo(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return Xt(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let o=n.copy_,i=o,s=!1;n.type_===3&&(i=new Set(o),o.clear(),s=!0),Kt(i,(l,a)=>Lo(e,n,o,l,a,r,s)),Xt(e,o,!1),r&&e.patches_&&Ke("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function Lo(e,t,r,n,o,i,s){if(se(o)){let l=i&&t&&t.type_!==3&&!Ur(t.assigned_,n)?i.concat(n):void 0,a=Jt(e,o,l);if(Po(r,n,a),se(a))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(We(o)&&!tr(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Jt(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&Xt(e,o)}}function Xt(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Wr(t,r)}function rc(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:Do(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=Kr;r&&(o=[n],i=vt);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return n.draft_=l,n.revoke_=s,l}var Kr={get(e,t){if(t===pe)return e;let r=He(e);if(!Ur(r,t))return nc(e,r,t);let n=r[t];return e.finalized_||!We(n)?n:n===Mr(e.base_,t)?(Fr(e),e.copy_[t]=Yr(n,e)):n},has(e,t){return t in He(e)},ownKeys(e){return Reflect.ownKeys(He(e))},set(e,t,r){let n=Vo(He(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=Mr(He(e),t),i=o?.[pe];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(Xa(r,o)&&(r!==void 0||Ur(e.base_,t)))return!0;Fr(e),qr(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return Mr(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Fr(e),qr(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=He(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){Ie(11)},getPrototypeOf(e){return lt(e.base_)},setPrototypeOf(){Ie(12)}},vt={};Kt(Kr,(e,t)=>{vt[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});vt.deleteProperty=function(e,t){return vt.set.call(this,e,t,void 0)};vt.set=function(e,t,r){return Kr.set.call(this,e[0],t,r,e[0])};function Mr(e,t){let r=e[pe];return(r?He(r):e)[t]}function nc(e,t,r){let n=Vo(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function Vo(e,t){if(!(t in e))return;let r=lt(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=lt(r)}}function qr(e){e.modified_||(e.modified_=!0,e.parent_&&qr(e.parent_))}function Fr(e){e.copy_||(e.copy_=Br(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var oc=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,n)=>{if(typeof t=="function"&&typeof r!="function"){let i=r;r=t;let s=this;return function(a=i,...c){return s.produce(a,u=>r.call(this,u,...c))}}typeof r!="function"&&Ie(6),n!==void 0&&typeof n!="function"&&Ie(7);let o;if(We(t)){let i=$o(this),s=Yr(t,void 0),l=!0;try{o=r(s),l=!1}finally{l?Gr(i):zr(i)}return Ro(i,n),ko(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===To&&(o=void 0),this.autoFreeze_&&Wr(o,!0),n){let i=[],s=[];Ke("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else Ie(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,a=>t(a,...l));let n,o;return[this.produce(t,r,(s,l)=>{n=s,o=l}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){We(e)||Ie(8),se(e)&&(e=Je(e));let t=$o(this),r=Yr(e,void 0);return r[pe].isManual_=!0,zr(t),r}finishDraft(e,t){let r=e&&e[pe];(!r||!r.isManual_)&&Ie(9);let{scope_:n}=r;return Ro(n,t),ko(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let o=t[r];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}r>-1&&(t=t.slice(r+1));let n=Ke("Patches").applyPatches_;return se(e)?n(e,t):this.produce(e,o=>n(o,t))}};function Yr(e,t){let r=Zt(e)?Ke("MapSet").proxyMap_(e,t):er(e)?Ke("MapSet").proxySet_(e,t):rc(e,t);return(t?t.scope_:Do()).drafts_.push(r),r}function Je(e){return se(e)||Ie(10,e),jo(e)}function jo(e){if(!We(e)||tr(e))return e;let t=e[pe],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=Br(e,t.scope_.immer_.useStrictShallowCopy_)}else r=Br(e,!0);return Kt(r,(n,o)=>{Po(r,n,jo(o))}),t&&(t.finalized_=!1),r}var ye=new oc,Jr=ye.produce,Th=ye.produceWithPatches.bind(ye),Nh=ye.setAutoFreeze.bind(ye),Ph=ye.setUseStrictShallowCopy.bind(ye),Dh=ye.applyPatches.bind(ye),Vh=ye.createDraft.bind(ye),jh=ye.finishDraft.bind(ye);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},L={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"}},ue=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Xr=e=>{if(!e||e.trim()==="")throw new C("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new C(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${r}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let r of t)if(e.trim().endsWith(r))throw new C(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Mo=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,r]=e.split(" in ");if(!r||r.trim()==="")throw new C(`Missing iterable expression after 'in' (got: '$for ${e}')`);let n=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of n){if(!o)throw new 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 Fo=(e,t,r=!1)=>{if(t===null)return new ue(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new ue(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new ue(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new ue(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},Uo=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new ue(`Unknown function '${e}' (${r})`)};var ic=(e,t,r={})=>{let n={},o={};r&&typeof r=="object"&&(r.functions!==void 0||r.partials!==void 0?(n=r.functions||{},o=r.partials||{}):typeof r=="object"&&(n=r));let s=V(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},V=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return J(e.var,r,n);if(e.type===y.LITERAL)return e.value;if(e.type===y.VARIABLE)return J(e.path,r,n);if(e.type===y.INTERPOLATION)return ac(e.parts,t,r,n);switch(e.type){case y.FUNCTION:return Go(e,t,r,n);case y.BINARY:return zo(e,t,r,n);case y.UNARY:return qo(e,t,r,n);case y.CONDITIONAL:return lc(e,t,r,n);case y.LOOP:return hc(e,t,r,n);case y.OBJECT:return gc(e,t,r,n);case y.ARRAY:return yc(e,t,r,n);case y.PARTIAL:return bc(e,t,r,n);case y.PATH_REFERENCE:return Ic(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Bo=new Map,sc=e=>{let t=[],r="",n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")r&&(t.push({type:"property",value:r}),r=""),n=!0;else if(i==="]"){if(n&&r){let s=r.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let l=s.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},J=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=Bo.get(e);if(!n){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),n=[];for(let a of i){let c=sc(a.trim());n.push(...c)}Bo.set(e,n)}let o=t;for(let i=0;i<n.length;i++){let s=n[i];if(s.type==="property"&&s.value in r){o=r[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},ac=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=V(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},Go=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Uo(e.name,o);let s=e.args.map(l=>V(l,t,r,n));return i(...s)},Pe=(e,t,r,n)=>{if(e.var&&!e.type)return J(e.var,r,n);switch(e.type){case y.VARIABLE:return J(e.path,r,n);case y.LITERAL:return e.value;case y.BINARY:return zo(e,t,r,n);case y.UNARY:return qo(e,t,r,n);case y.FUNCTION:return Go(e,t,r,n);default:return V(e,t,r,n)}},zo=(e,t,r,n)=>{if(e.op===L.AND||e.op===L.OR){let s=Pe(e.left,t,r,n),l=Pe(e.right,t,r,n);switch(e.op){case L.AND:return s&&l;case L.OR:return s||l}}let o=V(e.left,t,r,n),i=V(e.right,t,r,n);switch(e.op){case L.EQ:return o==i;case L.NEQ:return o!=i;case L.GT:return o>i;case L.LT:return o<i;case L.GTE:return o>=i;case L.LTE:return o<=i;case L.IN:return Array.isArray(i)?i.includes(o):!1;case L.ADD:if(typeof o!="number"||typeof i!="number")throw new ue(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case L.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new ue(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},qo=(e,t,r,n)=>{let o=e.op===ut.NOT?Pe(e.operand,t,r,n):V(e.operand,t,r,n);if(e.op===ut.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},cc=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===y.VARIABLE)if(J(o.path,r,n)){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,t,r,n):a.key,u=a.value;if(u.type===y.LITERAL)l[c]=u.value;else if(u.type===y.VARIABLE)l[c]=J(u.path,r,n);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=J(f.path,r,n);d.push(p!=null?String(p):"")}else{let p=V(f,t,r,n);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=V(u,t,r,n)}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,t,r,n):a.key,u=a.value;if(u.type===y.LITERAL)l[c]=u.value;else if(u.type===y.VARIABLE)l[c]=J(u.path,r,n);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=J(f.path,r,n);d.push(p!=null?String(p):"")}else{let p=V(f,t,r,n);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=V(u,t,r,n)}return l}}}return null},lc=(e,t,r,n)=>{let o=cc(e,t,r,n);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||Pe(s,t,r,n))return V(e.bodies[i],t,r,n)}return Yo},uc=(e,t)=>{let r=e.body,n=e.itemVar;if(r.type===y.CONDITIONAL&&r.conditions.length===1&&r.conditions[0].type===y.VARIABLE){let o=r.conditions[0].path,i=r.bodies[0];if(o.startsWith(n+".")){let s=o.substring(n.length+1);if(i.type===y.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===y.LITERAL)u[f]=p.value;else if(p.type===y.VARIABLE){let h=p.path;if(h===n)u[f]=c;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);u[f]=c[g]}else return null}else if(p.type===y.INTERPOLATION){let h=[],g=!0;for(let I of p.parts)if(typeof I=="string")h.push(I);else if(I.type===y.VARIABLE){let b=I.path;if(b===n)h.push(c!=null?String(c):"");else if(b.startsWith(n+".")){let w=b.substring(n.length+1),S=c[w];h.push(S!=null?String(S):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[f]=h.join("")}else return null}l.push(u)}}return l}}}return null},dc=(e,t)=>{let r=e.body,n=e.itemVar,o=uc(e,t);if(o!==null)return o;if(r.type===y.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let l of r.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of r.properties){let 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===n)i.push({key:a,type:"item"});else if(u.startsWith(n+".")){let d=u.substring(n.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===n)i.push({key:a,type:"item_string"});else if(d.startsWith(n+".")){let f=d.substring(n.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},fc=(e,t,r,n,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={...n,[l]:u,...a&&{[a]:c}};f.__paths__||(f.__paths__=n.__paths__||{});let p=e.iterable.path||"";if(n&&n.__paths__&&p){let h=p.split("."),g=h[0];g in n.__paths__&&(p=n.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}f.__paths__={...f.__paths__,[l]:`${p}[${c}]`,...a&&{[a]:c}};for(let h of s.properties){let g=h.parsedKey?V(h.parsedKey,t,r,f):h.key,I=h.value;if(I.type===y.LITERAL)d[g]=I.value;else if(I.type===y.VARIABLE){let b=I.path;if(b===l)d[g]=u;else if(b===a)d[g]=c;else if(b.startsWith(l+".")){let w=b.substring(l.length+1);!w.includes(".")&&!w.includes("[")?d[g]=u[w]:d[g]=J(b,r,{...n,[l]:u,...a&&{[a]:c}})}else d[g]=J(b,r,{...n,[l]:u,...a&&{[a]:c}})}else if(I.type===y.INTERPOLATION){let b=[];for(let w of I.parts)if(typeof w=="string")b.push(w);else if(w.type===y.VARIABLE){let S=w.path,O;if(S===l)O=u;else if(S===a)O=c;else if(S.startsWith(l+".")){let $=S.substring(l.length+1);!$.includes(".")&&!$.includes("[")?O=u[$]:O=J(S,r,{...n,[l]:u,...a&&{[a]:c}})}else O=J(S,r,{...n,[l]:u,...a&&{[a]:c}});b.push(O!=null?String(O):"")}else{let S={...n,[l]:u,...a&&{[a]:c}},O=V(w,t,r,S);b.push(O!=null?String(O):"")}d[g]=b.join("")}else{let b={...n,[l]:u,...a&&{[a]:c}};d[g]=V(I,t,r,b)}}i.push(d)}return i}return null},pc=(e,t,r)=>{let n=e.body;if(n.type===y.OBJECT&&n.properties.length===1&&n.properties[0].key==="$if item.visible"){let i=n.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<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},hc=(e,t,r,n)=>{let o=V(e.iterable,t,r,n);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 Fo(d,o,u)}if(!e.indexVar){let c=pc(e,o,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=dc(e,o);if(c!==null)return c}let i=fc(e,t,r,n,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(n&&n.__paths__&&l){let c=l.split("."),u=c[0];u in n.__paths__&&(l=n.__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?{...n,[e.itemVar]:o[c],[e.indexVar]:c}:{...n,[e.itemVar]:o[c]};u.__paths__||(u.__paths__=n.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${c}]`},e.indexVar&&(u.__paths__[e.indexVar]=c);let d=V(e.body,t,r,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},mc=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?V(o.parsedKey,t,r,n):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,t,r,n):u.key,f=u.value;if(f.type===y.LITERAL)a[d]=f.value;else if(f.type===y.VARIABLE)a[d]=J(f.path,r,n);else if(f.type===y.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===y.VARIABLE){let g=J(h.path,r,n);p.push(g!=null?String(g):"")}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 h of f.properties){let g=h.key,I=h.value;if(I.type===y.LITERAL)p[g]=I.value;else if(I.type===y.VARIABLE)p[g]=J(I.path,r,n);else if(I.type===y.INTERPOLATION){let b=[];for(let w of I.parts)if(typeof w=="string")b.push(w);else if(w.type===y.VARIABLE){let S=J(w.path,r,n);b.push(S!=null?String(S):"")}else{c=!1;break}if(!c)break;p[g]=b.join("")}else{c=!1;break}}if(!c)break;a[d]=p}else{c=!1;break}}if(c)return l[i]=a,l}}return null},gc=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!Pe(e.whenCondition,o,r,n))return;let i=mc(e,t,r,n);if(i!==null)return i;if(e.fast){let c={};for(let u of e.properties){let d=u.parsedKey?V(u.parsedKey,t,r,n):u.key,f=u.value;if(f.type===y.LITERAL)c[d]=f.value;else if(f.type===y.VARIABLE)c[d]=J(f.path,r,n);else if(f.type===y.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===y.VARIABLE){let g=J(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=V(h,t,r,n);p.push(g!=null?String(g):"")}c[d]=p.join("")}else c[d]=V(f,t,r,n)}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,t,r,n);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,t,r,n)}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,t,r,n);f!==void 0&&(s[c.key]=f)}else{let f=V(c.value,t,r,n);f!==void 0&&(s[c.key]=f)}}else{let d=c.parsedKey?V(c.parsedKey,t,r,n):c.key,f=V(c.value,t,r,n);f!==void 0&&(s[d]=f)}}return s},Yo={},yc=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===y.LOOP){let s=V(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=V(i,t,r,n);s!==Yo&&s!==void 0&&o.push(s)}return o},bc=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},a=t.functions||t;if(s&&!Pe(s,a,r,n))return;if(!l[o])throw new ue(`Partial '${o}' is not defined`);let c=n._partialStack||[];if(c.includes(o))throw new ue(`Circular partial reference detected: ${o}`);let u=l[o],d=r,f={...n,_partialStack:[...c,o]};if(n){d={...r};for(let p of Object.keys(n))p.startsWith("_")||(d[p]=n[p])}if(i){let p=V(i,t,r,n);d={...d,...p}}return V(u,t,d,f)},Ic=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],l=i.slice(1);if(!n||!(s in n))throw new ue(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(n.__paths__||(n.__paths__={}),!(s in n.__paths__))throw new ue(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=n.__paths__[s];if(typeof a=="number"){if(l.length>0)throw new ue(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return l.length>0&&(a+="."+l.join(".")),a};var Qr=ic;var Ac=/\$\{([^}]*)\}/g,wc=/#\{([^}]*)\}/g,Wo=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=Ec(o,t);return{isFunction:!0,type:y.FUNCTION,name:n,args:i}},Ec=(e,t={})=>e.trim()?xc(e).map(n=>vc(n.trim(),t)):[],xc=e=>{let t=[],r="",n=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,r+=l):o&&l===i&&a!=="\\"?(o=!1,i="",r+=l):!o&&l==="("?(n++,r+=l):!o&&l===")"?(n--,r+=l):!o&&l===","&&n===0?(t.push(r),r=""):r+=l}return r&&t.push(r),t},vc=(e,t={})=>{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 r=Wo(e,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};let n=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:l,type:a}of o){let c=0;for(;c<n.length;){let u=Xe(n.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 Q(n,t)}catch{return{type:y.VARIABLE,path:n}}return{type:y.VARIABLE,path:n}},Ko=/^\w+\(.*\)$/,Cc=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Sc=e=>{if(!(!e||e.trim()===""||Ko.test(e))&&Cc.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}"`)},Ho=e=>{let t=e.trim();if(Ko.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:y.PATH_REFERENCE,path:t}},Ct=(e,t={})=>{let r=e.trim();Sc(r);let n=Wo(r,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};if(r.includes("[")&&!/[\s+\-*/%|&?:]/.test(r)){let o=0;for(let i of r)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:y.VARIABLE,path:r}},Zr=(e,t={})=>{let r=e,n=[];(e.includes("\\${")||e.includes("\\#{"))&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),r=r.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${n.length}__`;return n.push(u),d}),r=r.replace(/\\(#\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${n.length}__`;return n.push(u),d}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(Ac)],i=[...r.matchAll(wc)],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=r;for(let u=0;u<n.length;u++)c=c.replace(`__ESCAPED_${u}__`,n[u]);return{type:y.LITERAL,value:c}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:c,type:u}=s[0];try{return u==="variable"?Ct(c[1],t):Ho(c[1])}catch(d){if(d.message==="Invalid array index syntax")return{type:y.LITERAL,value:r};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=r.substring(a,p);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&l.push(h)}try{let h;u==="variable"?h=Ct(f.trim(),t):h=Ho(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<r.length){let c=r.substring(a);for(let u=0;u<n.length;u++)c=c.replace(`__ESCAPED_${u}__`,n[u]);c&&l.push(c)}return{type:y.INTERPOLATION,parts:l}};var rn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Qo=e=>Object.keys(e),ae=e=>e.join("."),De=(e,t,r)=>{let n=Qo(e).filter(o=>!t.has(o));if(n.length>0)throw new C(`Unexpected key '${n[0]}' in condition JSON at '${ae(r)}'`)},Ve=(e,t)=>typeof e=="string"?Zr(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Oc(e,t):Rc(e,t):{type:y.LITERAL,value:e},_c=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new C("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new C("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new C("Empty $each body not allowed");if(r.$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 ${n}`]:r}},Oc=(e,t)=>{let r=[],n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let a=_c(i),c=Object.keys(a);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let u=Xo(c[0],a[c[0]],t,!0);r.push(u),n=!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=Xo(l[0],i[l[0]],t);r.push(a),n=!0;continue}}let s=Ve(i,t);r.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)&&(n=!0)}return{type:y.ARRAY,items:r,fast:!n}},Rc=(e,t)=>{let r=[],n=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new 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[b]of i)for(let w of a)if(b===w||b.startsWith(w+" ")||b.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[b,w]of Object.entries(f)){let S=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(S=b.slice(1)),p[S]=w,h=!0}let g=null;if(h&&(g=Ve(p,t),g.type===y.OBJECT)){let b=!1;for(let w of g.properties)if(w.value.type===y.VARIABLE||w.value.type===y.INTERPOLATION||w.value.type===y.FUNCTION||w.value.type===y.CONDITIONAL||w.value.type===y.OBJECT&&!w.value.fast||w.value.type===y.ARRAY&&!w.value.fast){b=!0;break}b&&(g.fast=!1)}let I={type:y.PARTIAL,name:u,data:g};return d!==void 0&&(I.whenCondition=Jo(d,t)),I}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=Jo(c,t),n=!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=$c(i,s,t);r.push({key:a,value:u.node}),n=!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=Ve(c,t);(u.type===y.FUNCTION||u.type===y.CONDITIONAL||u.type===y.PARTIAL||u.type===y.OBJECT&&!u.fast||u.type===y.ARRAY&&!u.fast)&&(n=!0);let d=Zr(a,t),f={key:a,value:u};(d.type!==y.LITERAL||d.value!==a)&&(f.parsedKey=d),r.push(f),s++}}}let l={type:y.OBJECT,properties:r,fast:!n};return o&&(l.whenCondition=o),l},$c=(e,t,r={})=>{let n=[],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());Xr(c);let u=Q(c,r);for(n.push(u),o.push(Ve(l,r)),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)n.push(null);else{Xr(h);let g=Q(h,r);n.push(g)}if(o.push(Ve(f,r)),i++,h===null)break}else break}return{node:{type:y.CONDITIONAL,conditions:n,bodies:o,id:a},nextIndex:i}},en={eq:L.EQ,neq:L.NEQ,gt:L.GT,gte:L.GTE,lt:L.LT,lte:L.LTE,in:L.IN,add:L.ADD,sub:L.SUBTRACT},tn={all:L.AND,any:L.OR},kc=new Set(["var","literal","call","not",...Object.keys(en),...Object.keys(tn)]),Lc=(e,t,r)=>{if(!Array.isArray(e))throw new C(`Condition JSON operator '${t}' at '${ae(r)}' requires an array`);if(e.length!==2)throw new C(`Condition JSON operator '${t}' at '${ae(r)}' requires exactly 2 operands`);return e},Tc=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new C(`Condition JSON operator '${t}' at '${ae(o)}' requires an array`);if(e.length===0)throw new C(`Condition JSON operator '${t}' at '${ae(o)}' requires at least 1 condition`);return e.map((s,l)=>he(s,n,[...o,l])).reduce((s,l)=>({type:y.BINARY,op:r,left:s,right:l}))},Nc=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],De(e,new Set(["call","args"]),r);else if(rn(e.call))n=e.call.name,o=e.call.args??[],De(e,new Set(["call"]),r),De(e.call,new Set(["name","args"]),[...r,"call"]);else throw new C(`Condition JSON call at '${ae(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new C(`Condition JSON call at '${ae(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new C(`Invalid condition JSON function name '${n}' at '${ae(r)}'`);if(!Array.isArray(o))throw new C(`Condition JSON call '${n}' at '${ae(r)}' requires args to be an array`);return{type:y.FUNCTION,name:n,args:o.map((i,s)=>he(i,t,[...r,"args",s]))}},he=(e,t={},r=["$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 C(`Condition JSON array at '${ae(r)}' must be wrapped in an operator or { literal: [...] }`);if(!rn(e))throw new C(`Invalid condition JSON value at '${ae(r)}'`);let n=Qo(e);if(n.length===0)throw new C(`Condition JSON object at '${ae(r)}' must contain an operator`);let o=n.filter(s=>kc.has(s));if(o.length===0)throw new C(`Unknown condition JSON operator '${n[0]}' at '${ae(r)}'`);if(o.length>1)throw new C(`Condition JSON at '${ae(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(De(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new C(`Condition JSON var at '${ae(r)}' requires a non-empty path`);return{type:y.VARIABLE,path:e.var}}if(i==="literal")return De(e,new Set(["literal"]),r),{type:y.LITERAL,value:e.literal};if(i==="call")return Nc(e,t,r);if(i==="not")return De(e,new Set(["not"]),r),{type:y.UNARY,op:ut.NOT,operand:he(e.not,t,[...r,"not"])};if(i in tn)return De(e,new Set([i]),r),Tc(e[i],i,tn[i],t,[...r,i]);if(i in en){De(e,new Set([i]),r);let s=Lc(e[i],i,[...r,i]);return{type:y.BINARY,op:en[i],left:he(s[0],t,[...r,i,0]),right:he(s[1],t,[...r,i,1])}}throw new C(`Unknown condition JSON operator '${i}' at '${ae(r)}'`)},Jo=(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 Q(e,t)}return rn(e)||Array.isArray(e)?he(e,t):{type:y.LITERAL,value:e}},Q=(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 Q(c,t)}let r=Xe(e,"||");if(r!==-1)return{type:y.BINARY,op:L.OR,left:Q(e.substring(0,r).trim(),t),right:Q(e.substring(r+2).trim(),t)};let n=Xe(e,"&&");if(n!==-1)return{type:y.BINARY,op:L.AND,left:Q(e.substring(0,n).trim(),t),right:Q(e.substring(n+2).trim(),t)};let o=[{op:">=",type:L.GTE},{op:"<=",type:L.LTE},{op:"==",type:L.EQ},{op:"!=",type:L.NEQ},{op:">",type:L.GT},{op:"<",type:L.LT},{op:" in ",type:L.IN}];for(let{op:c,type:u}of o){let d=Xe(e,c);if(d!==-1)return{type:y.BINARY,op:u,left:Q(e.substring(0,d).trim(),t),right:Q(e.substring(d+c.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:L.ADD},{op:" - ",type:L.SUBTRACT}];for(let{op:c,type:u}of l){let d=0;for(;d<e.length;){let f=Xe(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:Q(e.substring(0,i).trim(),t),right:Q(e.substring(i+s.op.length).trim(),t)};let a=[" * "," / "," % "];for(let c of a)if(Xe(e,c)!==-1)throw new C(`Arithmetic operations are not allowed in conditionals: "${c}"`);return e.startsWith("!")?{type:y.UNARY,op:ut.NOT,operand:Q(e.substring(1).trim(),t)}:Zo(e,t)},Xe=(e,t)=>{let r=0,n=0;for(;n<=e.length-t.length;){if(e[n]==="(")r++;else if(e[n]===")")r--;else if(r===0&&e.substring(n,n+t.length)===t)return n;n++}return-1},Pc=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 t=Number(e);return!isNaN(t)&&isFinite(t)?{type:y.LITERAL,value:t}:{type:y.VARIABLE,path:e}},Zo=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return Ct(r,t);let o=Pc(r);if(o.type===y.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:y.VARIABLE,path:r};try{return Ct(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Dc=(e,t=!1)=>{let r=t?"$each":"$for";try{Mo(e)}catch(n){if(n instanceof C&&t){let o=n.message.replace(/\$for/g,"$each");throw new C(o.replace("Parse Error: ",""))}throw n}},Xo=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let I=n?"$each":"$for";throw new C(`Invalid loop syntax (got: '${e.replace("$for",I)}')`)}let s=i[1],l=i[2].trim();Dc(l,n);let a=l.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let I=n?"$each":"$for";throw new C(`Invalid loop syntax - missing 'in' keyword (got: '${I} ${l}')`)}let c=a[1].trim(),u=a[2].trim(),d,f=null;if(c.includes(",")){let I=c.split(",").map(b=>b.trim());if(I.length!==2)throw new C(`Invalid loop variables: ${c}. Expected format: "item" or "item, index"`);d=I[0],f=I[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=Zo(u,r),g=Ve(t,r);return{type:y.LOOP,itemVar:d,indexVar:f,iterable:h,body:g,flatten:s!=="nested"}};var Vc=(e,t={})=>{let{functions:r={}}=t;return Ve(e,r)},rr=Vc;var St={};Ka(St,{now:()=>jc});var jc=()=>Date.now();var Mc=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...St,...n},s=rr(e,{functions:i}),l={};for(let[a,c]of Object.entries(o))l[a]=rr(c,{functions:i});return Qr(s,t,{functions:i,partials:l})},Qe=Mc;var Fc=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Uc=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Bc=(e,t)=>{if(Fc(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new C("Empty condition expression");return Q(e,t)}return he(e,t)},Gc=(e,t={},r={})=>{let n=Uc(r),o={...St,...n},i=Bc(e,o);return!!Pe(i,{functions:o,partials:{}},t,{})},nn=Gc;var gn=Symbol("runStoreTransaction"),un="__routeEngineConditionComparison",nr=(e,t)=>typeof e=="number"&&typeof t=="number"&&Number.isFinite(e)&&Number.isFinite(t)||typeof e=="string"&&typeof t=="string",je=Object.freeze({eq:(e,t)=>e===t,neq:(e,t)=>e!==t,gt:(e,t)=>nr(e,t)&&e>t,gte:(e,t)=>nr(e,t)&&e>=t,lt:(e,t)=>nr(e,t)&&e<t,lte:(e,t)=>nr(e,t)&&e<=t}),si=Object.freeze(Object.fromEntries(Object.keys(je).map(e=>[e,`${un}${e}`]))),zc=Object.freeze(Object.fromEntries(Object.entries(si).map(([e,t])=>[t,je[e]]))),ei=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),qc=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},or=e=>{if(Array.isArray(e))return e.map(or);if(e===null||typeof e!="object"||ei(e,"literal")||ei(e,"var"))return e;if(qc(e)?.startsWith(un))throw new Error(`Condition function names beginning with "${un}" are reserved`);let r=Object.entries(e);if(r.length===1){let[[n,o]]=r,i=si[n];if(i)return{call:i,args:o.map(or)}}return Object.fromEntries(r.map(([n,o])=>[n,or(o)]))},Ot=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return he(e),nn(or(e),t,{functions:zc})},Yc=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],ai=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:l=c=>c}=r;for(let[c,u]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...d)=>u(s(n),...d):i[c]=(...d)=>{let f;return n=Jr(n,h=>{let g=u(l(h),...d);f=g!==void 0&&!se(g)?g:void 0}),f});let a=c=>{if(typeof c!="function")throw new Error("Store transaction requires a callback");let u=n;try{return c()}catch(d){throw n=u,d}};return{...o,...i,[gn]:a}},cr=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return Jr(n,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var Hc=(e,t)=>{if(e.default!==void 0)return e.default;let r=["number","boolean","string","object"];if(!r.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${r.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},N=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),dn=(e,t,r)=>{Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0})},be=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Wc=new Set(["pageSize","groups"]),Kc=new Set(["id","variants"]),Jc=new Set(["id","imageId"]),on=(e,t,r)=>{Object.keys(e).forEach(n=>{if(!t.has(n))throw new Error(`${r} contains unsupported property "${n}"`)})},sn=(e,t)=>{if(typeof e!="string"||e.length===0)throw new Error(`${t} must be a non-empty string`)},Rt=(e={})=>{let t=e?.resources?.imageGallery;if(t===void 0)return;if(!be(t))throw new Error("resources.imageGallery must be an object");if(on(t,Wc,"resources.imageGallery"),!Number.isInteger(t.pageSize)||t.pageSize<1)throw new Error("resources.imageGallery.pageSize must be an integer greater than or equal to 1");if(!Array.isArray(t.groups))throw new Error("resources.imageGallery.groups must be an array");let r=new Set;for(let[n,o]of t.groups.entries()){let i=`resources.imageGallery.groups[${n}]`;if(!be(o))throw new Error(`${i} must be an object`);if(on(o,Kc,i),sn(o.id,`${i}.id`),r.has(o.id))throw new Error(`Duplicate image gallery group id "${o.id}"`);if(r.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(!be(a))throw new Error(`${c} must be an object`);if(on(a,Jc,c),sn(a.id,`${c}.id`),sn(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),!N(e?.resources?.images,a.imageId))throw new Error(`Image gallery variant "${o.id}.${a.id}" references unknown image "${a.imageId}"`)}}},ci=e=>{let t=se(e)?Je(e):e;return structuredClone(t)},Xc=({characterId:e,resourceCharacter:t,variables:r={}}={})=>{if(!N(t,"nameVariableId"))return;let n=t.nameVariableId,o=r?.[n];if(typeof o!="string")throw new Error(`Character "${e}" nameVariableId "${n}" must resolve to a string variable`);return o},lr=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0;if(t?.name!==void 0)return t.name;if(r!==void 0)return r;let s=Xc({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},Ce=e=>N(e,"computed"),dt=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Ce(t[r]))),we=(e,t)=>new Error(`${t} has invalid path: ${JSON.stringify(e)}`),Qc=(e,t,r)=>{if(e[0]==='"')try{return JSON.parse(e)}catch{throw we(t,r)}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,r);o+=s;continue}if(i+=1,i>=e.length-1)throw we(t,r);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,r);o+=String.fromCharCode(Number.parseInt(c,16)),i+=4;continue}let a={"\\":"\\",'"':'"',"'":"'","/":"/",n:`
|
|
2
|
+
`,r:"\r",t:" ",b:"\b",f:"\f"};if(!N(a,l))throw we(t,r);o+=a[l]}return o},li=(e,t="Computed expression var")=>{if(typeof e!="string"||e.length===0||e.trim()!==e)throw we(e,t);let r=[],n=0,o=()=>{let s=n;for(;n<e.length&&e[n]!=="."&&e[n]!=="["&&e[n]!=="]";)n+=1;let l=e.slice(s,n);if(l.length===0||l.trim()!==l||/\s/.test(l))throw we(e,t);r.push(l)},i=()=>{for(n+=1;n<e.length&&/\s/.test(e[n]);)n+=1;let s=e[n];if(/\d/.test(s??"")){let u=n;for(;n<e.length&&/\d/.test(e[n]);)n+=1;let d=e.slice(u,n);for(;n<e.length&&/\s/.test(e[n]);)n+=1;if(e[n]!=="]"||d.length>1&&d.startsWith("0"))throw we(e,t);n+=1,r.push(d);return}if(s!=='"'&&s!=="'")throw we(e,t);let l=s,a=n;n+=1;let c=!1;for(;n<e.length;){let u=e[n];if(c)c=!1;else if(u==="\\")c=!0;else if(u===l){let d=e.slice(a,n+1);for(n+=1;n<e.length&&/\s/.test(e[n]);)n+=1;if(e[n]!=="]")throw we(e,t);n+=1,r.push(Qc(d,e,t));return}n+=1}if(c||n>=e.length)throw we(e,t)};for(o();n<e.length;){if(e[n]==="."){n+=1,o();continue}if(e[n]==="["){i();continue}throw we(e,t)}return r},an=(e,t)=>{let r=e;for(let n of t){if(r==null||!N(r,n))return;r=r[n]}return r},ui=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=li(e),[n,o,...i]=r;if(n==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return an(s,i)}return n==="runtime"?an(t.runtime,r.slice(1)):an(t,r)},di=(e,t,r)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(r!==void 0&&t.length!==r)throw new Error(`Computed expression operator "${e}" requires ${r} operand(s)`)},fn=(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`)},Zc=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},ve=(e,t,r,n)=>(di(e,t,n),t.map(o=>ar(o,r))),Ae=(e,t,r,n)=>{let o=ve(e,t,r,n);return o.forEach(i=>Zc(e,i)),o},el=(e,t,r)=>{switch(e){case"var":return ui(t,r);case"add":{let[n,o]=Ae(e,t,r,2);return n+o}case"sub":{let[n,o]=Ae(e,t,r,2);return n-o}case"mul":{let[n,o]=Ae(e,t,r,2);return n*o}case"div":{let[n,o]=Ae(e,t,r,2);return n/o}case"mod":{let[n,o]=Ae(e,t,r,2);return n%o}case"neg":{let[n]=Ae(e,t,r,1);return-n}case"round":{let[n]=Ae(e,t,r,1);return Math.round(n)}case"floor":{let[n]=Ae(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=Ae(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=Ae(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=Ae(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=Ae(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=ve(e,t,r,2);return je.eq(n,o)}case"neq":{let[n,o]=ve(e,t,r,2);return je.neq(n,o)}case"gt":{let[n,o]=ve(e,t,r,2);return je.gt(n,o)}case"gte":{let[n,o]=ve(e,t,r,2);return je.gte(n,o)}case"lt":{let[n,o]=ve(e,t,r,2);return je.lt(n,o)}case"lte":{let[n,o]=ve(e,t,r,2);return je.lte(n,o)}case"in":{let[n,o]=ve(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return fn(e,t),t.every(n=>!!ar(n,r));case"or":case"any":return fn(e,t),t.some(n=>!!ar(n,r));case"not":{let[n]=ve(e,t,r,1);return!n}case"length":{let[n]=ve(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:be(n)?Object.keys(n).length:0}case"includes":{let[n,o]=ve(e,t,r,2);return typeof n=="string"?typeof o=="string"&&n.includes(o):Array.isArray(n)?n.includes(o):!1}case"literal":return ci(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},ar=(e,t={})=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let r=Object.entries(e);if(r.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[n,o]]=r;return el(n,o,t)},pn=(e,t)=>{if(e===null||typeof e!="object"||N(e,"literal"))return e;if(N(e,"var"))return{literal:ui(e.var,t)};if(N(e,"call"))throw new Error("Function calls are not supported in computed-variable conditions");return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Array.isArray(n)?n.map(o=>pn(o,t)):pn(n,t)]))},tl=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return he(e),Ot(pn(e,t))},fi=(e,t)=>{if(!be(e))throw new Error(`${t} must be an object`);let r=N(e,"expr"),n=N(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},cn=(e,t,r)=>(fi(e,t),N(e,"value")?ci(e.value):ar(e.expr,r)),rl=(e,t={},r="unknown")=>{if(!be(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=N(e,"expr"),o=N(e,"value");if(N(e,"branches")){if(n||o)throw new Error(`Computed variable "${r}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${r}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${r}" branches must not be empty`);if(!be(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let l=e.branches[s];if(!be(l))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!N(l,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(tl(l.when,t))return cn(l,`Computed variable "${r}" branch ${s}`,t)}return cn(e.default,`Computed variable "${r}" default`,t)}if(n===o)throw new Error(`Computed variable "${r}" must contain exactly one of expr, value, or branches`);return cn(e,`Computed variable "${r}"`,t)},pi=(e,t,r)=>{switch(t){case"number":if(typeof r!="number"||!Number.isFinite(r))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(r)?"array":typeof r}`);return;case"boolean":if(typeof r!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(r)?"array":typeof r}`);return;case"string":if(typeof r!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(r)?"array":typeof r}`);return;case"object":if(r===null||typeof r!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof r}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},nl=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}),ol=new Set(["and","or","all","any"]),il=new Set(["add","sub","mul","div","mod","neg","round","floor","ceil","min","max","clamp","length"]),sl=new Set(["add","sub","mul","div","mod","neg","round","floor","ceil","min","max","clamp"]),al=new Set(["eq","neq","gt","gte","lt","lte","in","and","or","all","any","not","includes"]),cl=new Set(["all","any","eq","neq","gt","gte","lt","lte","in","add","sub"]),hi=new WeakMap,ti=e=>e===null?"null":Array.isArray(e)?"object":typeof e,ir=(e,t,r)=>{for(let n of Object.keys(e))if(!t.has(n))throw new Error(`${r} contains unsupported property "${n}"`)},ll=(e,t,r,n)=>{if(r!==void 0&&r!==t)throw new Error(`Computed variable "${e}" ${n} expected type ${t}, got ${r}`)},mi=(e,{variableId:t,variableConfigs:r,dependencies:n,path:o})=>{let i=`Computed variable "${t}" ${o} var`,[s,l,...a]=li(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(!N(r,l))throw new Error(`Computed variable "${t}" ${o} references unknown variable "${l}"`);let c=r[l];return Ce(c)&&n.add(l),a.length===0?c?.type:void 0},gi=(e,{variableId:t,variableConfigs:r,dependencies:n,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 ti(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 mi(l,{variableId:t,variableConfigs:r,dependencies:n,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 ti(l)}let a=nl[s];if(a===void 0&&!ol.has(s))throw new Error(`Unknown computed expression operator: ${s}`);a===void 0?fn(s,l):di(s,l,a);let c=l.map((u,d)=>gi(u,{variableId:t,variableConfigs:r,dependencies:n,path:`${o}.${s}[${d}]`}));if(sl.has(s)&&c.forEach(u=>{if(u!==void 0&&u!=="number")throw new Error(`Computed expression operator "${s}" requires numeric operands`)}),il.has(s))return"number";if(al.has(s))return"boolean"},ul=(e,{variableId:t,variableConfigs:r,dependencies:n,path:o})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");try{he(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"||N(s,"literal"))return;if(N(s,"var")){mi(s.var,{variableId:t,variableConfigs:r,dependencies:n,path:l});return}if(N(s,"call"))throw new Error(`Computed variable "${t}" ${l} function calls are not supported`);if(N(s,"not")){i(s.not,`${l}.not`);return}let a=Object.keys(s).find(c=>cl.has(c));s[a].forEach((c,u)=>{i(c,`${l}.${a}[${u}]`)})};i(e,o)},ln=(e,{variableId:t,variableConfig:r,variableConfigs:n,dependencies:o,path:i,allowedKeys:s=new Set(["expr","value"])})=>{if(fi(e,`Computed variable "${t}" ${i}`),ir(e,s,i),N(e,"value")){pi(t,r.type,e.value);return}let l=gi(e.expr,{variableId:t,variableConfigs:n,dependencies:o,path:`${i}.expr`});ll(t,r.type,l,`${i}.expr`)},dl=(e,t,r)=>{let n=t.computed;if(!be(n))throw new Error(`Computed variable "${e}" computed must be an object`);let o=new Set,i=N(n,"expr"),s=N(n,"value");if(N(n,"branches")){if(ir(n,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(n.branches))throw new Error(`Computed variable "${e}" branches must be an array`);if(n.branches.length===0)throw new Error(`Computed variable "${e}" branches must not be empty`);if(!be(n.default))throw new Error(`Computed variable "${e}" requires default`);return n.branches.forEach((a,c)=>{if(!be(a))throw new Error(`Computed variable "${e}" branch ${c} must be an object`);if(ir(a,new Set(["when","expr","value"]),`Computed variable "${e}" branch ${c}`),!N(a,"when"))throw new Error(`Computed variable "${e}" branch ${c} requires when`);ul(a.when,{variableId:e,variableConfigs:r,dependencies:o,path:`computed.branches[${c}].when`}),ln(a,{variableId:e,variableConfig:t,variableConfigs:r,dependencies:o,path:`computed.branches[${c}]`,allowedKeys:new Set(["when","expr","value"])})}),ln(n.default,{variableId:e,variableConfig:t,variableConfigs:r,dependencies:o,path:"computed.default"}),o}if(ir(n,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 ln(n,{variableId:e,variableConfig:t,variableConfigs:r,dependencies:o,path:"computed"}),o},Ze=(e={})=>{if(!be(e))throw new Error("Variable configs must be an object");if(N(e,"__proto__"))throw new Error('Variable id "__proto__" is reserved');if(N(e,""))throw new Error("Variable ids must not be empty");let t=new Map;Object.entries(e).forEach(([i,s])=>{if(Ce(s)){if(!be(s))throw new Error(`Computed variable "${i}" must be an object`);if(!N(s,"type"))throw new Error(`Computed variable "${i}" requires type`);if(!N(s,"scope"))throw new Error(`Computed variable "${i}" requires scope`);if(N(s,"default"))throw new Error(`Computed variable "${i}" must not declare a top-level default`);if(kt(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,dl(i,s,e))}});let r=new Set,n=[];t.forEach((i,s)=>{if(r.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),r.add(c.variableId),n.push(c.variableId);continue}let u=c.dependencies[c.nextDependencyIndex];if(c.nextDependencyIndex+=1,r.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(n)});return hi.set(e,o),o},$t=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let{evaluationOrder:o}=hi.get(r)??Ze(r),i=dt(e,r),s=Object.entries(r).filter(([,I])=>Ce(I)).map(([I])=>I),l=Object.create(null),a=[],c=new Map(o.map((I,b)=>[I,b])),u=-1,d=!1,f=I=>{if(N(l,I))return l[I];let b=r[I];if(!Ce(b))return N(i,I)?i[I]:void 0;let w=a.indexOf(I);if(w>=0){let S=[...a.slice(w),I].join(" -> ");throw new Error(`Computed variable cycle detected: ${S}`)}a.push(I);try{let S=rl(b.computed,g,I);return pi(I,b.type,S),dn(l,I,S),S}finally{a.pop()}},p=I=>{if(N(l,I))return l[I];let b=r[I];if(!Ce(b))return N(i,I)?i[I]:void 0;let w=c.get(I);if(n&&!d&&w!==void 0&&w>u){d=!0;try{for(let S=u+1;S<=w;S+=1)f(o[S]),u=S}finally{d=!1}return l[I]}return f(I)},h=new Proxy({},{get:(I,b)=>{if(typeof b=="string")return p(b)},has:(I,b)=>typeof b=="string"&&(N(i,b)||s.includes(b)),ownKeys:()=>[...new Set([...Object.keys(i),...s])],getOwnPropertyDescriptor:(I,b)=>{if(!(typeof b!="string"||!N(i,b)&&!s.includes(b)))return{enumerable:!0,configurable:!0}}}),g={variables:h,runtime:t,resolveVariable:p};return n?(s.forEach(I=>{p(I)}),{...i,...l}):h},fl=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>{let o=r??n?.resources?.variables??{};return Ze(o),$t({variables:e,runtime:t,variableConfigs:o,eager:!0})},ur=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(Ce(o))return;let i=Hc(o,n);o.scope==="context"?dn(t,n,i):dn(r,n,i)}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},kt=(e,t)=>{let r=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!r.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${r.join(", ")}`)},dr=(e,t,r)=>{let n={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=n[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${r}`);if(!Object.values(n).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${r}" of type "${e}". Valid operations: ${o.join(", ")}`)},pl=2,ri=12,yi=(e=pl)=>{if(!Number.isInteger(e)||e<0||e>ri)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${ri}.`);return e},hl=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},sr=e=>typeof e=="number"&&Number.isFinite(e),yn=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!sr(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!sr(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!sr(r))throw new Error(`Operation "divide" requires value to be a number for variable "${n}".`);if(t==="divide"){if(r===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${n}".`);yi(o.roundTo)}}},fr=(e,t,r,n={})=>{let o=(s,l,a)=>{let c=s??l;if(!sr(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 r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return hl(o(e,0,"current value")/i(r),yi(n.roundTo));case"increment":return o(e,0,"current value")+o(r,1,"value");case"decrement":return o(e,0,"current value")-o(r,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var bn=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let r=new Date(e),n=s=>String(s).padStart(2,"0"),o=String(r.getFullYear()),i={DD:n(r.getDate()),MM:n(r.getMonth()+1),MMM:Yc[r.getMonth()],YYYY:o,YY:o.slice(-2),HH:n(r.getHours()),mm:n(r.getMinutes()),ss:n(r.getSeconds())};return t.replace(/YYYY|MMM|YY|MM|DD|HH|mm|ss/g,s=>i[s])},ml=(e,t)=>{let r=i=>i?.ui,n=r(e),o=r(t);return JSON.stringify(n)===JSON.stringify(o)?null:n&&!o?{changeType:"delete",data:e}:o&&!n?{changeType:"add",data:t}:o&&n?{changeType:"update",data:t}:null},_t=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,gl=(e,t)=>{let r=e?.character?.sprite,n=t?.character?.sprite,o=_t(r)?r:void 0,i=_t(n)?n: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},ni=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};e.transformId!==void 0&&(t.transformId=e.transformId);for(let r of["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"])e[r]!==void 0&&(t[r]=e[r]);for(let r of["animationName","animationSpeed","loop"])e[r]!==void 0&&(t[r]=e[r]);return t},oi=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},ii=(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,yl=(e,t)=>{let r={},n=ii(ni(e),ni(t)),o=ii(oi(e),oi(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},In=(e={},t={})=>{let r={},n=["sfx","voice"],o=a=>{let c=e[a],u=t[a];u&&!c?r[a]={changeType:"add",data:u}:c&&!u?n.includes(a)||(r[a]={changeType:"delete",data:c}):c&&u&&JSON.stringify(c)!==JSON.stringify(u)&&(r[a]={changeType:"update",data:u})},i=yl(e.background,t.background);i&&(r.background=i),o("screen"),o("bgm"),o("voice");let s=ml(e.dialogue,t.dialogue);s&&(r.dialogue=s);let l=gl(e.dialogue,t.dialogue);return l&&(r.dialogueSprite=l),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),r},An=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,!t.background.resourceId&&!t.background.colorId&&delete t.background);let r=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};r("layout"),r("choice"),r("form"),r("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 n=(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 n("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),n("visual",o=>o.resourceId||o.transformId),t},bl=(e,t)=>{if(!e||!t)return;let r=e;for(let n of t.split(".")){if(r==null||!(n in Object(r)))return;r=r[n]}return r},Il=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let r=e.slice(7),n=bl(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},Al={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"])},bi=(e,t)=>{let r=e[e.length-1];return r?Al[r]?.has(t)===!0:!1},hn=(e,t,r=[])=>Array.isArray(e)?e.map(n=>hn(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,bi(r,n)?o:hn(o,t,[...r,n])])):Il(e,t),mn=(e,t,r=[])=>Array.isArray(e)?e.map(n=>mn(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,bi(r,n)?o:mn(o,t,[...r,n])])):typeof e=="string"?Qe(e,t):e,wn=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let r=hn(e,t._event);return mn(r,t)};var H=e=>structuredClone(se(e)?Je(e):e),U=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ii=e=>e?.animations?.playback?.continuity==="persistent",j=(e,t)=>U(e??{},t)&&e[t]!==void 0,Lt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:H(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},wl=e=>j(e,"opacity")||j(e,"blur"),Ci=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Si=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],En=["animationName","animationSpeed","loop"],El=e=>Ci.some(t=>j(e,t)),_i=e=>e?.text&&j(e.text,"content")&&j(e.text,"textStyleId"),Oi=e=>j(e,"text"),xl=(e,t)=>e.resourceId?!0:_i(e)?!t?.text:!1,vl=(e,t)=>{let r={...H(e),...t};return t.text&&e.text&&(r.text={...H(e.text),...H(t.text)}),r},Cl=(e,t)=>{if(Oi(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!_i(e)&&!t?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},Ai=e=>Si.some(t=>j(e,t)),wi=e=>En.some(t=>j(e,t)),Sl=(e,t,{hasAuthoredTransformId:r=!1}={})=>{if(!t)return e;for(let n of Si)!r&&!j(e,n)&&j(t,n)&&(e[n]=t[n]),U(e,n)&&e[n]===void 0&&delete e[n];return e},Ri=(e,t,r)=>{let n=e[r];return n?.id===t?.id?n:e.find(o=>o.id===t?.id)},_l=(e,t)=>{if(!t)return e;for(let r of Ci)!j(e,r)&&j(t,r)&&(e[r]=t[r]),U(e,r)&&e[r]===void 0&&delete e[r];return e},Ol=(e,t)=>(t&&(!j(e,"opacity")&&j(t,"opacity")&&(e.opacity=t.opacity),!j(e,"blur")&&j(t,"blur")&&(e.blur=H(t.blur)),U(e,"opacity")&&e.opacity===void 0&&delete e.opacity,U(e,"blur")&&e.blur===void 0&&delete e.blur),e),$i=(e,t,r=[],{hasPatchFn:n=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,l)=>{let a=Ri(r,s,l),c=t(s,a),u=wl(s),d=El(s),f=n(s),p=U(s,"animations"),h=H(s);return!c&&(u||d||f)&&a&&(h=o?o(a,h):{...H(a),...h},p||delete h.animations),Ol(_l(h,a),a)}).filter(s=>t(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},Rl=e=>{if(e){if(e.character&&U(e.character,"name"))return e.character.name;if(U(e,"characterName"))return e.characterName}},ki=e=>!!e?.character&&U(e.character,"sprite"),$l=e=>{let t={},r=!1,n=Rl(e);return n!==void 0&&(t.name=n,r=!0),ki(e)&&(t.sprite=H(e.character.sprite),r=!0),r?t:void 0},Ei=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},xi=({dialogueState:e,dialogueAction:t,persistCharacter:r})=>U(t,"persistSprite")?t.persistSprite===!0:U(e,"persistSprite")?e.persistSprite===!0:r&&!U(t,"characterId"),vi=({previousCharacter:e,characterFields:t,hasCharacterId:r,persistCharacter:n,persistSprite:o,hasExplicitPersistSprite:i,isAppendingAdvDialogueContent:s})=>{let l={},a=e??{},c=t??{},u=s&&!r,d=u&&!i;return U(c,"name")?l.name=c.name:(n&&!r||u)&&U(a,"name")&&(l.name=H(a.name)),U(c,"sprite")?l.sprite=H(c.sprite):(o||d)&&U(a,"sprite")&&(l.sprite=H(a.sprite)),Object.keys(l).length>0?l:void 0},kl=({dialogueState:e,content:t,append:r=!1})=>{if(!r||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let n=Array.isArray(e.content)?e.content:[];n.length>0?e.initialRevealedContent=n.map(o=>H(o)):delete e.initialRevealedContent,e.content=[...n,...t]},Ll=()=>({}),Tl=(e,t)=>{if(!t.screen)return;let r=j(t.screen,"opacity"),n=j(t.screen,"blur"),o=U(t.screen,"animations");if(!r&&!n){o||delete e.screen;return}let i=e.screen,s={};if(r?s.opacity=t.screen.opacity:j(i,"opacity")&&(s.opacity=i.opacity),n?s.blur=H(t.screen.blur):j(i,"blur")&&(s.blur=H(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},Nl=(e,t)=>{if(t.background){let r=j(t.background,"resourceId"),n=j(t.background,"colorId"),o=j(t.background,"opacity"),i=j(t.background,"blur"),s=j(t.background,"transformId"),l=Ai(t.background),a=wi(t.background),{animationsOnly:c,state:u}=Lt(t.background,p=>j(p,"resourceId")||j(p,"colorId")||j(p,"opacity")||j(p,"blur")||j(p,"transformId")||Ai(p)||wi(p));if(c){e.background=e.background?{...H(e.background),...u}:u;return}if(!r&&!n&&!o&&!i&&!s&&!l&&!a){delete e.background;return}let d=e.background,f=H(t.background);if(!r&&d?.resourceId){f.resourceId=d.resourceId,!U(f,"transformId")&&d.transformId&&(f.transformId=d.transformId);for(let p of En)!j(f,p)&&j(d,p)&&(f[p]=d[p])}Sl(f,d,{hasAuthoredTransformId:s}),!n&&d?.colorId&&(f.colorId=d.colorId),!o&&j(d,"opacity")&&(f.opacity=d.opacity),!i&&j(d,"blur")&&(f.blur=H(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 En)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")&&Ii(d)&&(f.animations=H(d.animations)),e.background=f}else e.background?.animations&&!Ii(e.background)&&(e.background.animations={})},Pl=(e,t)=>{if(!t.dialogue){if(e.dialogue&&(Ei(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=xi({dialogueState:e.dialogue,dialogueAction:{},persistCharacter:u});u||delete e.dialogue.characterId,e.dialogue.character=vi({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 r=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:u,state:d}=Lt(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 n=t.dialogue.append===!0&&r!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&kl({dialogueState:e.dialogue,content:t.dialogue.content,append:n}),U(t.dialogue,"textSpeed")?e.dialogue.textSpeed=t.dialogue.textSpeed:delete e.dialogue.textSpeed;let o=U(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=xi({dialogueState:e.dialogue,dialogueAction:t.dialogue,persistCharacter:o});U(t.dialogue,"persistSprite")&&(e.dialogue.persistSprite=i);let s=U(t.dialogue,"characterId"),l=$l(t.dialogue),a=ki(t.dialogue);s?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId;let c=vi({previousCharacter:e.dialogue.character,characterFields:l,hasCharacterId:s,persistCharacter:o,persistSprite:i,hasExplicitPersistSprite:U(t.dialogue,"persistSprite"),isAppendingAdvDialogueContent:n});if(c?e.dialogue.character=c:delete e.dialogue.character,a||Ei(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=H(e.dialogue.character)),e.dialogue.lines.push(u)}},Dl=(e,t)=>{if(t.sfx){let r=Array.isArray(t.sfx.items)&&t.sfx.items.length>0,n=Array.isArray(t.sfx.channels)&&t.sfx.channels.length>0;if(!r&&!n){delete e.sfx;return}e.sfx=H(t.sfx)}else e.sfx&&delete e.sfx},Vl=(e,t)=>{if(t.bgm){let r=Array.isArray(t.bgm.sounds);if(!t.bgm.resourceId&&!r||r&&t.bgm.sounds.length===0){e.bgm=void 0;return}e.bgm=H(t.bgm),t.bgm.resourceId&&(e.bgm.loop=t.bgm.loop??!0)}},jl=(e,t)=>{if(t.visual){let r=e.visual?.items||[];t.visual.items?.forEach((i,s)=>{Cl(i,Ri(r,i,s))});let{hasValidItems:n,processedItems:o}=$i(t.visual.items,xl,r,{hasPatchFn:Oi,mergeItemFn:vl});n?e.visual={items:o}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(r=>r.animations?{...r,animations:{}}:r))},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:r,processedItems:n}=$i(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);r?e.character={items:n}:delete e.character},Fl=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Ul=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=Lt(t.layout,o=>!!o.resourceId);if(r){e.layout=n;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},Bl=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=Lt(t.choice,o=>!!o.resourceId);if(r){e.choice={...e.choice,...n};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},Gl=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=Lt(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=H(t.form)}else e.form&&delete e.form},zl=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},ql=(e,t)=>{if(t.voice){let r=Array.isArray(t.voice.sounds);if(!t.voice.resourceId&&!r||r&&t.voice.sounds.length===0){delete e.voice;return}e.voice=H(t.voice)}else e.voice&&delete e.voice},Yl=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},et=e=>cr(Ll,[Yl,Tl,Nl,Dl,Vl,jl,Pl,Ml,Fl,Ul,Bl,Gl,zl,ql])(e);var ft=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=Qe(e,t);return r&&typeof r=="object"?e:r};var Hl=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"}}),tt=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}),Tt=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Li=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"}),xn=Object.freeze(["dialogueTextSpeed","autoForwardDelay","autoForwardSpeed","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),vn=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Wl=(e,t)=>{if(t.startsWith("global.")){let r=t.slice(7);return e?.global?.[r]}if(t.startsWith("context.runtime.")){let r=t.slice(16),n=Array.isArray(e?.contexts)?e.contexts:[];return n[n.length-1]?.runtime?.[r]}},rt=e=>Object.fromEntries(Object.entries(Hl).map(([t,r])=>{let n=Wl(e,r.source),o=n!==void 0?n:tt[t]??Tt[t];return[t,o]})),Me=(e,t)=>rt(e)[t],Ti=(e={})=>Object.fromEntries(xn.map(t=>[t,e[t]??tt[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}),ke=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}),Cn=ke.BEHIND_DIALOGUE,Sn=Object.freeze(Object.values(ke).sort((e,t)=>e-t));var Kl={__arrayOrEmpty:e=>Array.isArray(e)?e:[],objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:bn},Jl=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+?)(?::)?$/,Nt=e=>Array.isArray(e)?e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).length!==1)return Nt(t);let[r]=Object.keys(t),n=Jl.exec(r);if(!n)return Nt(t);let[,o,i,s]=n,l=`$for ${o}${i?`, ${i}`:""} in __arrayOrEmpty(${s.trim()})`,a=Array.isArray(t[r])?t[r]:[];return{[l]:Nt(a)}}):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Nt(r)])),Le=(e,t)=>{let r={functions:Kl};return Qe(Nt(e),t,r)},Gn=({animationType:e,animationId:t,animationPath:r})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${r}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},Xl=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);if(Gn({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n!==void 0){let s=tu(n,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},Ql=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Gn({animationType:e.type,animationId:t,animationPath:r}),e.type},Zl=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},eu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},tu=(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 r={};return e.continuity!==void 0&&(r.continuity=e.continuity),e.speed!==void 0&&e.speed!==1&&(r.speed=e.speed),Object.keys(r).length>0?r:void 0},ru=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},nt=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),qi=e=>e?.playback?.continuity==="persistent",Nn=e=>Array.isArray(e)?e.map(Nn):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=Nn(e[r]),t),{}),yr=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(Nn(t))},Yi=(e=[])=>e.filter(t=>qi(t)).map(t=>structuredClone(t)),Hi=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,r)=>{let n=typeof r?.duration=="number"&&Number.isFinite(r.duration)?r.duration:0;return t+n},0):0,_n=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,Hi(r)),0),Wi=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(_n(e.tween),_n(e.prev?.tween),_n(e.next?.tween),Hi(e.mask?.progress))/ru(e),Ni=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let r=new Set(t.map(yr).filter(Boolean));return e.some(n=>{if(!qi(n))return!1;let o=yr(n);return o?r.has(o):!1})},Se=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||Ni({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:Ni({animationInstances:e,activePersistentAnimations:o}),nu=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),ou=(e,t)=>{if(nu(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},iu=({resources:e,animationId:t,playback:r,instanceId:n,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?Xl({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},su=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Gn({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},zn=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(su(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Pn=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(r=>r===null||typeof r!="object"||Array.isArray(r)))throw new Error(`${t} must be an array of objects`);return e},au=({content:e,path:t,variables:r})=>Pn(e,t).reduce((n,o)=>{let i=ft(o.text,{variables:r});return n+`${i??""}`.length},0),Pi=(e=[])=>{let t=new Map;for(let r of e)r?.id&&t.set(r.id,(t.get(r.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,r])=>r>1).map(([r])=>r))},pr=(e,t=0,r=new Set)=>{if(!r.has(e?.id))return`character-container-${e.id}`;let n=e?.sprites?.map(({resourceId:o})=>o)||[];return n.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${n.join("-")}`},hr=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return r},cu=(e,t={})=>{if(!t?.transformId)return;let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for background`);return r},lu=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],uu=(e={})=>lu.some(t=>nt(e,t)),Ki=(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"}},gr=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},du=(e={})=>e.textStyles||{},fu=(e={})=>e.images||{},pu=.5,hu=(e={},t,r)=>{if(t){if(!e.animations?.[t])throw new Error(`Animation '${t}' not found in spritesheet resource '${r}'`);return t}return Object.keys(e.animations??{})[0]},Ji=({id:e,resourceId:t,spritesheet:r,animationName:n,animationSpeed:o,loop:i,transform:s={}}={})=>{let l=hu(r,n,t),a=l?r.animations?.[l]:void 0;if(!a){console.warn(`Spritesheet animation not found: ${t}`);return}return{id:e,type:"spritesheet-animation",...s,width:r.width,height:r.height,src:r.fileId,atlas:r.jsonData,playback:{frames:a.frames,animationSpeed:o??a.animationSpeed??pu,loop:i??a.loop??!0}}},Xi=({id:e,item:t,resources:r={}}={})=>{let n=r.images?.[t.resourceId];if(n)return{type:"sprite",id:e,src:n.fileId,width:n.width,height:n.height,x:0,y:0};let o=r.spritesheets?.[t.resourceId];if(o)return Ji({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}`)},mu=(e={})=>e.colors||{},gu=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Vt=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,mt=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},On=(e,t,r)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);return e},Rn=(e,t,r,n,{minimum:o}={})=>{if(e===void 0)return n;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 "${r}" must be ${i}`)}return e},Ar=(e,t)=>{if(typeof e!="string"||!gu.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(r=>r.repeat(2)).join("")}`:e},Di=(e,t,r)=>{let n=Ar(e,r);if(t===1)return n;let o=Number.parseInt(n.slice(1,3),16),i=Number.parseInt(n.slice(3,5),16),s=Number.parseInt(n.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},yu=(e={},t)=>{let r=du(e)?.[t];if(!r)throw new Error(`Text style "${t}" not found`);let o=(Array.isArray(r.fontId)?r.fontId:[r.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?.[r.colorId];if(!i)throw new Error(`Color "${r.colorId}" not found for text style "${t}"`);let s=On(r.colorAlpha,"colorAlpha",t),l={fontFamily:Array.isArray(r.fontId)?o.join(", "):o[0],fontSize:r.fontSize??16,fontWeight:r.fontWeight??"400",fontStyle:r.fontStyle??"normal",lineHeight:r.lineHeight??1.2,fill:Di(i.hex,s,`Color "${r.colorId}" for text style "${t}"`)};if(r.align!==void 0&&(l.align=r.align),r.wordWrap!==void 0&&(l.wordWrap=r.wordWrap),r.breakWords!==void 0&&(l.breakWords=r.breakWords),r.wordWrapWidth!==void 0&&(l.wordWrapWidth=r.wordWrapWidth),r.strokeColorId){let a=e.colors?.[r.strokeColorId];if(!a)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let c=On(r.strokeAlpha,"strokeAlpha",t);l.strokeColor=Di(a.hex,c,`Stroke color "${r.strokeColorId}" for text style "${t}"`)}else if(r.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);if(r.strokeWidth!==void 0&&(l.strokeWidth=r.strokeWidth),r.shadow!==void 0){let a=e.colors?.[r.shadow.colorId];if(!a)throw new Error(`Shadow color "${r.shadow.colorId}" not found for text style "${t}"`);l.shadow={color:Ar(a.hex,`Shadow color "${r.shadow.colorId}" for text style "${t}"`),alpha:On(r.shadow.alpha,"shadow.alpha",t),blur:Rn(r.shadow.blur,"blur",t,0,{minimum:0}),offsetX:Rn(r.shadow.offsetX,"offsetX",t,2),offsetY:Rn(r.shadow.offsetY,"offsetY",t,2)}}return l},Dn=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Dn(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${r}". Use textStyleId instead`);let n={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(n[o]=Dn(i,t,Vt(r,o)));return e.textStyleId!==void 0&&(mt(e.textStyleId,r,"textStyleId"),n.textStyle=yu(t,e.textStyleId)),n},qn=(e={},t)=>{let r=mu(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return Ar(r.hex,`Color "${t}"`)},Qi=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",$n=(e,t,r)=>{let n=e?.[t];if(!(!n||typeof n!="object"||Array.isArray(n))&&Object.prototype.hasOwnProperty.call(n,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${r}". Use ${Qi(`${t}.fill`)} instead`)},bu=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>jt(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;let n={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(n[o]=jt(i,t,Vt(r,o)));return e.colorId!==void 0&&(mt(e.colorId,r,"colorId"),n.fill=qn(t,e.colorId)),n},jt=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>jt(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${r}". Use ${Qi("fill")} instead`);$n(e,"hover",r),$n(e,"click",r),$n(e,"rightClick",r)}let n={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){n[o]=bu(i,t,Vt(r,o));continue}n[o]=jt(i,t,Vt(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(mt(e.colorId,r,"colorId"),n.fill=qn(t,e.colorId)),n},kn=(e={},t)=>{let r=fu(e)?.[t];return r||null},Zi=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",Vi=(e,t,r,n)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,n))throw new Error(`Inline ${t}.${n} is not allowed in sprite layout elements at "${r}". Use ${Zi(`${t}.${n}`)} instead`)},ji=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},Vn=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Vn(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${r}". Use ${Zi(o)} instead`);Vi(e,"hover",r,"src"),Vi(e,"click",r,"src")}let n={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(n[o]=Vn(i,t,Vt(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){mt(e.imageId,r,"imageId");let o=kn(t,e.imageId),i=o?.fileId??e.imageId;n.src=i,n.width===void 0&&o?.width!==void 0&&(n.width=o.width),n.height===void 0&&o?.height!==void 0&&(n.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(mt(e.hoverImageId,r,"hoverImageId"),ji(n,"hover",kn(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(mt(e.clickImageId,r,"clickImageId"),ji(n,"click",kn(t,e.clickImageId)?.fileId??e.clickImageId)),n},Yn=(e,t={},r="root")=>Vn(jt(Dn(e,t,r),t,r),t,r),Te=Yn,it=(e=[])=>e.find(t=>t.id==="story"),Iu="#000000",jn="bg-cg-background-color",Au=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?Ar(r?.backgroundColor??Iu,"screen.backgroundColor"):qn(e,t.colorId),es=(e={})=>{if(nt(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},wu=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Mi=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=es(e),n=wu(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},Eu=(e={})=>{if(nt(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},xu=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},ts=(e={})=>{let t=Eu(e),r=xu(e),n={};return t!==void 0&&(n.alpha=t),r&&(n.blur=r),n},Pt=(e={})=>ts(e),Fe=(e={},t={})=>{let r={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},n=t.originX??e.originX,o=t.originY??e.originY;return n!==void 0&&(r.originX=n),o!==void 0&&(r.originY=o),r},vu=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],Hn=(e={})=>e.text&&nt(e.text,"content")&&nt(e.text,"textStyleId"),Fi=(e={})=>{if(e.resourceId)return e.resourceId;if(Hn(e))return"text"},Cu=e=>{if(e.text){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!Hn(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let t of vu)if(nt(e.text,t))throw new Error(`Visual item "${e.id}" text.${t} is reserved for the visual item`)}},Su=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:jn,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:Au({resources:e,background:t,screen:r})};if(n){let i=es(t);i!==void 0&&(o.alpha=i)}return o},_u=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.spritesheets?.[t]||e.layouts?.[t]):!1,Ui=({resources:e={},resourceId:t,colorId:r})=>{let n=Ki(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:gr({resourceId:t,kind:n})}:r!==void 0?{resourceId:jn,targetId:jn}:{resourceId:void 0,targetId:void 0}},rs=100,ot=rs,Ou="channel:bgm",Ru="channel:voice",$u="default",ku=e=>String(e).replaceAll("%","%25").replaceAll(":","%3A"),Dt=(...e)=>e.map(ku).join(":"),br=(e,t,r)=>{let n=new Set;e.forEach(({id:o})=>{if(n.has(o)){let i=r?` in ${r}`:"";throw new Error(`Duplicate ${t} id "${o}"${i}.`)}n.add(o)})},Lu=(e,t)=>e*t/rs,ns=(e={},t)=>e?.[t]??tt[t],Wn=(e={},t,r=ot)=>Lu(r,ns(e,t)),Kn=({id:e,volume:t,muted:r,pan:n,loop:o,interruption:i,children:s,runtime:l})=>{let a={id:e,type:"audio-channel",volume:t,muted:!!l?.muteAll||(r??!1),pan:n??0,children:s};return o!==void 0&&(a.loop=o),i!==void 0&&(a.interruption=i),a},mr=(e,t,r,n)=>e[r]!==void 0?e[r]:t[r]!==void 0?t[r]:n,Tu=["muted","pan","playbackRate","startAt","endAt"],Jn=({id:e,sound:t,resource:r,defaultLoop:n=!1})=>{let o={id:e,type:"sound",src:r.fileId,loop:mr(t,r,"loop",n),volume:mr(t,r,"volume",ot),startDelayMs:mr(t,r,"startDelayMs",0)};Tu.forEach(s=>{let l=mr(t,r,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},_e=({variables:e,imageGallery:t,runtime:r,saveSlots:n=[],dialogueState:o,includeInactiveAdvDialogue:i=!1,isLineCompleted:s,autoMode:l,skipMode:a,isChoiceVisible:c,isFormVisible:u,canRollback:d,confirmDialog:f,form:p,historyDialogue:h=[],characters:g={},dialogueUIHidden:I,skipOnlyViewedLines:b,skipTransitionsAndAnimations:w}={})=>{let S={dialogueTextSpeed:r?.dialogueTextSpeed??50,autoForwardDelay:r?.autoForwardDelay??1e3,autoForwardSpeed:r?.autoForwardSpeed??1,skipUnseenText:r?.skipUnseenText??!1,skipTransitionsAndAnimations:r?.skipTransitionsAndAnimations??!1,soundVolume:r?.soundVolume??50,musicVolume:r?.musicVolume??50,muteAll:r?.muteAll??!1,saveLoadPagination:r?.saveLoadPagination??1,menuPage:r?.menuPage??"",menuEntryPoint:r?.menuEntryPoint??"",autoMode:r?.autoMode??l??!1,skipMode:r?.skipMode??a??!1,dialogueUIHidden:r?.dialogueUIHidden??I??!1,isLineCompleted:r?.isLineCompleted??s??!1},O=ju({dialogueState:o,includeInactiveAdvDialogue:i,characters:g,variables:e,runtime:S}),$={variables:e,imageGallery:t,runtime:S,saveSlots:n,isChoiceVisible:c,isFormVisible:u,canRollback:d,confirmDialog:f,form:p,historyDialogue:h,characters:g};return O&&($.dialogue=O,$.dialogueLines=O.lines),$},Bi=100,Ir=(e,t)=>{if(Array.isArray(e))return e.map(n=>Ir(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=Ir(r[n],t)}),r.type==="text-revealing"?t(r):r},Nu=e=>Ir(e,t=>({...t,revealEffect:"none"})),Pu=e=>Ir(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,Bi):Bi;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),Ue=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?Nu(e):r?Pu(e):e,os=({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:{}}}}),Mn=e=>{if(Array.isArray(e))return e.map(Mn);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Mn(s);let r=t.click?.payload;if(!r||typeof r!="object"||Array.isArray(r))return t;let n=r.actions,o=n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"nextLine")?{...n.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...r,bypassChoice:!0,...o?{actions:{...n,nextLine:o}}:{}}}}},Du=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),Gi="submit",Ln=(e,t,r={})=>{let n=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},o=n.actions&&typeof n.actions=="object"?n.actions:{},i=r.replaceActions===!0?t:{...o,...t};return{...e||{},payload:{...n,actions:i}}},Fn=(e,t,r={})=>{if(Array.isArray(e))return e.map(c=>Fn(c,t,r));if(!e||typeof e!="object")return e;let n=typeof e.type=="string",o=n&&e.formRole===Gi,i=n&&r.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},l={};for(let[c,u]of Object.entries(e))l[c]=Fn(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:Ln(a.change,u),submit:Ln(a.submit,t.submitActions)}}}return a.formRole===Gi||i?{...a,click:Ln(a.click,t.submitActions,{replaceActions:!0})}:a},Un=(e,t)=>{if(Array.isArray(e))return e.map(n=>Un(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Un(o,t);for(let n of Du){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form"}})}return r},Bn=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0,s=lr({characterId:e,character:t,characterName:r,characters:n,variables:o});return{...i||{},...t||{},name:s}},is=(e=[],t={},r={})=>e.map(n=>{let o=Bn({characterId:n.characterId,character:n.character,characterName:n.characterName,characters:t,variables:r}),i=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(s=>s?.text??"").join(""):"";return{...n,text:i,character:o,characterName:o.name}}),Vu=e=>!(!e||e.mode==="adv"&&e.content===void 0),ju=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n,runtime:o}={})=>{if(!t&&!Vu(e))return;let i=e.content===void 0?[{text:""}]:Pn(e.content,"dialogue.content"),s=e.content===void 0?0:au({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),l=o?.dialogueTextSpeed??tt.dialogueTextSpeed,a=e.textSpeed??l,c=(e.lines||[]).map((d,f)=>{let p=Pn(d.content,`dialogue.lines[${f}].content`),h=Bn({characterId:d.characterId,character:d.character,characterName:d.characterName,characters:r,variables:n});return{...d,textSpeed:d.textSpeed??l,content:p.map(g=>({...g,text:ft(g.text,{variables:n})})),character:h,characterName:h.name}}),u=Bn({characterId:e.characterId,character:e.character,characters:r,variables:n});return{characterId:e.characterId,persistCharacter:e.persistCharacter,persistSprite:e.persistSprite,character:u,textSpeed:a,content:i.map(d=>({...d,text:ft(d.text,{variables:n})})),initialRevealedCharacters:s,lines:c}},ss=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=Le(e,r);return Te(Ue(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},Tn=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),zi=({renderStateKeyboard:e,keyboard:t,phase:r})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([n,o])=>{let i=e[n]??{},s=r==="keydown"?o?.keydown:o?.keyup;if(r==="keydown"&&s&&typeof s=="object"){e[n]={...i,keydown:{payload:Tn(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:Tn(o.keyup)});return}e[n]={...i,[r]:{payload:Tn(o)}}})},Mu=(e={},t={})=>{let r={};return zi({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),zi({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},Ne=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l})=>{if(!e)return[];let a=[],c=({instanceId:b,targetId:w})=>{let S=iu({resources:t,animationId:p,playback:h,instanceId:b,targetId:w,animationPath:s});S&&a.push(S)},u=r!=null&&r!==!1,d=n!=null&&n!==!1,f=o&&i&&o===i;ou(e,s);let p=Zl(e),h=eu(e),g=t?.animations?.[p],I=Ql(g,{animationId:p,animationPath:s});if(I==="update")return d&&i?c({instanceId:`${l}-animation-update`,targetId:i}):u&&o&&c({instanceId:`${l}-animation-update`,targetId:o}),a;if(I==="transition"){let b=`${l}-animation-transition`,w=h?.continuity==="persistent"?b:`${l}-animation-in`;if(u&&d&&f)return c({instanceId:b,targetId:i}),a;u&&c({instanceId:`${l}-animation-out`,targetId:o}),d&&c({instanceId:w,targetId:i})}return a},Fu=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Uu=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:a,imageGallery:c,runtime:u,activePersistentAnimations:d,restoredPersistentAnimations:f,autoMode:p,skipMode:h,isChoiceVisible:g,isFormVisible:I,canRollback:b,form:w,saveSlots:S=[]})=>{let{elements:O,animations:$}=e;if(t.background){let G=n===void 0?!0:nt(n?.background??{},"animations"),T=O.find(le=>le.id==="story");if(!T)return e;let x=cu(o,t.background),q=x||uu(t.background),Y=r?.background?.resourceId,W=r?.background?.colorId,B=t.background.resourceId??(t.background.animations?Y:void 0),te=t.background.colorId??(t.background.animations?W:void 0),re=_u(o,B),de={...t.background,colorId:te};if((te!==void 0||re)&&T.children.push(Su({resources:o,background:de,screen:i,includeOpacity:!re})),B){let{images:le={},videos:ie={},spritesheets:Z={}}=o,X=Ki(o,B),v;if(X==="sprite"?v=le[B]:X==="video"?v=ie[B]:X==="spritesheet-animation"&&(v=Z[B]),v){let R=X==="video",M=X==="spritesheet-animation",fe={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...x},me={...Mi(t.background,{includeDefaultAlpha:!0}),...Fe(fe,t.background)},F;M?F=Ji({id:gr({resourceId:B,kind:X}),resourceId:B,spritesheet:v,animationName:t.background.animationName,animationSpeed:t.background.animationSpeed,loop:t.background.loop,transform:me}):F={id:gr({resourceId:B,kind:X}),type:R?"video":"sprite",src:v.fileId,width:v.width,height:v.height,...me},R&&(F.loop=t.background.loop??!1,F.volume=v.volume??50),F&&T.children.push(F)}}if(B){let{layouts:le={}}=o,ie=le[B];if(ie){let Z={id:gr({resourceId:B,kind:"container"}),type:"container",children:ie.elements,...Mi(t.background)};q&&Object.assign(Z,Fe({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...x},t.background));let X=Le(Z,_e({variables:a,imageGallery:c,runtime:u,saveSlots:S,dialogueState:t.dialogue,isLineCompleted:s,autoMode:p,skipMode:h,isChoiceVisible:g,isFormVisible:I,canRollback:b,form:w,characters:o.characters||{},skipTransitionsAndAnimations:l}));T.children.push(Te(Ue(X,{isLineCompleted:s,skipMode:h,skipTransitionsAndAnimations:l}),o))}}let Oe=Ui({resources:o,resourceId:Y,colorId:W}),ne=Ui({resources:o,resourceId:B,colorId:te}),oe=Ne({animationsDef:t.background.animations,resources:o,previousResourceId:Oe.resourceId,currentResourceId:ne.resourceId,previousTargetId:Oe.targetId,currentTargetId:ne.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});Se({animationInstances:oe,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:d,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:G})&&$.push(...oe)}return e},Bu=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:a}=e;if(t.character&&n){let c=l.find(h=>h.id==="story");if(!c)return e;let u=t.character.items||[],d=r?.character?.items||[],f=Pi(u),p=Pi(d);for(let h=0;h<u.length;h++){let g=u[h],{transformId:I,sprites:b}=g,w=d.find(W=>W.id===g.id),S=d.findIndex(W=>W.id===g.id),O=w?.sprites&&w.sprites.length>0,$=b&&b.length>0,G=S>=0?pr(w,S,p):void 0,T=Ne({animationsDef:g.animations,resources:n,previousResourceId:G,currentResourceId:$?pr(g,h,f):void 0,previousTargetId:G,currentTargetId:$?pr(g,h,f):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!I&&O&&Se({animationInstances:T,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...T);continue}if(g.animations&&!b&&!I)continue;if(!b||b.length===0||!I){console.warn("Character item missing sprites or transformId:",g);continue}let x=pr(g,h,f),q=n.transforms[I];if(!q){console.warn("Transform not found:",I);continue}let Y={type:"container",id:x,...Fe(q,g),...Pt(g),children:[]};for(let W of b){let B=Xi({id:`${x}-${W.id}`,item:W,resources:n});B&&Y.children.push(B)}c.children.push(Y),Se({animationInstances:T,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...T)}}return e},as=(e,t)=>{if(!Sn.includes(e))throw new Error(`${t} must be one of: ${Sn.join(", ")}.`)},Gu=(e,t)=>{let r=!!e.resourceId||Hn(e),n=e.layer??(r?void 0:t?.layer)??Cn;return as(n,`Visual item "${e.id}" layer`),n},zu=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,imageGallery:l,runtime:a,activePersistentAnimations:c,autoMode:u,skipMode:d,isChoiceVisible:f,isFormVisible:p,canRollback:h,form:g,saveSlots:I=[],visualLayer:b})=>{let{elements:w,animations:S}=e;if(t.visual&&n){let O=w.find(x=>x.id==="story");if(!O)return e;let $=t.visual.items,G=r?.visual?.items||[],T=_e({variables:s,imageGallery:l,runtime:a,saveSlots:I,dialogueState:t.dialogue,isLineCompleted:o,autoMode:u,skipMode:d,isChoiceVisible:f,isFormVisible:p,canRollback:h,form:g,characters:n.characters||{},skipTransitionsAndAnimations:i});b!==void 0&&as(b,"visualLayer");for(let x of $){let q=G.find(re=>re.id===x.id),Y=Gu(x,q);if(b!==void 0&&Y!==b)continue;if(Cu(x),x.text){let re=hr(n,x),de={...structuredClone(x.text),id:`visual-${x.id}`,type:"text",...Fe(re,x)};Object.assign(de,Pt(x)),O.children.push(Te(Le(de,T),n))}if(x.resourceId){let{images:re={},videos:de={},spritesheets:Oe={}}=n,ne=Oe[x.resourceId];if(ne){let oe=hr(n,x),le=x.animationName;if(le){let ie=ne.animations?.[le];if(!ie)throw new Error(`Animation '${le}' not found in spritesheet resource '${x.resourceId}'`);let Z=Pt(x),X={id:`visual-${x.id}`,type:"spritesheet-animation",...Fe(oe,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:ie.frames,animationSpeed:x.animationSpeed??ie.animationSpeed??.5,loop:x.loop??ie.loop??!0}};Z.blur&&(X.blur=Z.blur),O.children.push(structuredClone(X))}}else{let oe=re[x.resourceId]||de[x.resourceId];if(oe){let le=de[x.resourceId]!==void 0,ie=hr(n,x),Z={id:`visual-${x.id}`,type:le?"video":"sprite",src:oe.fileId,width:oe.width,height:oe.height,...Fe(ie,x)};Object.assign(Z,Pt(x)),le&&(Z.loop=oe.loop??!1,Z.volume=oe.volume??50),O.children.push(Z)}}}if(x.resourceId){let{layouts:re={}}=n,de=re[x.resourceId];if(de){let Oe=hr(n,x),ne={id:`visual-${x.id}`,type:"container",children:structuredClone(de.elements),...Fe(Oe,x)};Object.assign(ne,Pt(x));let oe=Le(ne,T);O.children.push(Te(Ue(oe,{isLineCompleted:o,skipMode:d,skipTransitionsAndAnimations:i}),n))}}let W=Fi(q),B=Fi(x),te=Ne({animationsDef:x.animations,resources:n,previousResourceId:W,currentResourceId:B,previousTargetId:W?`visual-${x.id}`:void 0,currentTargetId:B?`visual-${x.id}`:void 0,animationPath:`visual.items[${x.id}].animations`,idPrefix:x.id});Se({animationInstances:te,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:c})&&S.push(...te)}}return e},ht="dialogue-character-sprite",qu=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=it(e.elements);if(!a)return e;let c=t.dialogue?.character?.sprite,u=r?.dialogue?.character?.sprite,d=_t(c),f=_t(u),p=Ne({animationsDef:c?.animations,resources:n,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=n.transforms?.[c.transformId];if(!h)return console.warn("Transform not found:",c.transformId),e;let g={type:"container",id:ht,...Fe(h),children:[]};for(let I of c.items){let b=Xi({id:`${ht}-${I.id}`,item:I,resources:n});b&&g.children.push(b)}return a.children.push(g),Se({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e},Yu=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,skipOnlyViewedLines:d,isLineCompleted:f,skipTransitionsAndAnimations:p,variables:h,imageGallery:g,runtime:I,activePersistentAnimations:b,saveSlots:w=[]})=>{let{elements:S,animations:O}=e;if(!t.dialogue||o)return e;let $=S.find(T=>T.id==="story");if(!$)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:T={}}=n,x=T[t.dialogue.ui.resourceId];if(x){let q={elements:x.elements},Y=_e({variables:h,imageGallery:g,runtime:I,saveSlots:w,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:f,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:d,skipTransitionsAndAnimations:p}),W=Le(q,Y),B=Te(Ue(W?.elements,{isLineCompleted:f,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(B))for(let te of B)$.children.push(te);else B&&$.children.push(B)}}qu(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:b});let G=Ne({animationsDef:t.dialogue.ui?.animations,resources:n,previousResourceId:r?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:r?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return Se({animationInstances:G,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:b})&&O.push(...G),e},Hu=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,imageGallery:a,runtime:c,autoMode:u,skipMode:d,isChoiceVisible:f,isFormVisible:p,canRollback:h,form:g,activePersistentAnimations:I,saveSlots:b=[]})=>{let{elements:w,animations:S}=e;if(t.choice&&n){let O=it(w);if(!O)return e;let $=n?.layouts[t.choice.resourceId];if($&&$.elements){let T={elements:$.elements},x=Le(T,{..._e({variables:l,imageGallery:a,runtime:c,saveSlots:b,dialogueState:t.dialogue,isLineCompleted:i,autoMode:u,skipMode:d,isChoiceVisible:f??!!t.choice,isFormVisible:p,canRollback:h,form:g,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}}),q=Mn(Te(Ue(x?.elements,{isLineCompleted:i,skipMode:d,skipTransitionsAndAnimations:s}),n));if(Array.isArray(q))for(let Y of q)O.children.push(Y);else q&&O.children.push(q)}let G=Ne({animationsDef:t.choice.animations,resources:n,previousResourceId:r?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:r?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});Se({animationInstances:G,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:I})&&S.push(...G)}return e},Wu=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,imageGallery:a,runtime:c,autoMode:u,skipMode:d,isChoiceVisible:f,isFormVisible:p,canRollback:h,activePersistentAnimations:g,saveSlots:I=[],form:b})=>{let{elements:w,animations:S}=e;if(!b?.resourceId||!n)return e;let O=it(w);if(!O)return e;let $=n?.layouts?.[b.resourceId];if(!$)return console.warn(`Form layout not found: ${b.resourceId}`),e;let G={id:"form-container",type:"container",x:0,y:0,children:$.elements||[]},T={..._e({variables:l,imageGallery:a,runtime:c,saveSlots:I,dialogueState:t.dialogue,isLineCompleted:i,autoMode:u,skipMode:d,isChoiceVisible:f,isFormVisible:p,canRollback:h,characters:n.characters||{},skipTransitionsAndAnimations:s,form:b}),form:b},x=Le(G,T),q=Un(Te(Ue(Fn(x,b),{isLineCompleted:i,skipMode:d,skipTransitionsAndAnimations:s}),n),b);q&&O.children.push(q);let Y=Ne({animationsDef:b.animations,resources:n,previousResourceId:r?.form?.resourceId,currentResourceId:b.resourceId,previousTargetId:r?.form?.resourceId?"form-container":void 0,currentTargetId:b.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return Se({animationInstances:Y,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&S.push(...Y),e},Ku=(e,{presentationState:t,resources:r={},variables:n,imageGallery:o,runtime:i,isLineCompleted:s,autoMode:l,skipMode:a,isChoiceVisible:c,isFormVisible:u,canRollback:d,form:f,saveSlots:p=[],skipTransitionsAndAnimations:h})=>{if(!t.control?.resourceId)return e;let g=r.controls?.[t.control.resourceId];if(!g)return e;let I=Mu(g.keyboard,g.keyup);if(I&&Object.keys(I).length>0&&(e.global.keyboard=I),!Array.isArray(g.elements)||g.elements.length===0)return e;let b=it(e.elements);if(!b)return e;let w={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:g.elements};return b.children.push(ss({container:w,resources:r,templateData:_e({variables:n,imageGallery:o,runtime:i,saveSlots:p,dialogueState:t.dialogue,isLineCompleted:s,autoMode:l,skipMode:a,isChoiceVisible:c,isFormVisible:u,canRollback:d,form:f,characters:r.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:s,skipMode:a,skipTransitionsAndAnimations:h})),e},Ju=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!it(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||br(u,"BGM sound"),d){let h=u.find(g=>g.loop===!0);if(h)throw new Error(`BGM sound "${h.id}" cannot loop inside a looping BGM channel.`)}if(u.forEach(h=>{let g=r.sounds?.[h.resourceId];if(!g)return;let I=d?{...h,loop:h.loop??!1}:h;f.push(Jn({id:Dt("bgm",c?"default":h.id),sound:I,resource:g,defaultLoop:!d}))}),f.length===0)return e;let p=_e({variables:o,runtime:n}).runtime;s.push(Kn({id:Ou,volume:Wn(p,"musicVolume",c?ot:a.volume??ot),muted:a.muted,pan:a.pan,loop:c?void 0:a.loop,interruption:a.interruption,children:f,runtime:p}))}return e},Xu=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx,s=!Array.isArray(i.channels),l=s?[{id:$u,sounds:i.items??[]}]:i.channels;s||br(l,"SFX channel"),l.forEach(a=>{let c=!s&&a.loop===!0,u=[];if(s||br(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=r.sounds?.[d.resourceId];if(!p)return;let h=c?{...d,loop:d.loop??!1}:d;u.push(Jn({id:s?Dt("sfx","default",f,d.id):Dt("sfx",a.id,d.id),sound:h,resource:p,defaultLoop:c?!1:void 0}))}),u.length!==0&&o.push(Kn({id:Dt("channel","sfx",a.id),volume:Wn(n,"soundVolume",a.volume??ot),muted:a.muted,pan:a.pan,loop:s?void 0:a.loop,interruption:s?void 0:a.interruption,children:u,runtime:n}))})}return e},Qu=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},Zu=(e,{presentationState:t,resources:r,currentSceneId:n,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:ot,startDelayMs:l.startDelayMs??0}]:[]:l.sounds,u=!a&&l.loop===!0,d=[];if(a||br(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=Qu(r,n,p.resourceId);if(!h)return;let g=u?{...p,loop:p.loop??!1}:p;d.push(Jn({id:Dt("voice",n,a?"default":p.id),sound:g,resource:h,defaultLoop:u?!1:void 0}))}),d.length===0)return e;let f=_e({variables:i,runtime:o}).runtime;return s.push(Kn({id:Ru,volume:a?l.volume??ns(f,"soundVolume"):Wn(f,"soundVolume",l.volume??ot),muted:l.muted,pan:l.pan,loop:a?void 0:l.loop,interruption:l.interruption,children:d,runtime:f})),e},ed=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,imageGallery:i,runtime:s,autoMode:l,skipMode:a,isChoiceVisible:c,isFormVisible:u,canRollback:d,form:f,saveSlots:p=[],isLineCompleted:h,skipTransitionsAndAnimations:g,activePersistentAnimations:I})=>{let{elements:b,animations:w}=e;if(t.layout){let G=it(b);if(!G)return e;let T=n.layouts[t.layout.resourceId];if(!T)return e;Array.isArray(T.transitions)&&!h&&!g&&zn({animations:w,transitions:T.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:T.elements||[]};G.children.push(ss({container:x,resources:n,templateData:_e({variables:o,imageGallery:i,runtime:s,saveSlots:p,dialogueState:t.dialogue,isLineCompleted:h,autoMode:l,skipMode:a,isChoiceVisible:c,isFormVisible:u,canRollback:d,form:f,characters:n.characters||{},skipTransitionsAndAnimations:g}),isLineCompleted:h,skipMode:a,skipTransitionsAndAnimations:g}))}let S=r?.layout?.resourceId,O=t.layout?.resourceId,$=Ne({animationsDef:t.layout?.animations,resources:n,previousResourceId:S,currentResourceId:O,previousTargetId:S?`layout-${S}`:void 0,currentTargetId:O?`layout-${O}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return Se({animationInstances:$,isLineCompleted:h,skipTransitionsAndAnimations:g,activePersistentAnimations:I})&&w.push(...$),e},td=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=t?.screen?.animations;if(!a)return e;let c=r!=null,u=Ne({animationsDef:a,resources:n,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},rd=(e,{presentationState:t})=>{let r=it(e.elements);return!r||!t?.screen||Object.assign(r,ts(t.screen)),e},nd=(e,{presentationState:t,resources:r={},variables:n,imageGallery:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,overlayStack:f=[],dialogueHistory:p=[],saveSlots:h=[],screen:g,isLineCompleted:I,skipTransitionsAndAnimations:b})=>{let{elements:w,animations:S}=e;return f&&f.length>0&&f.forEach((O,$)=>{let G=r.layouts[O.resourceId];if(!G){console.warn(`Overlay layout not found: ${O.resourceId}`);return}Array.isArray(G.transitions)&&(b||zn({animations:S,transitions:G.transitions,defaultTargetId:`overlayStack-${$}`,idPrefix:`overlayStack-${$}`,animationPathPrefix:`overlayStack[${$}]`}));let T={id:`overlayStack-${$}`,type:"container",x:0,y:0,children:[os({id:`overlayStack-${$}-blocker`,screen:g}),...G.elements||[]]},x=is(p,r.characters,n),q=_e({variables:n,imageGallery:o,runtime:i,saveSlots:h,dialogueState:t?.dialogue,isLineCompleted:I,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,historyDialogue:x,characters:r.characters||{},skipTransitionsAndAnimations:b}),Y=Le(T,q),[W,...B]=Y.children||[],te=Te(Ue({...Y,children:B},{isLineCompleted:I,skipMode:l,skipTransitionsAndAnimations:b}),r);w.push({...te,children:W?[W,...te.children||[]]:te.children})}),e},od=(e,{presentationState:t,resources:r={},variables:n,imageGallery:o,runtime:i,saveSlots:s=[],autoMode:l,skipMode:a,isChoiceVisible:c,isFormVisible:u,canRollback:d,form:f,confirmDialog:p,dialogueHistory:h=[],screen:g,isLineCompleted:I,skipTransitionsAndAnimations:b})=>{let{elements:w,animations:S}=e;if(!p?.resourceId)return e;let O=r.layouts?.[p.resourceId];if(!O)return console.warn(`ConfirmDialog layout not found: ${p.resourceId}`),e;Array.isArray(O.transitions)&&!b&&zn({animations:S,transitions:O.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let $={id:"confirmDialog",type:"container",x:0,y:0,children:[os({id:"confirmDialog-blocker",screen:g}),...O.elements||[]]},G=is(h,r.characters,n),T=Le($,_e({variables:n,imageGallery:o,runtime:i,saveSlots:s,dialogueState:t?.dialogue,isLineCompleted:I,autoMode:l,skipMode:a,isChoiceVisible:c,isFormVisible:u,canRollback:d,form:f,confirmDialog:p,historyDialogue:G,characters:r.characters||{},skipTransitionsAndAnimations:b})),[x,...q]=T.children||[],Y=Te(Ue({...T,children:q},{isLineCompleted:I,skipMode:a,skipTransitionsAndAnimations:b}),r);return w.push({...Y,children:x?[x,...Y.children||[]]:Y.children}),e},Mt=e=>(t,r)=>zu(t,{...r,visualLayer:e}),id=Mt(ke.BEHIND_BACKGROUND),sd=Mt(ke.BEHIND_CHARACTER),ad=Mt(ke.BEHIND_DIALOGUE),cd=Mt(ke.BEHIND_CHOICE),ld=Mt(ke.FOREGROUND),cs=e=>cr(Fu,[Ku,id,Uu,sd,Bu,ad,Yu,cd,Hu,Wu,ed,ld,rd,td,Ju,Xu,Zu,nd,od])(e);function ls(e,t=""){let r=[],n=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<n;){let a=s+1+l();s=a+l(),r.push([a,s,t?parseInt(t[i++],36):0])}return r}function us(e,t,r){let n=0,o=t.length-1;for(;n<=o;){let i=n+o>>>1,s=r[i];if(e<t[i])o=i-1;else if(e>s>>>5)n=i+1;else return s&31}return 0}var ds="090001000h1v5g2903000hl2v6jh16ng1s210111110o35aa10u2k1g10l6600152113h2010u1q1r5aq3890o13181214r22k3158q2n1000v100h1k20000001207030001160721k171001h1j11610332010010321210090411021c1c02100o301201412230u1130b100h1j116111420120411001100k11l10051001h1j11611142011000321210072411021d0g10r3000000132120090o200200g1j11f2012031213711271t1001o301001000001121371b1f0c101h1l2011001031212000080a1t1001m40400102101600i11t301006c7i601008b6p41r10101041h3d0004115a1j290p3q223000511010100g1501010302003172030c0010016000e0i6v50n40n5tl12ir33s12t11u11cj30100060700010a90t220000l71i20m7203010241000502rd101004k300000006101027050920g3t22bk1300616g209030207u18c1000t10003010501b2o20000102000004g37070101o921c000640602001mcv3rg20000001o16d0c0m1fg6g2h30m10q55f1vm11c0ma0p1a42nc0ne1a090q3314902021204020112030318250105bb1201110i1021i15101131502141b15120511011k1155132040202510201010603060a1f02040104210b1g3290e0e0kn11vs12j11j3040pp12t80g6v1vmo7319g21g51gh103040n11010040j51i3f01q1h1d0m27p1a0000cs13200523j200010301010100v140018a4q2501010101c08000i1f12601011g3012215110u1a0001015000pcq181000100011000iji5fvc0u91g5bhg20ie0l94lo6002115303121s12240la1tj23h44tj11t45m4ah33q700000l3ep2021a200t220301012040a0i320j2040007f00100r20c100g3208000011531000s520201036020t900207l1101n311000000321210090a12634b910201l22001051020120011020000e1i520701020000n10h5001050000010000010001re0010323010001r11i520701000001q6000000107l600000230004gg12080001lc62027111n1000411230000000000t820321030030r10090n205001380800501020n2050c0001mc00002000000nc006150000i5l1100600010001q753011160000i441111000000rl11019100000c1h201043102n10ltk1f006eoss2b0202gs94r36si2033ku101m373h50b1rqs4113sli1t22m1uh2435070726u13k92rr7m34h380e0m141egl561g1261114k60ga6nn10t33sv13uf1jf0207150qt16t66pr60n23k6bf1f0e1l29g71c1e029j1n30p11ea0k1028139m16rb2v621122i52213040tf1u3b51n17127c0232041d120819052c28220104060306l5g3l4572g130152cqdl2c3o37a5o27u11c32d9m2cu2191obo57eh9gg1tv3",fs="262122424333333393233393339333333333393393bf3b3b3b3b3f3f3bffff33b3bb33ff3f33b3b3333333bffff3b33bb33f33bffff33b3bb33ff3f33b3bbb333b3ff33b333f33b3b3b3b3333b3bf33b3bb39333b33b33b3b3b333b333333b3b33333f3b33b3ffb3f3fff3f3b33f35dc33333f3b3b3b33323333b3bb3b33b3fb3b3333b33333bff3b3f33bfb3b3ff3b3b3b3b3b333b333b3323e22442344444444444444444444444444444444444444444444444444444444444444444444444444444443333333333b3b3bb33333b353bff3b3b3b3f3ff3b3b333bfff3f33333fb3bb3fb3b3bb33232333f333fff333333333b3b3333bb3b39393f3b3fbf33bb3b393b3b3b3333b33b33b3bbb33b33ffff3b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b3fffff3bb39b9b3b33b3bf3f3b33f3b3f93b33b3b3bb33b33b3b3b3333393b3b3b33b39bffb3b332333b333dd3b3333233332333333333333333333333333333444444444444a4444444444444344444444444444444444444444444444444444444444",ps="0001000000010010000000100000000000000000000000000001000000010014000100000001001000010101100101100000000000000000000100000001111000010000000110101001110111111111000100000021001000010000000100100001000000011010000100000001111000013000000100140001000000010010";var hs=65535,Xn=40960,wr=126976,ys=new Uint8Array(12288),bs=new Uint8Array(3072),Is=new Uint8Array(2816),As,ws;{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),r=new Uint32Array(320),n=0;for(let[o,i,s]of ls(ds,fs))e(ys,0,o,i,s),e(bs,Xn,o,i,s),e(Is,wr,o,i,s),i>=65040&&!(o>=wr&&i<=129791)&&(t[n]=o,r[n++]=i<<5|s);As=t.slice(0,n),ws=r.slice(0,n)}function ms(e){return e<12288?ys[e]:e<Xn?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?bs[e-Xn]: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>=wr&&e<129792?Is[e-wr]:e>=917504?e>921599?0:e>=917536&&e<917632||e>=917760&&e<918e3?3:2:us(e,As,ws)}var Es=Uint8Array.from(ps,Number);function ud(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 gs(e,t,r){switch(t){case 3:return e&24?r===8204?e&6:(e&24)===16||ud(r)?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*xs(e){let t=e.length;if(t===0)return;let r=e.codePointAt(0),n=r>hs?2:1,o=ms(r),i=50200>>o&1?gs(0,o,r):0,s=0,l=r,a=o;for(;n<t;){r=e.codePointAt(n);let c=r>hs?2:1,u=ms(r),d=Es[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)?gs(i,u,r):0,f&&(yield{segment:e.slice(s,n),index:s,input:e,_hd:l,_catBegin:a===15?0:a,_catEnd:o===15?0:o},s=n,l=r,a=u),n+=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*vs(e){for(let t of xs(e))yield t.segment}{let e=xs("_");Es._keep=[e,e.next()]}var Cs=1e3,dd=1,fd=60,pd=3,hd=.5,md=2e4,gd=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,yd=/^\s+$/u,Ss,bd=e=>{let t=`${e??""}`.normalize("NFC"),r=globalThis.Intl?.Segmenter;return typeof r!="function"?Array.from(vs(t)):(Ss??=new r(void 0,{granularity:"grapheme"}),Array.from(Ss.segment(t),({segment:n})=>n))},Id=e=>bd(e).reduce((t,r)=>yd.test(r)?t+hd:gd.test(r)?t+pd:t+1,0),_s=({text:e="",baseDelay:t=Cs,speed:r=dd}={})=>{let n=Number.isFinite(t)?Math.max(0,t):Cs,o=Number.isFinite(r)&&r>0?r:1,i=Id(e)*fd/o,s=Math.max(n,md);return Math.min(n+i,s)};var Er={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Ts=1,Zn=1,yt="choice",Be="form",Cr=()=>({manual:{...Er.manual},auto:{...Er.auto},applyMode:Er.applyMode}),eo=()=>({groupId:null,variantId:null,pageIndex:0}),to=new Set,Ad=new Set(["groupId","variantId"]),wd=new Set(["pageIndex"]),ro=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...Cr()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},D=e=>{let t=se(e)?Je(e):e;return structuredClone(t)},P=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ns=(e,t)=>{if(typeof t!="string"||t.length===0)throw new Error("Achievement action requires a non-empty resourceId");let r=e.projectData.resources?.achievements?.[t];if(!r)throw new Error(`Achievement resource "${t}" not found`);if(r.type!=="boolean"&&r.type!=="number")throw new Error(`Achievement resource "${t}" has invalid type "${r.type}"`);return r},Bt=e=>String(e),Ps=()=>({sections:[],resources:[]}),Ed=e=>P(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Ps(),xd=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",vd=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:xd(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),Cd=()=>({resourceId:void 0}),Sd=e=>{if(!P(e))return e;let t={...e};return Object.prototype.hasOwnProperty.call(t,"requireComplete")&&!Object.prototype.hasOwnProperty.call(t,"requireLineCompleted")&&(t.requireLineCompleted=t.requireComplete),delete t.requireComplete,t},bt=(e,t)=>{let r=e?.story?.scenes??{};for(let[n,o]of Object.entries(r))if(o?.sections?.[t])return{sceneId:n,section:o.sections[t]};return{sceneId:void 0,section:void 0}},Ds=e=>{let t=e?.story?.scenes??{},r=new Map;for(let[n,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let l=r.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},Vs=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},js=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Ts)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},_d=(e,t={})=>{let r;try{r=js(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:Vs(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},Od=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,_d(t,r)])),Ms=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Up(r));return t.length>0?t:void 0},Rd=e=>{!P(e)||!Array.isArray(e.timeline)||(e.returnabilityVersion=Zn,e.timeline.forEach(t=>{if(!P(t))return;typeof t.returnable!="boolean"&&delete t.returnable;let r=Ms(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions}))},Os=(e,t,r,n="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!P(e))throw new Error(`Malformed ${n}.${t}[${r}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${n}.${t}[${r}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${n}.sections[${r}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},$d=(e,t="viewedRegistry")=>{if(e===void 0)return Ps();if(!P(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let r=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Os(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Os(o,"resources",i,t);return[s.resourceId,s]})))}},Fs=(e,t,r)=>{if(!P(e))throw new Error(`Malformed save slot ${r}.`);let{sectionId:n,lineId:o}=e;if(typeof n!="string"||n.length===0)throw new Error(`Malformed save slot ${r}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${r}: missing lineId.`);let{sceneId:i,section:s}=bt(t,n);if(!s)throw new Error(`Malformed save slot ${r}: section "${n}" does not exist in projectData.`);if(!s.lines?.some(a=>a.id===o))throw new Error(`Malformed save slot ${r}: line "${o}" does not exist in section "${n}".`);return{sceneId:i,sectionId:n,lineId:o}},Us=(e,t)=>e?.sectionId===t?.sectionId&&e?.lineId===t?.lineId,kd=(e,t)=>{let{section:r}=bt(e,t?.sectionId);return r?.lines?.find(n=>n.id===t?.lineId)},Ld=(e,t)=>{let{section:r}=bt(e,t?.sectionId),n=r?.lines?.findIndex(i=>i.id===t?.lineId);if(typeof n!="number"||n<0)return null;let o=r.lines[n+1];return o?{sectionId:t.sectionId,lineId:o.id}:null},Bs=(e,t,r)=>{if(typeof t?.sectionId!="string")return!1;let{section:n}=bt(e,t.sectionId);return Us({sectionId:t.sectionId,lineId:n?.lines?.[0]?.id},r)},Td=new Set(["jumpToLine","rollbackByOffset","rollbackToLine","sectionTransition","resetStoryAtSection"]),gt={always:"always",maybe:"maybe",never:"never"},Nd=e=>{if(!Object.prototype.hasOwnProperty.call(e??{},"when"))return gt.always;let t=e.when,r;if(t===null||typeof t=="boolean"||typeof t=="number")r=t;else if(P(t)&&Object.keys(t).length===1&&Object.prototype.hasOwnProperty.call(t,"literal"))r=t.literal;else return gt.maybe;return r?gt.always:gt.never},Gs=(e,t)=>{if(!Array.isArray(e?.branches))return!1;for(let r of e.branches){let n=Nd(r);if(n!==gt.never){if(t(r))return!0;if(n===gt.always)return!1}}return!1},zs=e=>Gs(e,t=>Object.entries(t?.actions??{}).some(([r,n])=>r==="conditional"?zs(n):Td.has(r))),qs=(e,t,r)=>Gs(t,n=>Object.entries(n?.actions??{}).some(([o,i])=>o==="sectionTransition"?Bs(e,i,r):o==="conditional"?qs(e,i,r):!1)),Pd=(e,t,r)=>{if(!t)return!0;let n=kd(r,e)?.actions;if(!P(n))return!0;if(Bs(r,n.sectionTransition,t))return!1;let o=n.conditional;return o?!(qs(r,o,t)||!(n.choice?.resourceId||n.form?.resourceId)&&!zs(o)&&Us(Ld(r,e),t)):!0},Dd=(e,t,r)=>{if(!P(e)||!Array.isArray(e.timeline))return Ut({pointer:t,replayStartIndex:1});let n=new WeakSet,o=e.timeline.flatMap((c,u)=>{if(!P(c))return[];try{let d=Fs(c,r,`rollback.timeline[${u}]`),f=vr({sectionId:d.sectionId,lineId:d.lineId,rollbackPolicy:c.rollbackPolicy,returnable:c.returnable});typeof c.returnable=="boolean"&&n.add(f);let p=Ms(D(c.executedActions));return p&&(f.executedActions=p),[f]}catch{return[]}});if(o.length===0)return Ut({pointer:t,replayStartIndex:1});e.returnabilityVersion!==Zn&&o.forEach((c,u)=>{!n.has(c)&&!Pd(c,o[u+1],r)&&(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(vr({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}},Vd=(e,t,r)=>{if(!P(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=io(t),o=Fs(e.pointers?.read,t,`contexts[${r}].pointers.read`);if(e.variables!==void 0&&!P(e.variables))throw new Error(`Malformed save slot contexts[${r}].variables entry.`);if(e.runtime!==void 0&&!P(e.runtime))throw new Error(`Malformed save slot contexts[${r}].runtime entry.`);let i=e.variables?dt(D(e.variables),t.resources?.variables??{}):{},s=Jd({loadedContextRuntime:P(e.runtime)?D(e.runtime):{}}),l={currentPointerMode:"read",pointers:{read:o},configuration:P(e.configuration)?D(e.configuration):{},views:Array.isArray(e.views)?D(e.views):[],bgm:P(e.bgm)?D(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:Dd(e.rollback,o,t)};return s&&(l.runtime=s),l},jd=(e,t)=>{if(!P(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((r,n)=>Vd(r,t,n))}},Md=(e,t)=>{if(!P(e))throw new Error("Malformed save slot.");let r=js(e.formatVersion);return{...e,formatVersion:r,state:jd(e.state,t)}},Rs=(e,t,{required:r=!1}={})=>{if(e===void 0){if(r)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let n=D(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},Fd=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Rs(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Rs(e.cancelActions,"cancelActions")}},It=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Ud=e=>(P(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),At=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},Ys=e=>{if(!(!P(e)||!e.animations))return{animations:D(e.animations)}},Bd=(e,t)=>{let r=Ys(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},Gd=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},zd=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},xr=e=>String(e??""),Hs=(e,t)=>{let r=xr(t);return e?.trim===!0?r.trim():r},qd=e=>P(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>P(t)).map(([t,r])=>[t,{id:t,...D(r)}])):{},Yd=(e,t)=>{if(!t||!P(e.global.formDrafts))return;let r=e.global.formDrafts[t];return P(r)?r:void 0},Ws=(e,t)=>{let r=Ud(e);P(r[t])||(r[t]={values:{},touched:{},errors:{},submitted:!1});let n=r[t];return P(n.values)||(n.values={}),P(n.touched)||(n.touched={}),P(n.errors)||(n.errors={}),typeof n.submitted!="boolean"&&(n.submitted=!1),n},no=(e,t)=>{let r=Hs(e,t);return e?.required===!0&&r.length===0?"required":null},Hd=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=ce({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:et(n.slice(0,o+1).map(i=>i.actions||{}))},Wd=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=Gd(t),o=zd(r,n);if(!n||!o)return null;let i=Yd(e,o),s=qd(t),l=_r({state:e}),a={},c=[],u={},d=!0;return Object.entries(s).forEach(([f,p])=>{let h=xr(l?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},f)?xr(i.values[f]):h,I=i?.touched?.[f]===!0,b=no(p,g),w=i?.submitted||I?b:null,S=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,O={id:f,variableId:p.variableId,value:g,initialValue:h,valid:!b,error:w,touched:I,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...S!==void 0?{maxLength:S}:{}};b&&(d=!1),a[f]=O,c.push(O),u[f]=g}),{id:n,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??{})}}}},st=[],$s="line",oo="interaction",vr=({sectionId:e,lineId:t,rollbackPolicy:r,returnable:n})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free",...typeof n=="boolean"?{returnable:n}:{}}),io=e=>{let{contextVariableDefaultValues:t}=ur(e??{});return D(t)},Ks=()=>({...D(Tt)}),Js=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:D(r),hasLoadedValues:!1};if(!P(e))throw new Error(`Malformed ${n}.`);let o=D(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Xs(s,D(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Kd=({loadedGlobalRuntime:e={}})=>Js({loadedRuntime:e,runtimeIds:xn,defaults:tt,path:"global.runtime"}).runtimeState,Jd=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=Js({loadedRuntime:e,runtimeIds:vn,defaults:Ks(),path:"context.runtime"});return r?t:void 0},Sr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Xd=e=>e.runtime?(vn.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=D(Tt[t]))}),e.runtime):(e.runtime=Ks(),e.runtime),Qd=e=>Ti(e.global),Zd=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Qd(e)}})},ef=e=>Li[e],tf=(e,t)=>{let r=ef(e);if(r==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(r==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(r==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},Xs=(e,t)=>{if(tf(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},Qs=(e,t,r)=>{let n=Xs(t,r);if(t in Tt){let o=Sr(e);if(!o)return n;let i=Xd(o);return i[t]=n,n}return e.global[t]=n,n},Zs=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:D(e)},configuration:{},views:[],bgm:Cd(),variables:io(t),rollback:Ut({pointer:e})}),wt=e=>e?(e.currentPointerMode="read",P(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,rf=(e,{queueRender:t=!0}={})=>{let r=e.contexts?.[e.contexts.length-1],n=r?.pointers?.read;if(!r||!n?.sectionId||!n?.lineId)return null;let o=Zs({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,nf(e,{queueRender:t}),o},nf=(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=Cr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},ea=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},Ut=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[vr({sectionId:e.sectionId,lineId:e.lineId})]:[]}},ct=(e,t={})=>{if(e?.rollback)return ea(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let r=e?.pointers?.read;return e.rollback=Ut({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},so=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=ct(r);n.isRestoring||(n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1)),n.timeline.push(vr(t)),n.currentIndex=n.timeline.length-1)},of=({state:e})=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;return!Array.isArray(r?.timeline)||typeof r.currentIndex!="number"?null:{checkpointIndex:r.currentIndex,checkpoint:r.timeline[r.currentIndex]??null}},sf=({state:e},t={})=>{let{checkpointIndex:r,checkpointIdentity:n,sectionId:o,lineId:i}=t,l=e.contexts?.[e.contexts.length-1]?.rollback;if(!Number.isInteger(r)||!Array.isArray(l?.timeline)||typeof l.currentIndex!="number")return e;let a=l.timeline[r];return(se(a)?Hr(a):a)!==n||a?.sectionId!==o||a?.lineId!==i||(a.returnable=!1),e},af=({state:e},t={})=>{let{slotId:r,saveSlotIdentity:n,checkpointIndex:o,sectionId:i,lineId:s}=t,l=Bt(r),a=e.global.saveSlots?.[l],c=se(a)?Hr(a):a;if(!a||c!==n)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=Zn,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}})),e},cf=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;if(!r||r.isRestoring||!Array.isArray(r.timeline)||typeof r.currentIndex!="number")return null;let n=st[st.length-1],o=typeof n?.checkpointIndex=="number"?n.checkpointIndex:r.currentIndex;return o<0||o>=r.timeline.length?null:(typeof n?.checkpointIndex!="number"&&o<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,o+1)),r.timeline[o]??null)},lf=({state:e},t={})=>{let r=t?.source===$s?$s:oo,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?(st.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),st.push({checkpointIndex:o.currentIndex,source:r}),e)},uf=({state:e})=>(st.pop(),e),Re=(e,t,r)=>{let o=st[st.length-1]?.source??oo;if(!Bp(t,o))return;let i=cf(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:D(r)}))},ks=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:l}of n){let 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}`);kt(c,o),dr(u,i,o),yn(u,i,s,o,{roundTo:l}),c==="context"&&(r.variables[o]=fr(r.variables[o],i,s,{roundTo:l}))}},df=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{Gp(e,r,n)})},ff=(e,t)=>{let{sectionId:r,lineId:n}=t,s=ce({state:e},{sectionId:r})?.lines?.find(l=>l.id===n)?.actions;s&&Object.entries(s).forEach(([l,a])=>{Ea(e,l,a)})},ta=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=ct(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&zt({state:e}),e.global.skipMode&&Ge({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=io(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=D(Er),e.global.overlayStack=[],It(e),At(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let l=i;l<=t;l++)l>i&&ro(e),ff(e,n.timeline[l]),df(e,n.timeline[l]);let s=wt(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},pf=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;Ds(t),Rt(t),Ze(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}=ur(t),p={...f,...dt(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:$d(s,"accountViewedRegistry"),nextLineConfig:Cr(),imageGalleryNavigation:eo(),saveSlots:Od(n),overlayStack:[],variables:p,...Kd({loadedGlobalRuntime:i})},contexts:[Zs({pointer:d,projectData:t})]}},hf=({state:e})=>e.global.overlayStack||[],mf=({state:e})=>e.global.pendingEffects,ra=({state:e})=>e.global.skipMode,gf=({state:e})=>e.global.autoMode,na=({state:e})=>e.global.dialogueUIHidden,oa=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(!r)return[];let{sectionId:n,lineId:o}=r.pointers.read,i=ce({state:e},{sectionId:n});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=$t({variables:{...e.global?.variables??{},...Sr(e)?.variables??{}},runtime:rt(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let d of l){let f=d.actions||{};if(c=et([c,f]),!f.dialogue)continue;let p=c.dialogue||{},h=lr({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:u}),g=vd({sectionId:n,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:g.content,text:g.text,characterId:g.characterId,character:g.character,characterName:g.characterName};continue}a.push(g)}return a},yf=({state:e})=>e.global.confirmDialog??null,Gt=({state:e},{pointer:t}={})=>{let r=t??Ee({state:e})?.pointer,n=Hd({state:e,pointer:r});return Wd({state:e,form:n.form,pointer:r})},bf=({state:e},{pointer:t}={})=>!!Gt({state:e},{pointer:t}),xe=({state:e},{pointer:t}={})=>{let r=Gt({state:e},{pointer:t});if(r)return{source:Be,formId:r.id,formKey:r.key};let n=aa({state:e,pointer:t});return n?{source:yt,resourceId:n}:null},If=({state:e,registry:t},r)=>{let{sectionId:n,lineId:o}=r,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===n);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let l=ce({state:e},{sectionId:n});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},ia=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},ao=({state:e},t)=>If({state:e,registry:e.global.accountViewedRegistry},t),Af=({state:e},t)=>ia({registry:e.global.accountViewedRegistry},t),Ft=(e,t)=>!ia({registry:e.global.accountViewedRegistry},{resourceId:t.imageId}),co=e=>e.groups.length===0?0:Math.ceil(e.groups.length/e.pageSize),lo=(e,t)=>{let r=co(e);if(r===0)return 0;let n=Number.isInteger(t?.pageIndex)?t.pageIndex:0;return Math.min(Math.max(n,0),r-1)},Qn=(e,t,r,n)=>{for(let o=r+n;o>=0&&o<t.length;o+=n)if(!Ft(e,t[o]))return t[o]},wf=({state:e})=>{let t=e.projectData?.resources?.imageGallery;return t===void 0?void 0:D(t)},sa=({state:e})=>{let t=e.projectData?.resources?.imageGallery;if(t===void 0)return null;let r=e.global.imageGalleryNavigation??eo(),n=co(t),o=lo(t,r),i=o*t.pageSize,s=t.groups.slice(i,i+t.pageSize).map(a=>({groupId:a.id,locked:Ft(e,a.variants[0]),variants:a.variants.map(c=>({variantId:c.id,imageId:c.imageId,locked:Ft(e,c)}))})),l=null;if(typeof r.groupId=="string"&&typeof r.variantId=="string"){let a=t.groups.findIndex(p=>p.id===r.groupId),c=t.groups[a],u=c?.variants.findIndex(p=>p.id===r.variantId),d=u===void 0||u<0?void 0:c.variants[u],f=a<0?-1:Math.floor(a/t.pageSize);d&&f===o&&!Ft(e,d)&&(l={groupId:c.id,variantId:d.id,imageId:d.imageId,canMoveToPreviousVariant:Qn(e,c.variants,u,-1)!==void 0,canMoveToNextVariant:Qn(e,c.variants,u,1)!==void 0})}return{pageGroups:s,selection:l,pagination:{pageIndex:o,pageCount:n,canMoveToPreviousPage:o>0,canMoveToNextPage:o+1<n}}},Ef=({state:e})=>e.global.nextLineConfig,aa=({state:e,pointer:t}={})=>{let r=t??Ee({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=ce({state:e},{sectionId:n})?.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},ca=({state:e})=>!!aa({state:e}),xf=({state:e})=>structuredClone(e),vf=({state:e})=>D(e.projectData.resources?.achievements??{}),Cf=({state:e},t)=>{let r=e.projectData.resources?.achievements?.[t?.resourceId];return r===void 0?void 0:D(r)},la=({state:e})=>e.global.saveSlots,Sf=({state:e},t)=>{let r=t?.slotId,n=Bt(r);return e.global.saveSlots[n]},uo=({state:e})=>rt(e),_f=({state:e},t)=>Me(e,t?.runtimeId),_r=({state:e})=>{let t={...e.global?.variables??{},...Sr(e)?.variables??{}};return $t({variables:t,runtime:rt(e),variableConfigs:e.projectData.resources?.variables??{}})},Ee=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},ce=({state:e},t)=>{let{sectionId:r}=t;return bt(e.projectData,r).section},Or=({state:e})=>{let t=Ee({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=ce({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},ua=({state:e})=>{let{sectionId:t,lineId:r}=Ee({state:e}).pointer,o=ce({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===r),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 et(l)},Of=e=>{let t=Or({state:e})?.actions?.dialogue;if(t?.clear===!0||!Array.isArray(t?.content))return"";let r=_r({state:e});return t.content.map(n=>`${ft(n?.text,{variables:r})??""}`).join("")},Rr=({state:e})=>_s({text:Of(e),baseDelay:Me(e,"autoForwardDelay"),speed:Me(e,"autoForwardSpeed")}),Rf=({state:e})=>{let t=da({state:e}),n=Or({state:e})?.actions??{},o=et([t??{},n]);return In(t??{},o??{})},$f=({state:e},{sectionId:t})=>{let r=ce({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},l=et([o,s]),a=In(o,l);n.push({id:i.id,changes:a,presentationState:l}),o=An(l)}return n},kf=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=$f({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},da=({state:e})=>{let{sectionId:t,lineId:r}=Ee({state:e}).pointer,o=ce({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===r);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 An(et(l))},fo=({state:e},{slotsPerPage:t=6}={})=>{let o=((uo({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[Bt(l)]||{};i.push({...a,slotId:l})}return{saveSlots:i}},Lf=la,Tf=fo,Nf=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;return!r||!Array.isArray(r.timeline)||typeof r.currentIndex!="number"?!1:r.currentIndex>=0&&r.currentIndex<r.timeline.length-1},Pf=({state:e},t={})=>{let r=ua({state:e}),n=da({state:e}),o=Or({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:D(i)}:o,l=i?.animations&&n===null?{}:n,{sectionId:a}=Ee({state:e}).pointer,{sceneId:c}=bt(e.projectData,a),u=uo({state:e}),d=t?.activePersistentAnimations??[],f=t?.restoredPersistentAnimations??[],p=Gt({state:e}),h=ca({state:e}),g=sa({state:e}),I=_r({state:e}),{saveSlots:b}=fo({state:e}),w=Nf(e);return cs({presentationState:r,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:Ca({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||w,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:oa({state:e}),saveSlots:b,variables:I,runtime:u,activePersistentAnimations:d,restoredPersistentAnimations:f,imageGallery:g})},Df=({state:e},t)=>(e.global.confirmDialog=Fd(t),e.global.pendingEffects.push({name:"render"}),e),Vf=({state:e})=>(e.global.confirmDialog&&(It(e),e.global.pendingEffects.push({name:"render"})),e),jf=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Re(e,"pushOverlay",t),e),Mf=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Re(e,"popOverlay",void 0),e),Ff=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),Re(e,"replaceLastOverlay",t),e),Uf=({state:e})=>(e.global.overlayStack=[],It(e),At(e),e.global.pendingEffects.push({name:"render"}),Re(e,"clearOverlays",void 0),e),Bf=(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"})},$r=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,Bd(e,r),At(e);let n=xe({state:e},{pointer:t}),o=n?.source===yt,i=n?.source===Be;return Bf(e,{activeInteraction:n}),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},kr=(e,t,r)=>{!(t?.source===yt||t?.source===Be)||r||!e.global.skipMode||e.global.pendingEffects.push({name:"startSkipNextTimer"})},fa=({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:Rr({state:e})}}),e.global.pendingEffects.push({name:"render"})),e),zt=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Gf=({state:e})=>{let t=e.global.autoMode;return xe({state:e})&&!t||(t?zt({state:e}):fa({state:e})),e},pa=({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),Ge=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),zf=({state:e})=>{let t=ra({state:e});return xe({state:e})&&!t||(t?Ge({state:e}):pa({state:e})),e},Lr=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Re(e,"showDialogueUI",void 0),e),ha=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Re(e,"hideDialogueUI",void 0),e),qf=({state:e})=>(na({state:e})?Lr({state:e}):ha({state:e}),e),ze=(e,t,r)=>(Qs(e,t,r),Zd(e),e.global.pendingEffects.push({name:"render"}),e),qt=(e,t,r,n)=>{let o=Qs(e,t,r);return e.global.pendingEffects.push({name:"render"}),Re(e,n,{value:o}),e},Yf=({state:e},t)=>ze(e,"dialogueTextSpeed",t?.value),Hf=({state:e},t)=>ze(e,"autoForwardDelay",t?.value),Wf=({state:e},t)=>ze(e,"autoForwardSpeed",t?.value),Kf=({state:e},t)=>ze(e,"skipUnseenText",t?.value),Jf=({state:e},t)=>ze(e,"skipTransitionsAndAnimations",t?.value),Xf=({state:e},t)=>ze(e,"soundVolume",t?.value),Qf=({state:e},t)=>ze(e,"musicVolume",t?.value),Zf=({state:e},t)=>ze(e,"muteAll",t?.value),ep=({state:e},t)=>qt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),tp=({state:e})=>{let t=Me(e,"saveLoadPagination")+1;return qt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},rp=({state:e})=>{let t=Me(e,"saveLoadPagination")-1;return qt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},np=({state:e},t)=>qt(e,"menuPage",t?.value,"setMenuPage"),op=({state:e},t)=>qt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),ip=({state:e})=>(e.global.pendingEffects=[],e),sp=({state:e},t)=>(e.global.pendingEffects.push(t),e),ap=({state:e},t)=>{let r=t?.resourceId;return Ns(e,r),e.global.pendingEffects.push({name:"completeAchievement",payload:{resourceId:r}}),e},cp=({state:e},t)=>{let r=t?.resourceId,n=Ns(e,r);if(n.type!=="number")throw new Error(`Achievement resource "${r}" does not support numeric progress`);let o=t?.current;if(!Number.isInteger(o)||o<0)throw new Error(`Achievement progress for "${r}" must be a non-negative integer`);if(!Number.isInteger(n.target)||n.target<1)throw new Error(`Achievement resource "${r}" must have a positive integer target`);let i=Math.min(o,n.target);return e.global.pendingEffects.push({name:"setAchievementProgress",payload:{resourceId:r,current:i,target:n.target,completed:i>=n.target}}),e},ma=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!Ys(n),i=ce({state:e},{sectionId:t});if(!i)return console.warn(`Section not found: ${t}`),e;let s=i.lines?.[0];if(!s)return console.warn(`Section ${t} has no lines`),e;if(r&&!rf(e,{queueRender:!o}))return e;let l=xe({state:e});r&&e.global.skipMode&&Ge({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let u=wt(a),d=u.read;r||at(e,{sectionId:d?.sectionId,lineId:d?.lineId}),a.rollback||ct(a,{compatibilityAnchor:!0}),u.read={sectionId:t,lineId:s.id},r?a.rollback=Ut({pointer:u.read}):so(e,{sectionId:t,lineId:s.id})}let{activeInteraction:c}=$r(e,a?.pointers?.read,{screenTransition:n});return kr(e,l,c),e},lp=({state:e},t)=>ma(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),ga=e=>(e.global.accountViewedRegistry=Ed(e.global.accountViewedRegistry),e.global.accountViewedRegistry),po=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(r=>({scope:r.scope,path:r.path,op:r.op,value:D(r.value)}))}})},ya=(e,t)=>{po(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(r=>({sectionId:r.sectionId,...r.lastLineId===void 0?{}:{lineId:r.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},up=(e,t,{sectionId:r,lineId:n})=>{if(!r||!n)return!1;let o=P(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===r);if(i){if(i.lastLineId===void 0)return!1;let s=ce({state:e},{sectionId:r});if(s?.lines){let l=s.lines.findIndex(c=>c.id===i.lastLineId),a=s.lines.findIndex(c=>c.id===n);if(l===-1||a>l)return i.lastLineId===n?!1:(i.lastLineId=n,!0)}else return i.lastLineId===n?!1:(i.lastLineId=n,!0);return!1}else return o.sections.push({sectionId:r,lastLineId:n}),!0},at=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;up(e,ga(e),t)&&ya(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},dp=({state:e},t)=>(at(e,t),e.global.pendingEffects.push({name:"render"}),e),fp=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=ga(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),ya(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},Yt=(e,t,r)=>{if(!P(t))throw new Error(`${e} payload must be an object`);Object.keys(t).forEach(n=>{if(!r.has(n))throw new Error(`${e} payload contains unsupported property "${n}"`)})},Ls=(e,t,r)=>{if(typeof r!="string"||r.length===0)throw new Error(`${e} requires a non-empty ${t}`)},Tr=(e,t)=>{let r=e.global.imageGalleryNavigation;r.groupId===t.groupId&&r.variantId===t.variantId&&r.pageIndex===t.pageIndex||(e.global.imageGalleryNavigation=t,e.global.pendingEffects.push({name:"render"}))},pp=({state:e},t)=>{let r="showImageGalleryVariant";Yt(r,t,Ad),Ls(r,"groupId",t.groupId),Object.prototype.hasOwnProperty.call(t,"variantId")&&Ls(r,"variantId",t.variantId);let n=e.projectData?.resources?.imageGallery;if(n===void 0)return e;let o=n.groups.findIndex(l=>l.id===t.groupId),i=n.groups[o];if(!i)return e;let s=t.variantId===void 0?i.variants[0]:i.variants.find(l=>l.id===t.variantId);return!s||Ft(e,s)||Tr(e,{groupId:i.id,variantId:s.id,pageIndex:Math.floor(o/n.pageSize)}),e},ba=(e,t,r,n)=>{Yt(n,t,to);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=Qn(e,s.variants,l,r);return a&&Tr(e,{...i,variantId:a.id}),e},hp=({state:e},t)=>ba(e,t,-1,"moveToPreviousImageGalleryVariant"),mp=({state:e},t)=>ba(e,t,1,"moveToNextImageGalleryVariant"),gp=({state:e},t)=>{if(Yt("clearImageGallerySelection",t,to),e.projectData?.resources?.imageGallery===void 0)return e;let n=e.global.imageGalleryNavigation;return Tr(e,{groupId:null,variantId:null,pageIndex:n.pageIndex}),e},Ia=(e,t)=>{let r=e.projectData?.resources?.imageGallery;if(r===void 0)return e;let n=co(r);if(t>=n)return e;let o=e.global.imageGalleryNavigation,i=lo(r,o);return t===i||Tr(e,{groupId:null,variantId:null,pageIndex:t}),e},yp=({state:e},t)=>{if(Yt("moveToImageGalleryPage",t,wd),!Number.isInteger(t.pageIndex)||t.pageIndex<0)throw new Error("moveToImageGalleryPage requires a non-negative integer pageIndex");return Ia(e,t.pageIndex)},Aa=(e,t,r,n)=>{Yt(n,t,to);let o=e.projectData?.resources?.imageGallery;if(o===void 0)return e;let s=lo(o,e.global.imageGalleryNavigation)+r;return s<0?e:Ia(e,s)},bp=({state:e},t)=>Aa(e,t,1,"moveToNextImageGalleryPage"),Ip=({state:e},t)=>Aa(e,t,-1,"moveToPreviousImageGalleryPage"),wa=({state:e},t)=>{let r=Sd(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;r&&n?(e.global.nextLineConfig={manual:r,auto:n},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(r&&(e.global.nextLineConfig.manual=r),n&&(e.global.nextLineConfig.auto=n),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let 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"}),Re(e,"setNextLineConfig",t),e},Ap=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:n}=t,o=t?.savedAt,i=Bt(r),s=D(e.contexts);s?.forEach(c=>{wt(c),ea(c.rollback),Rd(c.rollback)});let l={contexts:s},a={formatVersion:Ts,slotId:Vs(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:l};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},wp=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=Bt(r),o=e.global.saveSlots[n];if(o){let i=Md(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=Cr(),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},Ep=({state:e},t)=>{let{projectData:r}=t;Ds(r),Rt(r),Ze(r?.resources?.variables??{}),e.projectData=r,e.global.imageGalleryNavigation=eo();let n=r?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=ur(r??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...dt(e.global.variables,n)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...dt(s.variables,n)})}),It(e),At(e),e.global.pendingEffects.push({name:"render"}),e},xp=({state:e},t)=>{let{sectionId:r,lineId:n}=t;if(!n)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=r||o.pointers.read?.sectionId;if(r&&!ce({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=ce({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===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let a=xe({state:e}),c=wt(o);c.read={sectionId:i,lineId:n};let{activeInteraction:u}=$r(e,c.read);return kr(e,a,u),e},vp=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return Lr({state:e}),e;let r=xe({state:e});if(r?.source===yt&&t?.bypassChoice!==!0||r?.source===Be&&t?._interactionSource!==Be)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&&at(e,{sectionId:d,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&!r&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Rr({state:e})}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&!r&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=Ee({state:e})?.pointer,o=n?.sectionId,i=ce({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],l=i?.lines||[],c=l.findIndex(u=>u.id===n?.lineId)+1;if(c<l.length){let u=l[c],d=!Me(e,"skipUnseenText");if(e.global.skipMode&&d&&!ao({state:e},{sectionId:o,lineId:u.id}))return Ge({state:e}),e;if(s&&!s.rollback&&ct(s,{compatibilityAnchor:!0}),s){let p=wt(s),h=p.read?.lineId;h&&o&&at(e,{sectionId:o,lineId:h}),p.read={sectionId:o,lineId:u.id}}so(e,{sectionId:o,lineId:u.id}),ro(e);let{activeInteraction:f}=$r(e,{sectionId:o,lineId:u.id});kr(e,r,f)}else e.global.autoMode&&zt({state:e}),e.global.skipMode&&Ge({state:e});return e},Cp=({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:Rr({state:e})}});let r=Ee({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&at(e,{sectionId:n,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},Sp=({state:e},t)=>ma(e,{sectionId:t?.sectionId,screen:t?.screen}),_p=({state:e},t)=>{let r=t?._conditionalContinuation===!0;if(e.global.dialogueUIHidden&&!r)return Lr({state:e}),e;let n=xe({state:e});if(n?.source===yt&&t?.bypassChoice!==!0||n?.source===Be&&t?._interactionSource!==Be||n&&n.source!==yt&&n.source!==Be)return e;let o=Ee({state:e})?.pointer,i=o?.sectionId,s=ce({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&&!ao({state:e},{sectionId:i,lineId:d.id})&&(Ge({state:e}),!r))return e;if(l&&!l.rollback&&ct(l,{compatibilityAnchor:!0}),l){let h=wt(l),g=h.read?.lineId;g&&i&&at(e,{sectionId:i,lineId:g}),h.read={sectionId:i,lineId:d.id}}so(e,{sectionId:i,lineId:d.id}),ro(e);let{activeInteraction:p}=$r(e,{sectionId:i,lineId:d.id});kr(e,n,p)}else e.global.autoMode&&zt({state:e}),e.global.skipMode&&Ge({state:e}),e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},ho=(e,t={})=>{let r=Gt({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},Op=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let r=e.projectData.resources?.variables?.[t.variableId],n=r?.scope,o=r?.type;if(Ce(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return kt(n,t.variableId),dr(o,"set",t.variableId),{variableConfig:r,scope:n}},Rp=(e,t)=>({id:e.id,key:e.key,valid:!0,values:D(t),fields:D(e.fields),fieldList:D(e.fieldList)}),$p=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ee({state:e})?.pointer,r=t?.sectionId,n=t?.lineId;r&&n&&at(e,{sectionId:r,lineId:n})},kp=({state:e},t={})=>{let r=ho(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=Ws(e,r.key),i=xr(t.value),s=r.fields[n],l=no(s,i);return o.values[n]=i,o.touched[n]=!0,l?o.errors[n]=l:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},Lp=({state:e},t={})=>{let r=ho(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=Ws(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([d,f])=>{let p=Object.prototype.hasOwnProperty.call(n.values,d)?n.values[d]:f.value,h=no(f,p);n.touched[d]=!0,h&&(i[d]=h),o[d]=Hs(f,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:D(i),form:{id:r.id,key:r.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(r.fields).forEach(([d,f])=>{let{scope:p}=Op(e,f),h=p==="context"?s.variables:e.global.variables,g=o[d];h[f.variableId]=fr(h[f.variableId],"set",g),p==="context"&&(l=!0,c.push({variableId:f.variableId,op:"set",value:g})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${f.variableId}`,op:"set",value:D(h[f.variableId])})}),l&&Re(e,"updateVariable",{id:"submitForm",operations:c}),po(e,a);let u=Rp(r,o);return $p(e),delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},Tp=({state:e},t={})=>{let r=ho(e,t);return r?(delete e.global.formDrafts?.[r.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:r.id,key:r.key,values:D(r.values),fields:D(r.fields),fieldList:D(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},Np=({state:e},t)=>{let{id:r,operations:n=[]}=t;if(!r)throw new Error("updateVariable requires an id field");if(typeof r!="string"||!/^[a-zA-Z0-9]+$/.test(r))throw new Error(`updateVariable id must be alphanumeric, got: "${r}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],l=[];return n.forEach(({variableId: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}`);kt(p,a),dr(h,c,a),yn(h,c,u,a,{roundTo:d});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let I={variableId:a,op:c,value:u};d!==void 0&&(I.roundTo=d),l.push(I)}g[a]=fr(g[a],c,u,{roundTo:d}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:D(g[a])})}),i&&Re(e,"updateVariable",{id:r,operations:l}),po(e,s),e.global.pendingEffects.push({name:"render"}),e},Pp=e=>(t,r)=>e({state:t},r),Dp=e=>({variables:$t({variables:{...e.global?.variables??{},...Sr(e)?.variables??{}},runtime:rt(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:rt(e)}),Vp=e=>{if(!P(e))throw new Error("conditional action payload must be an object");if(!Array.isArray(e.branches))throw new Error("conditional action requires branches array");if(e.branches.length===0)throw new Error("conditional action requires at least one branch")},jp=(e,t,r)=>{if(!P(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!P(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==r-1)throw new Error("conditional else branch must be the last branch")},Mp=(e,t)=>{Vp(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(jp(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!Ot(n.when,Dp(e)))){Object.entries(n.actions).forEach(([i,s])=>{Ea(e,i,s)});return}}},Fp={conditional:{replayLine:Mp},updateVariable:{recordSources:[oo],replayLine:ks,replayRecorded:ks,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Pp(wa)}},Nr=e=>Fp[e]??null,Up=e=>Nr(e)?.persistInSaveSlot===!0,Bp=(e,t)=>{let r=Nr(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},Gp=(e,t,r)=>{Nr(t)?.replayRecorded?.(e,r)},Ea=(e,t,r)=>{Nr(t)?.replayLine?.(e,r)},zp=e=>e?.returnable!==!1,xa=(e,t)=>{if(t>=0)return e.currentIndex+t;let r=Math.abs(t);for(let n=e.currentIndex-1;n>=0;n-=1)if(zp(e.timeline[n])&&(r-=1,r===0))return n;return-1},va=({state:e},t)=>{let{offset:r}=t;if(r===void 0||typeof r!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let n=e.contexts[e.contexts.length-1];if(!n)return null;let o=n.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=xa(o,r);if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},Ca=({state:e})=>va({state:e},{offset:-1})!==null,qp=({state:e},t)=>{let{offset:r=-1}=t;if(r>=0)throw new Error("rollbackByOffset requires a negative offset");let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let o=ct(n,{compatibilityAnchor:!n.rollback}),i=xa(o,r);return i<0||i>=o.timeline.length?e:ta(e,i)},Yp=({state:e},t)=>{let{sectionId:r,lineId:n}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=ct(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===r&&a.lineId===n);if(l===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return l===i.currentIndex?e:ta(e,l)},Sa=e=>{let t=pf(e);return ai(t,{selectPendingEffects:mf,selectSkipMode:ra,selectAutoMode:gf,selectIsChoiceVisible:ca,selectIsFormVisible:bf,selectActiveInteraction:xe,selectActiveForm:Gt,selectDialogueUIHidden:na,selectDialogueHistory:oa,selectConfirmDialog:yf,selectIsLineAccountViewed:ao,selectIsResourceAccountViewed:Af,selectImageGalleryConfig:wf,selectImageGallery:sa,selectNextLineConfig:Ef,selectSystemState:xf,selectAchievements:vf,selectAchievement:Cf,selectSaveSlotMap:la,selectSaveSlots:Lf,selectSaveSlot:Sf,selectRuntime:uo,selectRuntimeValue:_f,selectAllVariables:_r,selectCurrentPointer:Ee,selectSection:ce,selectCurrentLine:Or,selectPresentationState:ua,selectAutoForwardTimerDelay:Rr,selectPresentationChanges:Rf,selectSectionLineChanges:kf,selectSaveSlotPage:fo,selectCurrentPageSlots:Tf,selectRenderState:Pf,selectOverlayStack:hf,selectLineIdByOffset:va,selectCanRollback:Ca,selectRollbackCursor:of,startAutoMode:fa,stopAutoMode:zt,toggleAutoMode:Gf,startSkipMode:pa,stopSkipMode:Ge,toggleSkipMode:zf,showDialogueUI:Lr,hideDialogueUI:ha,toggleDialogueUI:qf,setDialogueTextSpeed:Yf,setAutoForwardDelay:Hf,setAutoForwardSpeed:Wf,setSkipUnseenText:Kf,setSkipTransitionsAndAnimations:Jf,setSoundVolume:Xf,setMusicVolume:Qf,setMuteAll:Zf,setSaveLoadPagination:ep,incrementSaveLoadPagination:tp,decrementSaveLoadPagination:rp,setMenuPage:np,setMenuEntryPoint:op,showConfirmDialog:Df,hideConfirmDialog:Vf,resetStoryAtSection:lp,clearPendingEffects:ip,appendPendingEffect:sp,completeAchievement:ap,setAchievementProgress:cp,beginRollbackActionBatch:lf,endRollbackActionBatch:uf,markRollbackCheckpointTransient:sf,markSavedRollbackCheckpointTransient:af,addViewedLine:dp,addViewedResource:fp,showImageGalleryVariant:pp,moveToPreviousImageGalleryVariant:hp,moveToNextImageGalleryVariant:mp,clearImageGallerySelection:gp,moveToImageGalleryPage:yp,moveToNextImageGalleryPage:bp,moveToPreviousImageGalleryPage:Ip,setNextLineConfig:wa,saveSlot:Ap,loadSlot:wp,updateProjectData:Ep,sectionTransition:Sp,jumpToLine:xp,nextLine:vp,markLineCompleted:Cp,rollbackToLine:Yp,rollbackByOffset:qp,pushOverlay:jf,popOverlay:Mf,replaceLastOverlay:Ff,clearOverlays:Uf,updateFormField:kp,submitForm:Lp,cancelForm:Tp,updateVariable:Np,nextLineFromSystem:_p},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var Hp="route-engine",Wp="projectPersistence";var Oa=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),ee=e=>Object.prototype.toString.call(e)==="[object Object]",_a="variables.",Kp=(e={})=>{let t=ee(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!ee(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lineId=="string"?{lineId:r.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!ee(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Jp=(e={})=>{let t=ee(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!ee(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lastLineId=="string"?{lastLineId:r.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!ee(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Xp=(e,t)=>{let r=Jp(e),n=Kp(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.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}}),n.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},Ra=(e={})=>{let t=ee(e)?e:{};return{saveSlots:ee(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:ee(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:ee(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:ee(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:ee(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Qp=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!ee(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(_a)?t.path.slice(_a.length):null;if(n!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(n.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${r}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:n}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${r}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${r}].`)})},Zp=(e,t)=>{let r={};return Qp(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=Xp(r.accountViewedRegistry??e.accountViewedRegistry,n.value);return}let o=n.scope==="device"?"globalDeviceVariables":"globalAccountVariables";r[o]={...e[o],...r[o],[n.variableId]:n.value}}),r},mo=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},eh=e=>{let t=mo(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},th=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},rh=({indexedDB:e,databaseName:t,objectStoreName:r})=>new Promise((n,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(r)||s.createObjectStore(r,{keyPath:"namespace"})},i.onsuccess=()=>{n(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),nh=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let a=n.transaction(t,"readonly").objectStore(t).get(r);a.onsuccess=()=>{o(a.result??null)},a.onerror=()=>{i(a.error??new Error(`Failed to read persisted namespace "${r}" from IndexedDB.`))}})},Ht=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),a=l.objectStore(t),c=a.get(r),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 "${r}" before updating IndexedDB.`))},c.onsuccess=()=>{let p=Ra(c.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...Oa(),...p,...h},I=a.put(g);I.onerror=()=>{d(I.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},l.oncomplete=()=>{f()},l.onerror=()=>{d(l.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},l.onabort=()=>{d(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},oh=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let s=n.transaction(t,"readwrite"),a=s.objectStore(t).delete(r),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 "${r}" from IndexedDB.`))},s.oncomplete=()=>{d()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},go=(e={})=>{let{indexedDB:t,databaseName:r=Hp,objectStoreName:n=Wp,namespace:o}=e,i=th(t),s=eh(o),l=rh({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let a=await nh({databasePromise:l,objectStoreName:n,namespace:s});return{...Oa(),...Ra(a)}},clear:async()=>oh({databasePromise:l,objectStoreName:n,namespace:s}),saveSlots:async a=>Ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{saveSlots:ee(a)?a:{}}}),saveGlobalDeviceVariables:async a=>Ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:ee(a)?a:{}}}),saveGlobalAccountVariables:async a=>Ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalAccountVariables:ee(a)?a:{}}}),saveGlobalRuntime:async a=>Ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalRuntime:ee(a)?a:{}}}),applyScopedDataUpdates:async a=>Ht({databasePromise:l,objectStoreName:n,namespace:s,patch:c=>Zp(c,a)})}},ih=go;var sh=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),ah=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),$a="conditional",Io=Symbol("conditionalAutoContinue"),ch=new Set(["sectionTransition","resetStoryAtSection"]),lh=new Set(["nextLine","nextLineFromSystem","resetStoryAtSection","sectionTransition"]),uh=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),yo="form",dh=new Set(["submitForm","cancelForm"]),fh="showImageGalleryVariant",Et=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Pr=e=>e?.type===Io,bo=(e,t)=>e?.sectionId===t?.sectionId&&e?.lineId===t?.lineId;function Ao(e){let t,r=0,n=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,A=Date.now())=>new Map(Array.from(m.entries()).filter(([,E])=>A<E.expiresAt).map(([E,_])=>[E,{animation:structuredClone(_.animation),startedAt:_.startedAt,expiresAt:_.expiresAt}])),h=(m=new Map)=>Array.from(m.values()).map(A=>structuredClone(A.animation)),g=(m=Date.now())=>{c=new Map(Array.from(c.entries()).filter(([,A])=>m<A.expiresAt))},I=()=>{if(!(o>0||i)){i=!0;try{for(;t.selectPendingEffects().length>0;){let m=[...t.selectPendingEffects()];t.clearPendingEffects();try{f(m)}catch(A){throw t.clearPendingEffects(),m.forEach(E=>{t.appendPendingEffect(E)}),A}}}finally{i=!1}}},b=m=>{o+=1;let A=!1;try{let E=m();return A=!0,E}finally{o-=1,A&&I()}},w=({initialState:m,namespace:A})=>{t=Sa(m),r=0,n=mo(A),o=0,i=!1,s=0,l=[],a=null,c=new Map,u=new Map,d=new Map,t.appendPendingEffect({name:"handleLineActions"}),I()},S=()=>n,O=()=>t.selectPresentationState(),$=()=>t.selectPresentationChanges(),G=m=>t.selectSectionLineChanges(m),T=(m={})=>{r+=1;let A=Date.now();g(A);let E=u.size>0,_=p(c,A),k=E?p(u,A):new Map,K={...t.selectRenderState({activePersistentAnimations:h(_),restoredPersistentAnimations:h(k)}),id:`render-${r}`};return d.set(K.id,{builtAt:A,persistentAnimationSessions:new Map([...k.entries(),..._.entries()]),usedRestoredPersistentAnimationSessions:E}),K},x=(m={})=>T(m),q=(m={})=>T(m),Y=m=>{let A=typeof m?.id=="string"&&m.id.length>0?m.id:null,E=A?d.get(A):null;A&&d.delete(A);let _=new Map;Yi(m?.animations).forEach(k=>{let z=yr(k);if(!z)return;let K=E?.persistentAnimationSessions?.get(z)??c.get(z),ge=Math.max(0,Wi(k)),$e=K?.startedAt??E?.builtAt??Date.now();_.set(z,{animation:structuredClone(k),startedAt:$e,expiresAt:$e+ge})}),c=_,E?.usedRestoredPersistentAnimationSessions&&(u=new Map)},W=()=>t.selectSystemState(),B=()=>t.selectAchievements(),te=m=>t.selectAchievement(m),re=()=>t.selectSaveSlotMap(),de=m=>t.selectSaveSlot(m),Oe=m=>t.selectSaveSlotPage(m),ne=()=>t.selectImageGallery(),oe=()=>t.selectSkipMode(),le=()=>t.selectAutoMode(),ie=()=>t.selectRuntime(),Z=()=>t.selectIsChoiceVisible(),X=()=>t.selectIsFormVisible(),v=()=>t.selectActiveInteraction(),R=()=>t.selectPendingEffects().some(m=>m?.name==="handleLineActions"||m?.name==="render"),M=(m,A,E={})=>!Et(A)||m!=="nextLine"?A:E.bypassChoice===!0?{...A,bypassChoice:!0}:E.interactionSource===yo?{...A,_interactionSource:yo}:A,fe=(m={})=>({type:Io,payload:M("nextLine",{_conditionalContinuation:!0},m)}),me=(m,A)=>Pr(m)?{type:Io,payload:{...m.payload,...A.payload}}:A,F=m=>{m.savedCheckpointOccurrences.forEach(A=>{t.markSavedRollbackCheckpointTransient(A)}),m.savedCheckpointOccurrences=[]},qe=(m,A)=>{let E=a;return a=null,!E||!bo(E.pointer,m)||E.checkpointIndex!==A?.checkpointIndex||E.checkpointIdentity!==A?.checkpoint?[]:E.savedCheckpointOccurrences},Ye=m=>{m.markCurrentCheckpointTransient&&(t.markRollbackCheckpointTransient({checkpointIndex:m.rollbackCursor?.checkpointIndex,checkpointIdentity:m.rollbackCursor?.checkpoint,sectionId:m.pointer?.sectionId,lineId:m.pointer?.lineId}),F(m))},Ta=(m,A,E)=>lh.has(m)?m==="resetStoryAtSection"?E?.checkpoint!==A?.checkpoint:E?.checkpoint!==A?.checkpoint&&E?.checkpointIndex>A?.checkpointIndex:!1,Na=m=>{let A=l.at(-1);if(!A?.markCurrentCheckpointTransient)return;let E=t.selectSaveSlot({slotId:m?.slotId});E&&A.savedCheckpointOccurrences.push({slotId:m.slotId,saveSlotIdentity:E,checkpointIndex:A.rollbackCursor?.checkpointIndex,sectionId:A.pointer?.sectionId,lineId:A.pointer?.lineId})},Pa=(m,A,E)=>{let _=l.at(-1);if(!_)return;let k=t.selectCurrentPointer()?.pointer,z=Ta(m,A,E);if(bo(_.pointer,k)){let K=E?.checkpoint!==A?.checkpoint||E?.checkpointIndex!==A?.checkpointIndex;(z||K&&uh.has(m))&&(Ye(_),_.pointer=k,_.rollbackCursor=E,_.markCurrentCheckpointTransient=z,_.savedCheckpointOccurrences=[]);return}Ye(_),_.pointer=k,_.rollbackCursor=t.selectRollbackCursor?.()??null,_.markCurrentCheckpointTransient=z,_.savedCheckpointOccurrences=[]},Wt=(m,A)=>{if(!t[m])return;m==="updateProjectData"&&Da(A),ch.has(m)&&(s+=1),sh.has(m)&&(ah.has(m)?u=p(c):u=new Map,c=new Map);let E=t.selectRollbackCursor?.()??null,_=t[m](A),k=t.selectRollbackCursor?.()??null;return m==="saveSlot"&&Na(A),Pa(m,E,k),I(),_},Da=m=>{if(!Object.prototype.hasOwnProperty.call(m??{},"projectData"))throw new Error("updateProjectData requires projectData");Ze(m?.projectData?.resources?.variables??{}),Rt(m.projectData)},Va=(m,A,E)=>{let _=t.selectCurrentPointer()?.pointer;A!==_||E!==s||(t.appendPendingEffect({name:"clearAutoNextTimer"}),t.appendPendingEffect({name:"clearNextLineConfigTimer"}),Wt("nextLineFromSystem",m.payload))},ja=()=>({renderSequence:r,conditionalRoutingSequence:s,rollbackNavigationContexts:l.slice(),pendingRollbackLineEntrySaveHandoff:a,persistentAnimationSessions:new Map(c),restoredPersistentAnimationSessions:new Map(u),renderPersistentAnimationMetadata:new Map(d)}),Ma=m=>{r=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)},Eo=(m,A={})=>b(()=>{let E=ja();try{return t[gn](()=>{let _,k=t.selectCurrentPointer()?.pointer??null,z=t.selectRollbackCursor?.()??null,K=s,ge={pointer:k,rollbackCursor:z,markCurrentCheckpointTransient:A.rollbackSource==="line",savedCheckpointOccurrences:A.savedCheckpointOccurrences?.slice()??[]};l.push(ge);try{t.beginRollbackActionBatch({source:A.rollbackSource});try{_=m()}finally{t.endRollbackActionBatch({})}Pr(_)&&Va(_,k,K)}finally{l.pop(),(!bo(k,ge.pointer)||z?.checkpoint!==ge.rollbackCursor?.checkpoint)&&ge.markCurrentCheckpointTransient&&ge.savedCheckpointOccurrences.length>0&&(a={pointer:ge.pointer,checkpointIndex:ge.rollbackCursor?.checkpointIndex,checkpointIdentity:ge.rollbackCursor?.checkpoint,savedCheckpointOccurrences:ge.savedCheckpointOccurrences})}})}catch(_){throw Ma(E),_}}),xo=(m,A,E,_={})=>{if(m===$a)return Eo(()=>{let k=Vr(E),z=wn({[m]:A},k);return vo(z[m],E,_)},_);Wt(m,A)},Fa=(m,A)=>{xo(m,A)},Vr=m=>{if(!m)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(m,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:A,...E}=m,_=t.selectAllVariables?t.selectAllVariables():void 0;return{...E,_event:A,variables:_,runtime:t.selectRuntime?t.selectRuntime():{}}},Ua=m=>{if(!Et(m))return{templatePayload:m,literalTargetIds:null};let A=t.selectImageGalleryConfig();if(!Array.isArray(A?.groups))return{templatePayload:m,literalTargetIds:null};let E=typeof m.groupId=="string"?A.groups.find(k=>k.id===m.groupId):void 0;if(!E)return{templatePayload:m,literalTargetIds:null};let _=typeof m.variantId=="string"&&E.variants.some(k=>k.id===m.variantId);return{templatePayload:{...m,groupId:null,..._?{variantId:null}:{}},literalTargetIds:{groupId:m.groupId,..._?{variantId:m.variantId}:{}}}},Ba=m=>{if(!Et(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")},Ga=(m,A,E)=>{if(!Et(m))throw new Error(`conditional branch at index ${A} must be an object`);if(!Et(m.actions))throw new Error(`conditional branch at index ${A} requires actions object`);if(!Object.prototype.hasOwnProperty.call(m,"when")&&A!==E-1)throw new Error("conditional else branch must be the last branch")},vo=(m,A,E)=>{Ba(m);let _=fe(E);for(let k=0;k<m.branches.length;k+=1){let z=m.branches[k];Ga(z,k,m.branches.length);let K=Vr(A);if(Object.prototype.hasOwnProperty.call(z,"when")&&!Ot(z.when,K))continue;let $e=jr(z.actions,A,E);return Pr($e)?me(_,$e):_}return _},za=(m,A)=>({...m??{},_form:A}),qa=(m,A,E,_)=>{let k=Wt(m,A),z=k?.submitted===!0&&k.valid===!0,K=k?.cancelled===!0;if(!(!z&&!K)&&Et(A.actions))return jr(A.actions,za(E,k.form),{..._,interactionSource:yo})},Ya=(m,A,E,_)=>{let k=Vr(E),{templatePayload:z,literalTargetIds:K}=m===fh?Ua(A):{templatePayload:A,literalTargetIds:null},$e=wn({[m]:z},k)[m],So=K?{...$e,...K}:$e;if(m===$a)return vo(So,E,_);let _o=M(m,So,_);if(dh.has(m))return qa(m,_o,E,_);Wt(m,_o)},jr=(m,A,E)=>{let _;return Object.entries(m).forEach(([k,z])=>{let K=Ya(k,z,A,E);Pr(K)&&(_=me(_,K))}),_},Co=(m,A,E={})=>Eo(()=>jr(m,A,E),E),Ha=m=>{let A=t.selectCurrentPointer()?.pointer;if(m!==A||t.selectActiveInteraction())return;let E=t.selectNextLineConfig();E?.auto?.enabled&&E.auto.trigger==="fromStart"&&t.appendPendingEffect({name:"nextLineConfigTimer",payload:{delay:E.auto.delay}})};return{init:w,handleAction:xo,handleInternalAction:Fa,handleActions:Co,selectRenderState:x,prepareRenderState:q,commitRenderState:Y,selectPresentationState:O,selectPresentationChanges:$,selectSectionLineChanges:G,selectSystemState:W,selectAchievements:B,selectAchievement:te,selectSaveSlotMap:re,selectSaveSlot:de,selectSaveSlotPage:Oe,selectSaveSlots:re,selectImageGallery:ne,selectRuntime:ie,selectIsChoiceVisible:Z,selectIsFormVisible:X,selectActiveInteraction:v,selectHasPendingRenderWork:R,handleLineActions:()=>b(()=>{let m=t.selectCurrentPointer()?.pointer,A=t.selectRollbackCursor?.()??null,E=a,_=qe(m,A),k=t.selectCurrentLine(),z=!1;if(k?.actions){try{Co(k.actions,void 0,{rollbackSource:"line",savedCheckpointOccurrences:_})}catch(K){throw a=E,K}z=!0}return Ha(m),z}),getNamespace:S}}var wo=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},ph=80,La=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{if(e.selectHasPendingRenderWork?.())return;let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},hh=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&La({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},mh=({engine:e,ticker:t,autoTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let l=n.delay??1e3;r.getElapsed()>=l&&(t.remove(i),r.setCallback(null),r.setElapsed(0),Dr(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},gh=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},yh=({engine:e,ticker:t,skipTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let l=n?.delay??ph;r.getElapsed()>=l&&(r.setElapsed(0),Dr(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},bh=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Ih=({engine:e,ticker:t,nextLineConfigTimerState:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let l=n.delay??1e3;r.getElapsed()>=l&&(r.setElapsed(0),Dr(e,"nextLineFromSystem",{}),t.remove(i),r.getCallback()===i&&r.setCallback(null))};r.setCallback(i),t.add(i)},Ah=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},wh=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},Eh=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},xh=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},vh=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},Ch=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},ka={render:La,saveSlots:wh,saveGlobalDeviceVariables:Eh,saveGlobalAccountVariables:xh,saveGlobalRuntime:vh,applyScopedDataUpdates:Ch,handleLineActions:hh,startAutoNextTimer:mh,clearAutoNextTimer:gh,startSkipNextTimer:yh,clearSkipNextTimer:bh,nextLineConfigTimer:Ih,clearNextLineConfigTimer:Ah},Sh=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Dr=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},_h=(e=[])=>{let t=new Set,r=[];for(let n=e.length-1;n>=0;n-=1){let o=e[n];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!Sh.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},Oh=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let a=wo(),c=wo(),u=wo(),d=s??null,f=Promise.resolve(),p=null,h=null,g=!1,I=0,b=v=>{if(o){o(v);return}console.error("RouteEngine persistence write failed.",v)},w=()=>{if(d)return d;let v=e();return d=go({indexedDB:i,namespace:l??v?.getNamespace?.()}),d},S=v=>{f=f.catch(()=>{}).then(()=>{let R=w();return v(R)}).catch(R=>{b(R)})},O=v=>{let R=typeof v?.id=="string"&&v.id.length>0?v.id:null;I+=1,p=R,g=!1},$=()=>I,G=(v={})=>{if(v?.aborted===!0)return!1;let R=typeof v?.id=="string"&&v.id.length>0?v.id:null;return R?R!==p||R===h?!1:(h=R,!0):p!==null||g?!1:(g=!0,!0)},T=(v,R={})=>{if(v!=="renderComplete"||!G(R))return!1;let M=e();return Dr(M,"markLineCompleted",{}),!0},x=new Set(["updateFormField","submitForm","cancelForm"]),q=new Set(["updateVariable"]),Y=v=>typeof v?.selectActiveInteraction=="function"?v.selectActiveInteraction():typeof v?.selectIsChoiceVisible=="function"&&v.selectIsChoiceVisible()?{source:"choice"}:null,W=v=>v?._formKey??v?.formKey,B=(v,R)=>W(v)===R?.formKey,te=(v,R)=>!v||typeof v!="object"||Array.isArray(v)?!1:v._interactionSource===R?.source,re=(v,R)=>te(v,R)?R.source==="form"?B(v,R):!0:!1,de=(v,R)=>!v||typeof v!="object"||Array.isArray(v)||R?.source!=="form"?!1:B(v,R),Oe=(v={})=>Object.keys(v).some(R=>x.has(R)),ne=(v={},R)=>Object.entries(v).some(([M,fe])=>x.has(M)&&de(fe,R)),oe=(v={})=>Object.keys(v).length>0&&Object.keys(v).every(R=>q.has(R)),le=(v={},R)=>{let M=v?.actions;return R?.source==="form"?!M||typeof M!="object"||Array.isArray(M)?!1:ne(M,R)?!0:Oe(M)?!1:oe(M):re(v,R)?!0:!M||typeof M!="object"||Array.isArray(M)?!1:Object.values(M).some(fe=>re(fe,R))},ie=(v,R={})=>{if(!R?.actions)return!1;let M=Y(v);return!M||M.source==="choice"?!1:!le(R,M)},Z=({preprocessPayload:v,onEvent:R}={})=>async(M,fe={})=>{let me=e();if(ie(me,fe))return R?.(M,fe);let F=await v?.(M,fe)??fe;if(ie(me,F))return R?.(M,F);if(T(M,F),F?.actions){let qe=F?._event?{_event:F._event}:F?.event?{_event:F.event}:void 0,Ye;F?.bypassChoice===!0?Ye={bypassChoice:!0}:F?._interactionSource&&(Ye={interactionSource:F._interactionSource}),Ye?me.handleActions(F.actions,qe,Ye):me.handleActions(F.actions,qe)}return R?.(M,F)},X=v=>{let R=e(),M=_h(v),fe=M.some(F=>F.name==="handleLineActions");M.forEach(F=>{if(!ka[F.name]&&!n)throw new Error(`Unhandled pending effect "${F.name}".`)});let me={engine:R,routeGraphics:t,ticker:r,autoTimer:a,skipTimer:c,nextLineConfigTimerState:u,trackRenderDispatch:O,getRenderDispatchCount:$,enqueuePersistenceWrite:S};for(let F of M){if(fe&&F.name==="render")continue;let qe=ka[F.name];if(qe){qe(me,F.payload);continue}n(F,me)}};return X.handleRouteGraphicsEvent=T,X.createRouteGraphicsEventHandler=Z,X},Rh=Oh;var $h=(e,t={})=>{let{resources:r={}}=t;return Yn(e,r)};var cg=Ao;export{Cn as DEFAULT_VISUAL_LAYER,pt as RENDER_LAYER,ke as VISUAL_LAYER,Rh as createEffectsHandler,ih as createIndexedDbPersistence,cg as default,bn as formatDate,fl as resolveComputedVariables,$h as resolveLayoutReferences};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "route-engine-js",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.32.1",
|
|
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.
|
|
62
|
+
"route-graphics": "1.30.2",
|
|
63
63
|
"vitest": "4.0.16"
|
|
64
64
|
}
|
|
65
65
|
}
|