route-engine-js 1.28.0 → 1.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/RouteEngine.js +1 -1
- package/package.json +1 -1
package/dist/RouteEngine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var ms=Object.defineProperty;var gs=(e,t)=>{for(var r in t)ms(e,r,{get:t[r],enumerable:!0})};var Nn=Symbol.for("immer-nothing"),$n=Symbol.for("immer-draftable"),fe=Symbol.for("immer-state");function Ie(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Ze=Object.getPrototypeOf;function de(e){return!!e&&!!e[fe]}function Ue(e){return e?Vn(e)||Array.isArray(e)||!!e[$n]||!!e.constructor?.[$n]||kt(e)||Tt(e):!1}var ys=Object.prototype.constructor.toString();function Vn(e){if(!e||typeof e!="object")return!1;let t=Ze(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)===ys}function Rt(e,t){$t(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function $t(e){let t=e[fe];return t?t.type_:Array.isArray(e)?1:kt(e)?2:Tt(e)?3:0}function gr(e,t){return $t(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function jn(e,t,r){let n=$t(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function bs(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function kt(e){return e instanceof Map}function Tt(e){return e instanceof Set}function Me(e){return e.copy_||e.base_}function yr(e,t){if(kt(e))return new Map(e);if(Tt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=Vn(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[fe];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],c=n[s];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(n[s]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[s]})}return Object.create(Ze(e),n)}else{let n=Ze(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function Er(e,t=!1){return Dt(e)||de(e)||!Ue(e)||($t(e)>1&&(e.set=e.add=e.clear=e.delete=Is),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>Er(n,!0))),e}function Is(){Ie(2)}function Dt(e){return Object.isFrozen(e)}var As={};function Be(e){let t=As[e];return t||Ie(0,e),t}var lt;function Fn(){return lt}function ws(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function kn(e,t){t&&(Be("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function br(e){Ir(e),e.drafts_.forEach(Es),e.drafts_=null}function Ir(e){e===lt&&(lt=e.parent_)}function Tn(e){return lt=ws(lt,e)}function Es(e){let t=e[fe];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Dn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[fe].modified_&&(br(t),Ie(4)),Ue(e)&&(e=Ot(t,e),t.parent_||Lt(t,e)),t.patches_&&Be("Patches").generateReplacementPatches_(r[fe].base_,e,t.patches_,t.inversePatches_)):e=Ot(t,r,[]),br(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Nn?e:void 0}function Ot(e,t,r){if(Dt(t))return t;let n=t[fe];if(!n)return Rt(t,(o,i)=>Pn(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return Lt(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),Rt(i,(c,a)=>Pn(e,n,o,c,a,r,s)),Lt(e,o,!1),r&&e.patches_&&Be("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function Pn(e,t,r,n,o,i,s){if(de(o)){let c=i&&t&&t.type_!==3&&!gr(t.assigned_,n)?i.concat(n):void 0,a=Ot(e,o,c);if(jn(r,n,a),de(a))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(Ue(o)&&!Dt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Ot(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&Lt(e,o)}}function Lt(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Er(t,r)}function xs(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:Fn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=xr;r&&(o=[n],i=ut);let{revoke:s,proxy:c}=Proxy.revocable(o,i);return n.draft_=c,n.revoke_=s,c}var xr={get(e,t){if(t===fe)return e;let r=Me(e);if(!gr(r,t))return vs(e,r,t);let n=r[t];return e.finalized_||!Ue(n)?n:n===hr(e.base_,t)?(mr(e),e.copy_[t]=wr(n,e)):n},has(e,t){return t in Me(e)},ownKeys(e){return Reflect.ownKeys(Me(e))},set(e,t,r){let n=Mn(Me(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=hr(Me(e),t),i=o?.[fe];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(bs(r,o)&&(r!==void 0||gr(e.base_,t)))return!0;mr(e),Ar(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 hr(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,mr(e),Ar(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Me(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 Ze(e.base_)},setPrototypeOf(){Ie(12)}},ut={};Rt(xr,(e,t)=>{ut[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ut.deleteProperty=function(e,t){return ut.set.call(this,e,t,void 0)};ut.set=function(e,t,r){return xr.set.call(this,e[0],t,r,e[0])};function hr(e,t){let r=e[fe];return(r?Me(r):e)[t]}function vs(e,t,r){let n=Mn(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function Mn(e,t){if(!(t in e))return;let r=Ze(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=Ze(r)}}function Ar(e){e.modified_||(e.modified_=!0,e.parent_&&Ar(e.parent_))}function mr(e){e.copy_||(e.copy_=yr(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Cs=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,...l){return s.produce(a,f=>r.call(this,f,...l))}}typeof r!="function"&&Ie(6),n!==void 0&&typeof n!="function"&&Ie(7);let o;if(Ue(t)){let i=Tn(this),s=wr(t,void 0),c=!0;try{o=r(s),c=!1}finally{c?br(i):Ir(i)}return kn(i,n),Dn(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===Nn&&(o=void 0),this.autoFreeze_&&Er(o,!0),n){let i=[],s=[];Be("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,...c)=>this.produceWithPatches(s,a=>t(a,...c));let n,o;return[this.produce(t,r,(s,c)=>{n=s,o=c}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Ue(e)||Ie(8),de(e)&&(e=ze(e));let t=Tn(this),r=wr(e,void 0);return r[fe].isManual_=!0,Ir(t),r}finishDraft(e,t){let r=e&&e[fe];(!r||!r.isManual_)&&Ie(9);let{scope_:n}=r;return kn(n,t),Dn(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=Be("Patches").applyPatches_;return de(e)?n(e,t):this.produce(e,o=>n(o,t))}};function wr(e,t){let r=kt(e)?Be("MapSet").proxyMap_(e,t):Tt(e)?Be("MapSet").proxySet_(e,t):xs(e,t);return(t?t.scope_:Fn()).drafts_.push(r),r}function ze(e){return de(e)||Ie(10,e),Un(e)}function Un(e){if(!Ue(e)||Dt(e))return e;let t=e[fe],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=yr(e,t.scope_.immer_.useStrictShallowCopy_)}else r=yr(e,!0);return Rt(r,(n,o)=>{jn(r,n,Un(o))}),t&&(t.finalized_=!1),r}var pe=new Cs,vr=pe.produce,pd=pe.produceWithPatches.bind(pe),hd=pe.setAutoFreeze.bind(pe),md=pe.setUseStrictShallowCopy.bind(pe),gd=pe.applyPatches.bind(pe),yd=pe.createDraft.bind(pe),bd=pe.finishDraft.bind(pe);var m={LITERAL:0,VARIABLE:1,INTERPOLATION:2,FUNCTION:3,BINARY:4,UNARY:5,CONDITIONAL:6,LOOP:7,OBJECT:8,ARRAY:9,PARTIAL:10,PATH_REFERENCE:11},O={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},et={NOT:0};var E=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 Cr=e=>{if(!e||e.trim()==="")throw new E("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new E(`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 E(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Bn=e=>{if(e.trim().endsWith(" in"))throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new E(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new E(`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 E(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new E(`Invalid loop syntax (got: '$for ${e}')`)}};var zn=(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}'`)},qn=(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 Ss=(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=L(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},L=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return H(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return H(e.path,r,n);if(e.type===m.INTERPOLATION)return Rs(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return Hn(e,t,r,n);case m.BINARY:return Yn(e,t,r,n);case m.UNARY:return Gn(e,t,r,n);case m.CONDITIONAL:return Ls(e,t,r,n);case m.LOOP:return Ps(e,t,r,n);case m.OBJECT:return Vs(e,t,r,n);case m.ARRAY:return js(e,t,r,n);case m.PARTIAL:return Fs(e,t,r,n);case m.PATH_REFERENCE:return Ms(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Wn=new Map,_s=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 c=s.slice(1,-1);t.push({type:"property",value:c})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},H=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=Wn.get(e);if(!n){let i=[],s="",c=0;for(let a=0;a<e.length;a++){let l=e[a];l==="["?(c++,s+=l):l==="]"?(c--,s+=l):l==="."&&c===0?s&&(i.push(s),s=""):s+=l}s&&i.push(s),n=[];for(let a of i){let l=_s(a.trim());n.push(...l)}Wn.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},Rs=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},Hn=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw qn(e.name,o);let s=e.args.map(c=>L(c,t,r,n));return i(...s)},$e=(e,t,r,n)=>{if(e.var&&!e.type)return H(e.var,r,n);switch(e.type){case m.VARIABLE:return H(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return Yn(e,t,r,n);case m.UNARY:return Gn(e,t,r,n);case m.FUNCTION:return Hn(e,t,r,n);default:return L(e,t,r,n)}},Yn=(e,t,r,n)=>{if(e.op===O.AND||e.op===O.OR){let s=$e(e.left,t,r,n),c=$e(e.right,t,r,n);switch(e.op){case O.AND:return s&&c;case O.OR:return s||c}}let o=L(e.left,t,r,n),i=L(e.right,t,r,n);switch(e.op){case O.EQ:return o==i;case O.NEQ:return o!=i;case O.GT:return o>i;case O.LT:return o<i;case O.GTE:return o>=i;case O.LTE:return o<=i;case O.IN:return Array.isArray(i)?i.includes(o):!1;case O.ADD:if(typeof o!="number"||typeof i!="number")throw new ue(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case O.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}`)}},Gn=(e,t,r,n)=>{let o=e.op===et.NOT?$e(e.operand,t,r,n):L(e.operand,t,r,n);if(e.op===et.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Os=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(H(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let c={};for(let a of s.properties){let l=a.parsedKey?L(a.parsedKey,t,r,n):a.key,f=a.value;if(f.type===m.LITERAL)c[l]=f.value;else if(f.type===m.VARIABLE)c[l]=H(f.path,r,n);else if(f.type===m.INTERPOLATION){let u=[];for(let d of f.parts)if(typeof d=="string")u.push(d);else if(d.type===m.VARIABLE){let p=H(d.path,r,n);u.push(p!=null?String(p):"")}else{let p=L(d,t,r,n);u.push(p!=null?String(p):"")}c[l]=u.join("")}else c[l]=L(f,t,r,n)}return c}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let c={};for(let a of s.properties){let l=a.parsedKey?L(a.parsedKey,t,r,n):a.key,f=a.value;if(f.type===m.LITERAL)c[l]=f.value;else if(f.type===m.VARIABLE)c[l]=H(f.path,r,n);else if(f.type===m.INTERPOLATION){let u=[];for(let d of f.parts)if(typeof d=="string")u.push(d);else if(d.type===m.VARIABLE){let p=H(d.path,r,n);u.push(p!=null?String(p):"")}else{let p=L(d,t,r,n);u.push(p!=null?String(p):"")}c[l]=u.join("")}else c[l]=L(f,t,r,n)}return c}}}return null},Ls=(e,t,r,n)=>{let o=Os(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||$e(s,t,r,n))return L(e.bodies[i],t,r,n)}return Kn},$s=(e,t)=>{let r=e.body,n=e.itemVar;if(r.type===m.CONDITIONAL&&r.conditions.length===1&&r.conditions[0].type===m.VARIABLE){let o=r.conditions[0].path,i=r.bodies[0];if(o.startsWith(n+".")){let s=o.substring(n.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let a of i.properties)if(a.parsedKey)return null;let c=[];for(let a=0;a<t.length;a++){let l=t[a];if(l[s]){let f={};for(let u of i.properties){let d=u.key,p=u.value;if(p.type===m.LITERAL)f[d]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)f[d]=l;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);f[d]=l[g]}else return null}else if(p.type===m.INTERPOLATION){let h=[],g=!0;for(let y of p.parts)if(typeof y=="string")h.push(y);else if(y.type===m.VARIABLE){let b=y.path;if(b===n)h.push(l!=null?String(l):"");else if(b.startsWith(n+".")){let A=b.substring(n.length+1),x=l[A];h.push(x!=null?String(x):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;f[d]=h.join("")}else return null}c.push(f)}}return c}}}return null},ks=(e,t)=>{let r=e.body,n=e.itemVar,o=$s(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let c of r.properties)if(c.parsedKey)return null;let i=[],s=!0;for(let c of r.properties){let a=c.key,l=c.value;if(l.type===m.LITERAL)i.push({key:a,type:"literal",value:l.value});else if(l.type===m.VARIABLE){let f=l.path;if(f===n)i.push({key:a,type:"item"});else if(f.startsWith(n+".")){let u=f.substring(n.length+1);if(!u.includes(".")&&!u.includes("["))i.push({key:a,type:"prop",prop:u});else{s=!1;break}}else{s=!1;break}}else if(l.type===m.INTERPOLATION&&l.parts.length===1){let f=l.parts[0];if(f.type===m.VARIABLE){let u=f.path;if(u===n)i.push({key:a,type:"item_string"});else if(u.startsWith(n+".")){let d=u.substring(n.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:a,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let c=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 l=t[a];c[a]={id:l.id,title:l.title!=null?String(l.title):"",completed:l.completed}}else for(let a=0;a<t.length;a++){let l=t[a],f={};for(let u of i)if(u.type==="literal")f[u.key]=u.value;else if(u.type==="item")f[u.key]=l;else if(u.type==="prop")f[u.key]=l[u.prop];else if(u.type==="item_string")f[u.key]=l!=null?String(l):"";else if(u.type==="prop_string"){let d=l[u.prop];f[u.key]=d!=null?String(d):""}c[a]=f}return c}}return null},Ts=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let c=e.itemVar,a=e.indexVar;for(let l=0;l<o.length;l++){let f=o[l],u={},d={...n,[c]:f,...a&&{[a]:l}};d.__paths__||(d.__paths__=n.__paths__||{});let p=e.iterable.path||"";if(n&&n.__paths__&&p){let h=p.split("."),g=h[0];g in n.__paths__&&(p=n.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}d.__paths__={...d.__paths__,[c]:`${p}[${l}]`,...a&&{[a]:l}};for(let h of s.properties){let g=h.parsedKey?L(h.parsedKey,t,r,d):h.key,y=h.value;if(y.type===m.LITERAL)u[g]=y.value;else if(y.type===m.VARIABLE){let b=y.path;if(b===c)u[g]=f;else if(b===a)u[g]=l;else if(b.startsWith(c+".")){let A=b.substring(c.length+1);!A.includes(".")&&!A.includes("[")?u[g]=f[A]:u[g]=H(b,r,{...n,[c]:f,...a&&{[a]:l}})}else u[g]=H(b,r,{...n,[c]:f,...a&&{[a]:l}})}else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let x=A.path,S;if(x===c)S=f;else if(x===a)S=l;else if(x.startsWith(c+".")){let P=x.substring(c.length+1);!P.includes(".")&&!P.includes("[")?S=f[P]:S=H(x,r,{...n,[c]:f,...a&&{[a]:l}})}else S=H(x,r,{...n,[c]:f,...a&&{[a]:l}});b.push(S!=null?String(S):"")}else{let x={...n,[c]:f,...a&&{[a]:l}},S=L(A,t,r,x);b.push(S!=null?String(S):"")}u[g]=b.join("")}else{let b={...n,[c]:f,...a&&{[a]:l}};u[g]=L(y,t,r,b)}}i.push(u)}return i}return null},Ds=(e,t,r)=>{let n=e.body;if(n.type===m.OBJECT&&n.properties.length===1&&n.properties[0].key==="$if item.visible"){let i=n.properties[0].value;if(i.type===m.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===m.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===m.OBJECT&&s.properties.length===2){let c=s.properties[0],a=s.properties[1];if(c.key==="id"&&c.value.type===m.VARIABLE&&c.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===m.CONDITIONAL){let l=[];for(let f=0;f<t.length;f++){let u=t[f];if(u.visible){let d={id:u.id};u.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${u.name}`):(d.highlight=!1,d.message=u.name),l.push(d)}}return l}}}}return null},Ps=(e,t,r,n)=>{let o=L(e.iterable,t,r,n);if(!Array.isArray(o)){let l,f=!1;if(e.iterable.type===m.FUNCTION){f=!0;let d=e.iterable.args.map(p=>p.type===m.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===m.VARIABLE?p.path:p.type===m.FUNCTION?`${p.name}(...)`:"?").join(", ");l=`${e.iterable.name}(${d})`}else l=e.iterable.path||"undefined";let u=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw zn(u,o,f)}if(!e.indexVar){let l=Ds(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=ks(e,o);if(l!==null)return l}let i=Ts(e,t,r,n,o);if(i!==null)return i;let s=[],c=e.iterable.path||"";if(n&&n.__paths__&&c){let l=c.split("."),f=l[0];f in n.__paths__&&(c=n.__paths__[f],l.length>1&&(c+="."+l.slice(1).join(".")))}let a=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(l=>l.type===m.OBJECT&&l.properties.some(f=>f.key.startsWith("$if ")||f.key.startsWith("$when "))));for(let l=0;l<o.length;l++){let f=e.indexVar?{...n,[e.itemVar]:o[l],[e.indexVar]:l}:{...n,[e.itemVar]:o[l]};f.__paths__||(f.__paths__=n.__paths__||{}),f.__paths__={...f.__paths__,[e.itemVar]:`${c}[${l}]`},e.indexVar&&(f.__paths__[e.indexVar]=l);let u=L(e.body,t,r,f);if(Array.isArray(u)&&u.length===1&&!a){let d=u[0];s.push(d===void 0?{}:d)}else s.push(u===void 0?{}:u)}return s},Ns=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(o.parsedKey,t,r,n):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let c={},a={},l=!0;for(let f of s.properties){let u=f.parsedKey?L(f.parsedKey,t,r,n):f.key,d=f.value;if(d.type===m.LITERAL)a[u]=d.value;else if(d.type===m.VARIABLE)a[u]=H(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=H(h.path,r,n);p.push(g!=null?String(g):"")}else{l=!1;break}if(!l)break;a[u]=p.join("")}else if(d.type===m.OBJECT&&d.properties.length<=5){let p={};for(let h of d.properties){let g=h.key,y=h.value;if(y.type===m.LITERAL)p[g]=y.value;else if(y.type===m.VARIABLE)p[g]=H(y.path,r,n);else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let x=H(A.path,r,n);b.push(x!=null?String(x):"")}else{l=!1;break}if(!l)break;p[g]=b.join("")}else{l=!1;break}}if(!l)break;a[u]=p}else{l=!1;break}}if(l)return c[i]=a,c}}return null},Vs=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!$e(e.whenCondition,o,r,n))return;let i=Ns(e,t,r,n);if(i!==null)return i;if(e.fast){let l={};for(let f of e.properties){let u=f.parsedKey?L(f.parsedKey,t,r,n):f.key,d=f.value;if(d.type===m.LITERAL)l[u]=d.value;else if(d.type===m.VARIABLE)l[u]=H(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=H(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=L(h,t,r,n);p.push(g!=null?String(g):"")}l[u]=p.join("")}else l[u]=L(d,t,r,n)}return l}let s={},c=null,a=!1;for(let l of e.properties)if(!l.key.startsWith("$if ")&&!l.key.match(/^\$if\s+\w+.*:?$/)&&!l.key.startsWith("$elif")&&!l.key.startsWith("$else")&&!l.key.startsWith("$for ")){a=!0;break}for(let l of e.properties)if(l.key.startsWith("$if ")||l.key.match(/^\$if\s+\w+.*:?$/)){let f=L(l.value,t,r,n);if(!a&&f!==null&&f!==void 0)return Array.isArray(f)&&f.length===1?f[0]:f;typeof f=="object"&&f!==null&&!Array.isArray(f)&&Object.assign(s,f)}else if(l.key.startsWith("$for ")){if(e.properties.length===1)return L(l.value,t,r,n)}else{let f=l.value;if(f&&f.type===m.OBJECT&&f.properties){let u=f.properties.find(d=>d.key.startsWith("$for "));if(u){let d=L(u.value,t,r,n);d!==void 0&&(s[l.key]=d)}else{let d=L(l.value,t,r,n);d!==void 0&&(s[l.key]=d)}}else{let u=l.parsedKey?L(l.parsedKey,t,r,n):l.key,d=L(l.value,t,r,n);d!==void 0&&(s[u]=d)}}return s},Kn={},js=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=L(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,r,n);s!==Kn&&s!==void 0&&o.push(s)}return o},Fs=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,c=t.partials||{},a=t.functions||t;if(s&&!$e(s,a,r,n))return;if(!c[o])throw new ue(`Partial '${o}' is not defined`);let l=n._partialStack||[];if(l.includes(o))throw new ue(`Circular partial reference detected: ${o}`);let f=c[o],u=r,d={...n,_partialStack:[...l,o]};if(n){u={...r};for(let p of Object.keys(n))p.startsWith("_")||(u[p]=n[p])}if(i){let p=L(i,t,r,n);u={...u,...p}}return L(f,t,u,d)},Ms=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],c=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(c.length>0)throw new ue(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return c.length>0&&(a+="."+c.join(".")),a};var Sr=Ss;var Us=/\$\{([^}]*)\}/g,Bs=/#\{([^}]*)\}/g,Xn=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=zs(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},zs=(e,t={})=>e.trim()?qs(e).map(n=>Ws(n.trim(),t)):[],qs=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let c=e[s],a=s>0?e[s-1]:"";!o&&(c==='"'||c==="'")?(o=!0,i=c,r+=c):o&&c===i&&a!=="\\"?(o=!1,i="",r+=c):!o&&c==="("?(n++,r+=c):!o&&c===")"?(n--,r+=c):!o&&c===","&&n===0?(t.push(r),r=""):r+=c}return r&&t.push(r),t},Ws=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:m.LITERAL,value:parseFloat(e)};if(e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};let r=Xn(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:c,type:a}of o){let l=0;for(;l<n.length;){let f=qe(n.substring(l),c);if(f===-1)break;let u=l+f;u>i&&(i=u,s={op:c,type:a}),l=u+c.length}}if(i!==-1)try{return Q(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},Qn=/^\w+\(.*\)$/,Hs=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Ys=e=>{if(!(!e||e.trim()===""||Qn.test(e))&&Hs.test(e))throw e.includes("?")&&e.includes(":")?new E(`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 E(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new E(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Jn=e=>{let t=e.trim();if(Qn.test(t))throw new E(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new E(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new E(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new E(`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 E(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:m.PATH_REFERENCE,path:t}},ft=(e,t={})=>{let r=e.trim();Ys(r);let n=Xn(r,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};if(r.includes("[")&&!/[\s+\-*/%|&?:]/.test(r)){let o=0;for(let i of r)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:r}},_r=(e,t={})=>{let r=e,n=[];(e.includes("\\${")||e.includes("\\#{"))&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),r=r.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(l,f)=>{let u=`__ESCAPED_${n.length}__`;return n.push(f),u}),r=r.replace(/\\(#\{[^}]*\})/g,(l,f)=>{let u=`__ESCAPED_${n.length}__`;return n.push(f),u}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(Us)],i=[...r.matchAll(Bs)],s=[...o.map(l=>({match:l,type:"variable"})),...i.map(l=>({match:l,type:"pathref"}))].sort((l,f)=>l.match.index-f.match.index);if(s.length===0){let l=r;for(let f=0;f<n.length;f++)l=l.replace(`__ESCAPED_${f}__`,n[f]);return{type:m.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:l,type:f}=s[0];try{return f==="variable"?ft(l[1],t):Jn(l[1])}catch(u){if(u.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw u}}let c=[],a=0;for(let{match:l,type:f}of s){let[u,d]=l,p=l.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&&c.push(h)}try{let h;f==="variable"?h=ft(d.trim(),t):h=Jn(d.trim()),c.push(h)}catch(h){if(h.message==="Invalid array index syntax")c.push(u);else throw h}a=p+u.length}if(a<r.length){let l=r.substring(a);for(let f=0;f<n.length;f++)l=l.replace(`__ESCAPED_${f}__`,n[f]);l&&c.push(l)}return{type:m.INTERPOLATION,parts:c}};var Lr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),to=e=>Object.keys(e),ae=e=>e.join("."),ke=(e,t,r)=>{let n=to(e).filter(o=>!t.has(o));if(n.length>0)throw new E(`Unexpected key '${n[0]}' in condition JSON at '${ae(r)}'`)},Te=(e,t)=>typeof e=="string"?_r(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Ks(e,t):Js(e,t):{type:m.LITERAL,value:e},Gs=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new E("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new E("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new E("Empty $each body not allowed");if(r.$partial!==void 0)throw new E("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${n}`]:r}},Ks=(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=Gs(i),l=Object.keys(a);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let f=eo(l[0],a[l[0]],t,!0);r.push(f),n=!0;continue}}catch(a){throw a instanceof E?a:new E(a.message)}let c=Object.keys(i);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let a=eo(c[0],i[c[0]],t);r.push(a),n=!0;continue}}let s=Te(i,t);r.push(s),(s.type===m.FUNCTION||s.type===m.CONDITIONAL||s.type===m.LOOP||s.type===m.PARTIAL||s.type===m.OBJECT&&!s.fast||s.type===m.ARRAY&&!s.fast)&&(n=!0)}return{type:m.ARRAY,items:r,fast:!n}},Js=(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 E("$partial value must be a string");if(e.$partial.trim()==="")throw new E("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],l=[];for(let[b]of i)for(let A of a)if(b===A||b.startsWith(A+" ")||b.startsWith(A+"#")){l.push(A);break}if(l.length>0)throw new E(`Cannot use $partial with ${l.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:f,$when:u,...d}=e,p={},h=!1;for(let[b,A]of Object.entries(d)){let x=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(x=b.slice(1)),p[x]=A,h=!0}let g=null;if(h&&(g=Te(p,t),g.type===m.OBJECT)){let b=!1;for(let A of g.properties)if(A.value.type===m.VARIABLE||A.value.type===m.INTERPOLATION||A.value.type===m.FUNCTION||A.value.type===m.CONDITIONAL||A.value.type===m.OBJECT&&!A.value.fast||A.value.type===m.ARRAY&&!A.value.fast){b=!0;break}b&&(g.fast=!1)}let y={type:m.PARTIAL,name:f,data:g};return u!==void 0&&(y.whenCondition=Zn(u,t)),y}for(let[a,l]of i)if(a==="$when"){if(o!==null)throw new E("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new E("Missing condition expression after '$when'");o=Zn(l,t),n=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new E("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[a,l]=i[s];if(a==="$when"){s++;continue}if(a==="$each")throw new E("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let f=Xs(i,s,t);r.push({key:a,value:f.node}),n=!0,s=f.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let f=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",u=f?`:${f}`:"";throw new E(`$for loops must be inside arrays - use '- $for${u} item in items:' instead of '$for${u} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(a.startsWith("$elif ")||a.startsWith("$else"))throw new E(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new E("Missing condition expression after '$if'");{let f=Te(l,t);(f.type===m.FUNCTION||f.type===m.CONDITIONAL||f.type===m.PARTIAL||f.type===m.OBJECT&&!f.fast||f.type===m.ARRAY&&!f.fast)&&(n=!0);let u=_r(a,t),d={key:a,value:f};(u.type!==m.LITERAL||u.value!==a)&&(d.parsedKey=u),r.push(d),s++}}}let c={type:m.OBJECT,properties:r,fast:!n};return o&&(c.whenCondition=o),c},Xs=(e,t,r={})=>{let n=[],o=[],i=t,[s,c]=e[i],a=null,l;if(s.startsWith("$if#")){let u=s.match(/^\$if#(\w+)\s+(.+)$/);if(u)a=u[1],l=u[2];else throw new E(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());Cr(l);let f=Q(l,r);for(n.push(f),o.push(Te(c,r)),i++;i<e.length;){let[u,d]=e[i],p=!1,h;if(a?u.startsWith(`$elif#${a} `)?(h=u.substring(`$elif#${a} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(u===`$else#${a}`||u===`$else#${a}:`)&&(p=!0,h=null):u.startsWith("$elif ")?(h=u.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(u==="$else"||u==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{Cr(h);let g=Q(h,r);n.push(g)}if(o.push(Te(d,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:a},nextIndex:i}},Rr={eq:O.EQ,neq:O.NEQ,gt:O.GT,gte:O.GTE,lt:O.LT,lte:O.LTE,in:O.IN,add:O.ADD,sub:O.SUBTRACT},Or={all:O.AND,any:O.OR},Qs=new Set(["var","literal","call","not",...Object.keys(Rr),...Object.keys(Or)]),Zs=(e,t,r)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${ae(r)}' requires an array`);if(e.length!==2)throw new E(`Condition JSON operator '${t}' at '${ae(r)}' requires exactly 2 operands`);return e},ea=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${ae(o)}' requires an array`);if(e.length===0)throw new E(`Condition JSON operator '${t}' at '${ae(o)}' requires at least 1 condition`);return e.map((s,c)=>Ce(s,n,[...o,c])).reduce((s,c)=>({type:m.BINARY,op:r,left:s,right:c}))},ta=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],ke(e,new Set(["call","args"]),r);else if(Lr(e.call))n=e.call.name,o=e.call.args??[],ke(e,new Set(["call"]),r),ke(e.call,new Set(["name","args"]),[...r,"call"]);else throw new E(`Condition JSON call at '${ae(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new E(`Condition JSON call at '${ae(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new E(`Invalid condition JSON function name '${n}' at '${ae(r)}'`);if(!Array.isArray(o))throw new E(`Condition JSON call '${n}' at '${ae(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>Ce(i,t,[...r,"args",s]))}},Ce=(e,t={},r=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:m.LITERAL,value:e};if(Array.isArray(e))throw new E(`Condition JSON array at '${ae(r)}' must be wrapped in an operator or { literal: [...] }`);if(!Lr(e))throw new E(`Invalid condition JSON value at '${ae(r)}'`);let n=to(e);if(n.length===0)throw new E(`Condition JSON object at '${ae(r)}' must contain an operator`);let o=n.filter(s=>Qs.has(s));if(o.length===0)throw new E(`Unknown condition JSON operator '${n[0]}' at '${ae(r)}'`);if(o.length>1)throw new E(`Condition JSON at '${ae(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(ke(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new E(`Condition JSON var at '${ae(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return ke(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return ta(e,t,r);if(i==="not")return ke(e,new Set(["not"]),r),{type:m.UNARY,op:et.NOT,operand:Ce(e.not,t,[...r,"not"])};if(i in Or)return ke(e,new Set([i]),r),ea(e[i],i,Or[i],t,[...r,i]);if(i in Rr){ke(e,new Set([i]),r);let s=Zs(e[i],i,[...r,i]);return{type:m.BINARY,op:Rr[i],left:Ce(s[0],t,[...r,i,0]),right:Ce(s[1],t,[...r,i,1])}}throw new E(`Unknown condition JSON operator '${i}' at '${ae(r)}'`)},Zn=(e,t={})=>{if(e==null)throw new E("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression after '$when'");return Q(e,t)}return Lr(e)||Array.isArray(e)?Ce(e,t):{type:m.LITERAL,value:e}},Q=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let l=e.slice(1,-1),f=0,u=!0;for(let d=0;d<l.length;d++)if(l[d]==="("?f++:l[d]===")"&&f--,f<0){u=!1;break}if(u&&f===0)return Q(l,t)}let r=qe(e,"||");if(r!==-1)return{type:m.BINARY,op:O.OR,left:Q(e.substring(0,r).trim(),t),right:Q(e.substring(r+2).trim(),t)};let n=qe(e,"&&");if(n!==-1)return{type:m.BINARY,op:O.AND,left:Q(e.substring(0,n).trim(),t),right:Q(e.substring(n+2).trim(),t)};let o=[{op:">=",type:O.GTE},{op:"<=",type:O.LTE},{op:"==",type:O.EQ},{op:"!=",type:O.NEQ},{op:">",type:O.GT},{op:"<",type:O.LT},{op:" in ",type:O.IN}];for(let{op:l,type:f}of o){let u=qe(e,l);if(u!==-1)return{type:m.BINARY,op:f,left:Q(e.substring(0,u).trim(),t),right:Q(e.substring(u+l.length).trim(),t)}}let i=-1,s=null,c=[{op:" + ",type:O.ADD},{op:" - ",type:O.SUBTRACT}];for(let{op:l,type:f}of c){let u=0;for(;u<e.length;){let d=qe(e.substring(u),l);if(d===-1)break;let p=u+d;p>i&&(i=p,s={op:l,type:f}),u=p+l.length}}if(i!==-1&&s)return{type:m.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 l of a)if(qe(e,l)!==-1)throw new E(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:m.UNARY,op:et.NOT,operand:Q(e.substring(1).trim(),t)}:ro(e,t)},qe=(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},ra=e=>{if(e=e.trim(),e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:m.LITERAL,value:""};if(e==="{}")return{type:m.LITERAL,value:{}};if(e==="[]")return{type:m.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:m.LITERAL,value:t}:{type:m.VARIABLE,path:e}},ro=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return ft(r,t);let o=ra(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return ft(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},na=(e,t=!1)=>{let r=t?"$each":"$for";try{Bn(e)}catch(n){if(n instanceof E&&t){let o=n.message.replace(/\$for/g,"$each");throw new E(o.replace("Parse Error: ",""))}throw n}},eo=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new E(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],c=i[2].trim();na(c,n);let a=c.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let y=n?"$each":"$for";throw new E(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${c}')`)}let l=a[1].trim(),f=a[2].trim(),u,d=null;if(l.includes(",")){let y=l.split(",").map(b=>b.trim());if(y.length!==2)throw new E(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);u=y[0],d=y[1]}else u=l;let p=["this","undefined","null","true","false"];if(p.includes(u))throw new E(`Reserved variable name: ${u}`);if(d&&p.includes(d))throw new E(`Reserved variable name: ${d}`);let h=ro(f,r),g=Te(t,r);return{type:m.LOOP,itemVar:u,indexVar:d,iterable:h,body:g,flatten:s!=="nested"}};var oa=(e,t={})=>{let{functions:r={}}=t;return Te(e,r)},Pt=oa;var dt={};gs(dt,{now:()=>ia});var ia=()=>Date.now();var sa=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...dt,...n},s=Pt(e,{functions:i}),c={};for(let[a,l]of Object.entries(o))c[a]=Pt(l,{functions:i});return Sr(s,t,{functions:i,partials:c})},ce=sa;var aa=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",ca=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,la=(e,t)=>{if(aa(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression");return Q(e,t)}return Ce(e,t)},ua=(e,t={},r={})=>{let n=ca(r),o={...dt,...n},i=la(e,o);return!!$e(i,{functions:o,partials:{}},t,{})},$r=ua;var ht=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return $r(e,t)},co=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=a=>a,transformActionFirstArgument:c=a=>a}=r;for(let[a,l]of Object.entries(t))a!=="createInitialState"&&(a.startsWith("select")?o[a]=(...f)=>l(s(n),...f):i[a]=(...f)=>{let u;return n=vr(n,p=>{let h=l(c(p),...f);u=h!==void 0&&!de(h)?h:void 0}),u});return{...o,...i}},jt=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return vr(n,i=>{o.forEach(s=>{t.forEach(c=>{c(i,s)})})})};var fa=(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{}}},ge=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),pt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),lo=e=>{let t=de(e)?ze(e):e;return structuredClone(t)},da=({characterId:e,resourceCharacter:t,variables:r={}}={})=>{if(!ge(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},Ft=({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=da({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},De=e=>ge(e,"computed"),tt=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!De(t[r]))),pa=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),kr=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},ha=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=pa(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 kr(s,i)}return n==="runtime"?kr(t.runtime,r.slice(1)):kr(t,r)},ma=(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)`)},no=(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`)},ga=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},Ae=(e,t,r,n)=>(ma(e,t,n),t.map(o=>Vt(o,r))),me=(e,t,r,n)=>{let o=Ae(e,t,r,n);return o.forEach(i=>ga(e,i)),o},ya=(e,t,r)=>{switch(e){case"var":return ha(t,r);case"add":{let[n,o]=me(e,t,r,2);return n+o}case"sub":{let[n,o]=me(e,t,r,2);return n-o}case"mul":{let[n,o]=me(e,t,r,2);return n*o}case"div":{let[n,o]=me(e,t,r,2);return n/o}case"mod":{let[n,o]=me(e,t,r,2);return n%o}case"neg":{let[n]=me(e,t,r,1);return-n}case"round":{let[n]=me(e,t,r,1);return Math.round(n)}case"floor":{let[n]=me(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=me(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=me(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=me(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=me(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=Ae(e,t,r,2);return n==o}case"neq":{let[n,o]=Ae(e,t,r,2);return n!=o}case"gt":{let[n,o]=Ae(e,t,r,2);return n>o}case"gte":{let[n,o]=Ae(e,t,r,2);return n>=o}case"lt":{let[n,o]=Ae(e,t,r,2);return n<o}case"lte":{let[n,o]=Ae(e,t,r,2);return n<=o}case"in":{let[n,o]=Ae(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return no(e,t),t.every(n=>!!Vt(n,r));case"or":case"any":return no(e,t),t.some(n=>!!Vt(n,r));case"not":{let[n]=Ae(e,t,r,1);return!n}case"length":{let[n]=Ae(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:pt(n)?Object.keys(n).length:0}case"includes":{let[n,o]=Ae(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return lo(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},Vt=(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 ya(n,o,t)},ba=(e,t={})=>ht(e,{variables:t.variables,runtime:t.runtime}),Ia=(e,t)=>{if(!pt(e))throw new Error(`${t} must be an object`);let r=ge(e,"expr"),n=ge(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},Tr=(e,t,r)=>(Ia(e,t),ge(e,"value")?lo(e.value):Vt(e.expr,r)),Aa=(e,t={},r="unknown")=>{if(!pt(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=ge(e,"expr"),o=ge(e,"value");if(ge(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(!pt(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let c=e.branches[s];if(!pt(c))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!ge(c,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(ba(c.when,t))return Tr(c,`Computed variable "${r}" branch ${s}`,t)}return Tr(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 Tr(e,`Computed variable "${r}"`,t)},wa=(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}`)}},mt=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=tt(e,r),i=Object.entries(r).filter(([,u])=>De(u)).map(([u])=>u),s={},c=[],a=u=>{if(ge(s,u))return s[u];let d=r[u];if(!De(d))return o[u];let p=c.indexOf(u);if(p>=0){let h=[...c.slice(p),u].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}c.push(u);try{let h=Aa(d.computed,f,u);return wa(u,d.type,h),s[u]=h,h}finally{c.pop()}},l=new Proxy({},{get:(u,d)=>{if(typeof d=="string")return a(d)},has:(u,d)=>typeof d=="string"&&(ge(o,d)||i.includes(d)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(u,d)=>{if(!(typeof d!="string"||!ge(o,d)&&!i.includes(d)))return{enumerable:!0,configurable:!0}}}),f={variables:l,runtime:t,resolveVariable:a};return n?(i.forEach(u=>{a(u)}),{...o,...s}):l},Ea=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>mt({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),Mt=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(De(o))return;let i=fa(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},Ut=(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(", ")}`)},Bt=(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(", ")}`)},xa=2,oo=12,uo=(e=xa)=>{if(!Number.isInteger(e)||e<0||e>oo)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${oo}.`);return e},va=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},Nt=e=>typeof e=="number"&&Number.isFinite(e),Nr=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!Nt(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!Nt(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!Nt(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}".`);uo(o.roundTo)}}},zt=(e,t,r,n={})=>{let o=(s,c,a)=>{let l=s??c;if(!Nt(l))throw new Error(`Operation "${t}" requires ${a} to be a number.`);return l},i=s=>{let c=o(s,void 0,"value");if(c===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return c};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return va(o(e,0,"current value")/i(r),uo(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 fo=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let r=new Date(e),n=o=>String(o).padStart(2,"0");return t.replace("DD",n(r.getDate())).replace("MM",n(r.getMonth()+1)).replace("YYYY",r.getFullYear()).replace("YY",String(r.getFullYear()).slice(-2)).replace("HH",n(r.getHours())).replace("mm",n(r.getMinutes())).replace("ss",n(r.getSeconds()))},Ca=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let c=i.character?.sprite;return c&&Object.keys(c).length>0&&(s.sprite=c),Object.keys(s).length>0?s:void 0},n=r(e),o=r(t);return JSON.stringify(n)===JSON.stringify(o)?null:n&&!o?{changeType:"delete",data:e}:o&&!n?{changeType:"add",data:t}:o&&n?{changeType:"update",data:t}:null},io=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},so=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},ao=(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,Sa=(e,t)=>{let r={},n=ao(io(e),io(t)),o=ao(so(e),so(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},Vr=(e={},t={})=>{let r={},n=["sfx","voice"],o=c=>{let a=e[c],l=t[c];l&&!a?r[c]={changeType:"add",data:l}:a&&!l?n.includes(c)||(r[c]={changeType:"delete",data:a}):a&&l&&JSON.stringify(a)!==JSON.stringify(l)&&(r[c]={changeType:"update",data:l})},i=Sa(e.background,t.background);i&&(r.background=i),o("screen"),o("bgm"),o("voice");let s=Ca(e.dialogue,t.dialogue);return s&&(r.dialogue=s),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),r},jr=(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(c=>{let a={...c};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},_a=(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},Ra=(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=_a(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},Oa={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"])},po=(e,t)=>{let r=e[e.length-1];return r?Oa[r]?.has(t)===!0:!1},Dr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Dr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,po(r,n)?o:Dr(o,t,[...r,n])])):Ra(e,t),Pr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Pr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,po(r,n)?o:Pr(o,t,[...r,n])])):typeof e=="string"?ce(e,t):e,Fr=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let r=Dr(e,t._event);return Pr(r,t)};var Z=e=>structuredClone(de(e)?ze(e):e),U=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),ho=e=>e?.animations?.playback?.continuity==="persistent",$=(e,t)=>U(e??{},t)&&e[t]!==void 0,gt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:Z(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},La=e=>$(e,"opacity")||$(e,"blur"),bo=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Io=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Mr=["animationName","animationSpeed","loop"],$a=e=>bo.some(t=>$(e,t)),Ao=e=>e?.text&&$(e.text,"content")&&$(e.text,"textStyleId"),wo=e=>$(e,"text"),ka=(e,t)=>e.resourceId?!0:Ao(e)?!t?.text:!1,Ta=(e,t)=>{let r={...Z(e),...t};return t.text&&e.text&&(r.text={...Z(e.text),...Z(t.text)}),r},Da=(e,t)=>{if(wo(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!Ao(e)&&!t?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},mo=e=>Io.some(t=>$(e,t)),go=e=>Mr.some(t=>$(e,t)),Pa=(e,t,{hasAuthoredTransformId:r=!1}={})=>{if(!t)return e;for(let n of Io)!r&&!$(e,n)&&$(t,n)&&(e[n]=t[n]),U(e,n)&&e[n]===void 0&&delete e[n];return e},Eo=(e,t,r)=>{let n=e[r];return n?.id===t?.id?n:e.find(o=>o.id===t?.id)},Na=(e,t)=>{if(!t)return e;for(let r of bo)!$(e,r)&&$(t,r)&&(e[r]=t[r]),U(e,r)&&e[r]===void 0&&delete e[r];return e},Va=(e,t)=>(t&&(!$(e,"opacity")&&$(t,"opacity")&&(e.opacity=t.opacity),!$(e,"blur")&&$(t,"blur")&&(e.blur=Z(t.blur)),U(e,"opacity")&&e.opacity===void 0&&delete e.opacity,U(e,"blur")&&e.blur===void 0&&delete e.blur),e),xo=(e,t,r=[],{hasPatchFn:n=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,c)=>{let a=Eo(r,s,c),l=t(s,a),f=La(s),u=$a(s),d=n(s),p=U(s,"animations"),h=Z(s);return!l&&(f||u||d)&&a&&(h=o?o(a,h):{...Z(a),...h},p||delete h.animations),Va(Na(h,a),a)}).filter(s=>t(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},ja=e=>{if(e){if(e.character&&U(e.character,"name"))return e.character.name;if(U(e,"characterName"))return e.characterName}},vo=e=>!!e?.character&&U(e.character,"sprite"),Fa=e=>{let t={},r=!1,n=ja(e);return n!==void 0&&(t.name=n,r=!0),vo(e)&&(t.sprite=Z(e.character.sprite),r=!0),r?t:void 0},yo=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Ma=({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=>Z(o)):delete e.initialRevealedContent,e.content=[...n,...t]},Ua=()=>({}),Ba=(e,t)=>{if(!t.screen)return;let r=$(t.screen,"opacity"),n=$(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:$(i,"opacity")&&(s.opacity=i.opacity),n?s.blur=Z(t.screen.blur):$(i,"blur")&&(s.blur=Z(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},za=(e,t)=>{if(t.background){let r=$(t.background,"resourceId"),n=$(t.background,"colorId"),o=$(t.background,"opacity"),i=$(t.background,"blur"),s=$(t.background,"transformId"),c=mo(t.background),a=go(t.background),{animationsOnly:l,state:f}=gt(t.background,p=>$(p,"resourceId")||$(p,"colorId")||$(p,"opacity")||$(p,"blur")||$(p,"transformId")||mo(p)||go(p));if(l){e.background=e.background?{...Z(e.background),...f}:f;return}if(!r&&!n&&!o&&!i&&!s&&!c&&!a){delete e.background;return}let u=e.background,d=Z(t.background);if(!r&&u?.resourceId){d.resourceId=u.resourceId,!U(d,"transformId")&&u.transformId&&(d.transformId=u.transformId);for(let p of Mr)!$(d,p)&&$(u,p)&&(d[p]=u[p])}Pa(d,u,{hasAuthoredTransformId:s}),!n&&u?.colorId&&(d.colorId=u.colorId),!o&&$(u,"opacity")&&(d.opacity=u.opacity),!i&&$(u,"blur")&&(d.blur=Z(u.blur)),U(d,"resourceId")&&d.resourceId===void 0&&delete d.resourceId,U(d,"colorId")&&d.colorId===void 0&&delete d.colorId,U(d,"animations")&&d.animations===void 0&&delete d.animations,U(d,"transformId")&&d.transformId===void 0&&delete d.transformId,U(d,"opacity")&&d.opacity===void 0&&delete d.opacity,U(d,"blur")&&d.blur===void 0&&delete d.blur;for(let p of Mr)U(d,p)&&d[p]===void 0&&delete d[p];if(!d.resourceId&&!d.colorId){delete e.background;return}u?.resourceId===d.resourceId&&u?.transformId===d.transformId&&!U(d,"animations")&&ho(u)&&(d.animations=Z(u.animations)),e.background=d}else e.background?.animations&&!ho(e.background)&&(e.background.animations={})},qa=(e,t)=>{if(!t.dialogue){e.dialogue&&(yo(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,delete e.dialogue.textSpeed,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let r=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:l,state:f}=gt(t.dialogue.ui,u=>!!u.resourceId);l?e.dialogue.ui={...e.dialogue.ui,...f}: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&&Ma({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=U(t.dialogue,"characterId"),s=Fa(t.dialogue),c=s!==void 0,a=vo(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,c?e.dialogue.character=!i&&o&&e.dialogue.character?{...Z(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,a||yo(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let l={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.textSpeed!==void 0&&(l.textSpeed=e.dialogue.textSpeed),e.dialogue.character&&(l.character=Z(e.dialogue.character)),e.dialogue.lines.push(l)}},Wa=(e,t)=>{if(t.sfx){if(!t.sfx.items||t.sfx.items.length===0){delete e.sfx;return}e.sfx=t.sfx}else e.sfx&&delete e.sfx},Ha=(e,t)=>{if(t.bgm){if(!t.bgm.resourceId){e.bgm=void 0;return}e.bgm={...t.bgm,loop:t.bgm.loop||t.bgm.loop===void 0}}},Ya=(e,t)=>{if(t.visual){let r=e.visual?.items||[];t.visual.items?.forEach((i,s)=>{Da(i,Eo(r,i,s))});let{hasValidItems:n,processedItems:o}=xo(t.visual.items,ka,r,{hasPatchFn:wo,mergeItemFn:Ta});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))},Ga=(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}=xo(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},Ka=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Ja=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=gt(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},Xa=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=gt(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},Qa=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=gt(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=Z(t.form)}else e.form&&delete e.form},Za=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},ec=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},tc=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},We=e=>jt(Ua,[tc,Ba,za,Wa,Ha,Ya,qa,Ga,Ka,Ja,Xa,Qa,Za,ec])(e);var rt=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=ce(e,t);return r&&typeof r=="object"?e:r};var rc=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"}}),Pe=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}),yt=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Co=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"}),Ur=Object.freeze(["dialogueTextSpeed","autoForwardDelay","autoForwardSpeed","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Br=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),nc=(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]}},He=e=>Object.fromEntries(Object.entries(rc).map(([t,r])=>{let n=nc(e,r.source),o=n!==void 0?n:Pe[t]??yt[t];return[t,o]})),Ne=(e,t)=>He(e)[t],So=(e={})=>Object.fromEntries(Ur.map(t=>[t,e[t]??Pe[t]]));var nt=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:nt.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:nt.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:nt.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:nt.VISUAL_BEHIND_CHOICE,FOREGROUND:nt.VISUAL_FOREGROUND}),zr=_e.BEHIND_DIALOGUE,qr=Object.freeze(Object.values(_e).sort((e,t)=>e-t));var Re={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:fo},oc=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,ic=(e,t)=>{let r=String(t||"").trim();if(!r)return;let n=r.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of n){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},Ht=(e,t,r)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),c=oc.exec(s);if(c){let[,a,l,f]=c,u=ic(t,f);if(!Array.isArray(u))continue;let d=Array.isArray(i[s])?i[s]:[];u.forEach((p,h)=>{let g={...t,[a]:p};l&&(g[l]=h),d.forEach(y=>{let b=Ht(y,g,r),A=ce(b,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(Ht(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=Ht(i,t,r)}),n},sn=({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".`)},sc=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);if(sn({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n!==void 0){let s=uc(n,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},ac=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return sn({animationType:e.type,animationId:t,animationPath:r}),e.type},cc=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},lc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},uc=(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},fc=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},Ye=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Mo=e=>e?.playback?.continuity==="persistent",Jr=e=>Array.isArray(e)?e.map(Jr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=Jr(e[r]),t),{}),Gt=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(Jr(t))},Uo=(e=[])=>e.filter(t=>Mo(t)).map(t=>structuredClone(t)),Bo=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,r)=>{let n=typeof r?.duration=="number"&&Number.isFinite(r.duration)?r.duration:0;return t+n},0):0,Wr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,Bo(r)),0),zo=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(Wr(e.tween),Wr(e.prev?.tween),Wr(e.next?.tween),Bo(e.mask?.progress))/fc(e),_o=({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(Gt).filter(Boolean));return e.some(n=>{if(!Mo(n))return!1;let o=Gt(n);return o?r.has(o):!1})},we=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||_o({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:_o({animationInstances:e,activePersistentAnimations:o}),dc=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),pc=(e,t)=>{if(dc(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},hc=({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?sc({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},mc=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return sn({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},an=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(mc(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Xr=(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},gc=({content:e,path:t,variables:r})=>Xr(e,t).reduce((n,o)=>{let i=rt(o.text,{variables:r});return n+`${i??""}`.length},0),Ro=(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))},qt=(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("-")}`},Wt=(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},yc=(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},bc=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Ic=(e={})=>bc.some(t=>Ye(e,t)),qo=(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"}},Yt=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Ac=(e={})=>e.textStyles||{},wc=(e={})=>e.images||{},Ec=.5,xc=(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]},Wo=({id:e,resourceId:t,spritesheet:r,animationName:n,animationSpeed:o,loop:i,transform:s={}}={})=>{let c=xc(r,n,t),a=c?r.animations?.[c]: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??Ec,loop:i??a.loop??!0}}},Ho=({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 Wo({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}`)},vc=(e={})=>e.colors||{},Cc=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,It=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,it=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},Oo=(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},cn=(e,t)=>{if(typeof e!="string"||!Cc.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},Lo=(e,t,r)=>{let n=cn(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})`},Sc=(e={},t)=>{let r=Ac(e)?.[t];if(!r)throw new Error(`Text style "${t}" not found`);let n=e.fonts?.[r.fontId];if(!n)throw new Error(`Font "${r.fontId}" not found for text style "${t}"`);let o=e.colors?.[r.colorId];if(!o)throw new Error(`Color "${r.colorId}" not found for text style "${t}"`);let i=Oo(r.colorAlpha,"colorAlpha",t),s={fontFamily:n.fileId,fontSize:r.fontSize??16,fontWeight:r.fontWeight??"400",fontStyle:r.fontStyle??"normal",lineHeight:r.lineHeight??1.2,fill:Lo(o.hex,i,`Color "${r.colorId}" for text style "${t}"`)};if(r.align!==void 0&&(s.align=r.align),r.wordWrap!==void 0&&(s.wordWrap=r.wordWrap),r.breakWords!==void 0&&(s.breakWords=r.breakWords),r.wordWrapWidth!==void 0&&(s.wordWrapWidth=r.wordWrapWidth),r.strokeColorId){let c=e.colors?.[r.strokeColorId];if(!c)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let a=Oo(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=Lo(c.hex,a,`Stroke color "${r.strokeColorId}" for text style "${t}"`)}else if(r.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return r.strokeWidth!==void 0&&(s.strokeWidth=r.strokeWidth),s},Qr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Qr(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]=Qr(i,t,It(r,o)));return e.textStyleId!==void 0&&(it(e.textStyleId,r,"textStyleId"),n.textStyle=Sc(t,e.textStyleId)),n},ln=(e={},t)=>{let r=vc(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return cn(r.hex,`Color "${t}"`)},Yo=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Hr=(e,t,r)=>{let n=e?.[t];if(!(!n||typeof n!="object"||Array.isArray(n))&&Object.prototype.hasOwnProperty.call(n,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${r}". Use ${Yo(`${t}.fill`)} instead`)},_c=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>At(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;let n={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(n[o]=At(i,t,It(r,o)));return e.colorId!==void 0&&(it(e.colorId,r,"colorId"),n.fill=ln(t,e.colorId)),n},At=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>At(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${r}". Use ${Yo("fill")} instead`);Hr(e,"hover",r),Hr(e,"click",r),Hr(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]=_c(i,t,It(r,o));continue}n[o]=At(i,t,It(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(it(e.colorId,r,"colorId"),n.fill=ln(t,e.colorId)),n},Yr=(e={},t)=>{let r=wc(e)?.[t];return r||null},Go=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",$o=(e,t,r,n)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,n))throw new Error(`Inline ${t}.${n} is not allowed in sprite layout elements at "${r}". Use ${Go(`${t}.${n}`)} instead`)},ko=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},Zr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Zr(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${r}". Use ${Go(o)} instead`);$o(e,"hover",r,"src"),$o(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]=Zr(i,t,It(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){it(e.imageId,r,"imageId");let o=Yr(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&&(it(e.hoverImageId,r,"hoverImageId"),ko(n,"hover",Yr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(it(e.clickImageId,r,"clickImageId"),ko(n,"click",Yr(t,e.clickImageId)?.fileId??e.clickImageId)),n},un=(e,t={},r="root")=>Zr(At(Qr(e,t,r),t,r),t,r),Oe=un,Ge=(e=[])=>e.find(t=>t.id==="story"),Rc="#000000",en="bg-cg-background-color",Oc=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?cn(r?.backgroundColor??Rc,"screen.backgroundColor"):ln(e,t.colorId),Ko=(e={})=>{if(Ye(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Lc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},To=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=Ko(e),n=Lc(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},$c=(e={})=>{if(Ye(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},kc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Jo=(e={})=>{let t=$c(e),r=kc(e),n={};return t!==void 0&&(n.alpha=t),r&&(n.blur=r),n},bt=(e={})=>Jo(e),Ve=(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},Tc=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],fn=(e={})=>e.text&&Ye(e.text,"content")&&Ye(e.text,"textStyleId"),Do=(e={})=>{if(e.resourceId)return e.resourceId;if(fn(e))return"text"},Dc=e=>{if(e.text){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!fn(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let t of Tc)if(Ye(e.text,t))throw new Error(`Visual item "${e.id}" text.${t} is reserved for the visual item`)}},Pc=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:en,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:Oc({resources:e,background:t,screen:r})};if(n){let i=Ko(t);i!==void 0&&(o.alpha=i)}return o},Nc=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.spritesheets?.[t]||e.layouts?.[t]):!1,Po=({resources:e={},resourceId:t,colorId:r})=>{let n=qo(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:Yt({resourceId:t,kind:n})}:r!==void 0?{resourceId:en,targetId:en}:{resourceId:void 0,targetId:void 0}},Xo=100,Jt=Xo,Qo=(e,t)=>e*t/Xo,Vc=(e={},t=Jt)=>e?.muteAll?0:Qo(t,e?.soundVolume??Pe.soundVolume),jc=(e={},t=Jt)=>e?.muteAll?0:Qo(t,e?.musicVolume??Pe.musicVolume),Fc=({item:e,index:t}={})=>`sfx:${t}:${e?.resourceId}`,Ee=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,confirmDialog:u,form:d,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:b}={})=>{let A={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??c??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},x=qc({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e,runtime:A}),S={variables:e,runtime:A,saveSlots:r,isChoiceVisible:a,isFormVisible:l,canRollback:f,confirmDialog:u,form:d,historyDialogue:p,characters:h};return x&&(S.dialogue=x,S.dialogueLines=x.lines),S},No=100,Kt=(e,t)=>{if(Array.isArray(e))return e.map(n=>Kt(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=Kt(r[n],t)}),r.type==="text-revealing"?t(r):r},Mc=e=>Kt(e,t=>({...t,revealEffect:"none"})),Uc=e=>Kt(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,No):No;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),je=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?Mc(e):r?Uc(e):e,Zo=({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:{}}}}),tn=e=>{if(Array.isArray(e))return e.map(tn);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=tn(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}}:{}}}}},Bc=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),Vo="submit",Gr=(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}}},rn=(e,t,r={})=>{if(Array.isArray(e))return e.map(l=>rn(l,t,r));if(!e||typeof e!="object")return e;let n=typeof e.type=="string",o=n&&e.formRole===Vo,i=n&&r.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},c={};for(let[l,f]of Object.entries(e))c[l]=rn(f,t,l==="children"?s:{});let a=c;if(a.type==="input"&&typeof a.field=="string"){let l=t?.fields?.[a.field];if(l){let f={updateFormField:{formKey:t.key,field:l.id,value:"_event.value"}};a={...a,value:l.value,placeholder:a.placeholder===void 0?l.placeholder:a.placeholder,multiline:a.multiline===void 0?l.multiline:a.multiline,...a.maxLength===void 0&&l.maxLength!==void 0?{maxLength:l.maxLength}:{},change:Gr(a.change,f),submit:Gr(a.submit,t.submitActions)}}}return a.formRole===Vo||i?{...a,click:Gr(a.click,t.submitActions,{replaceActions:!0})}:a},nn=(e,t)=>{if(Array.isArray(e))return e.map(n=>nn(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=nn(o,t);for(let n of Bc){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form"}})}return r},on=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0,s=Ft({characterId:e,character:t,characterName:r,characters:n,variables:o});return{...i||{},...t||{},name:s}},ei=(e=[],t={},r={})=>e.map(n=>{let o=on({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}}),zc=e=>!(!e||e.mode==="adv"&&e.content===void 0),qc=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n,runtime:o}={})=>{if(!t&&!zc(e))return;let i=e.content===void 0?[{text:""}]:Xr(e.content,"dialogue.content"),s=e.content===void 0?0:gc({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),c=o?.dialogueTextSpeed??Pe.dialogueTextSpeed,a=e.textSpeed??c,l=(e.lines||[]).map((u,d)=>{let p=Xr(u.content,`dialogue.lines[${d}].content`),h=on({characterId:u.characterId,character:u.character,characterName:u.characterName,characters:r,variables:n});return{...u,textSpeed:u.textSpeed??c,content:p.map(g=>({...g,text:rt(g.text,{variables:n})})),character:h,characterName:h.name}}),f=on({characterId:e.characterId,character:e.character,characters:r,variables:n});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:f,textSpeed:a,content:i.map(u=>({...u,text:rt(u.text,{variables:n})})),initialRevealedCharacters:s,lines:l}},ti=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=ce(e,r,{functions:Re});return Oe(je(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},Kr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),jo=({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:Kr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:Kr(o.keyup)});return}e[n]={...i,[r]:{payload:Kr(o)}}})},Wc=(e={},t={})=>{let r={};return jo({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),jo({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},Le=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:c})=>{if(!e)return[];let a=[],l=({instanceId:b,targetId:A})=>{let x=hc({resources:t,animationId:p,playback:h,instanceId:b,targetId:A,animationPath:s});x&&a.push(x)},f=r!=null&&r!==!1,u=n!=null&&n!==!1,d=o&&i&&o===i;pc(e,s);let p=cc(e),h=lc(e),g=t?.animations?.[p],y=ac(g,{animationId:p,animationPath:s});if(y==="update")return u&&i?l({instanceId:`${c}-animation-update`,targetId:i}):f&&o&&l({instanceId:`${c}-animation-update`,targetId:o}),a;if(y==="transition"){let b=`${c}-animation-transition`,A=h?.continuity==="persistent"?b:`${c}-animation-in`;if(f&&u&&d)return l({instanceId:b,targetId:i}),a;f&&l({instanceId:`${c}-animation-out`,targetId:o}),u&&l({instanceId:A,targetId:i})}return a},Hc=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Yc=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:c,variables:a,runtime:l,activePersistentAnimations:f,restoredPersistentAnimations:u,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,saveSlots:A=[]})=>{let{elements:x,animations:S}=e;if(t.background){let P=n===void 0?!0:Ye(n?.background??{},"animations"),k=x.find(oe=>oe.id==="story");if(!k)return e;let w=yc(o,t.background),j=w||Ic(t.background),M=r?.background?.resourceId,ee=r?.background?.colorId,N=t.background.resourceId??(t.background.animations?M:void 0),q=t.background.colorId??(t.background.animations?ee:void 0),W=Nc(o,N),te={...t.background,colorId:q};if((q!==void 0||W)&&k.children.push(Pc({resources:o,background:te,screen:i,includeOpacity:!W})),N){let{images:oe={},videos:re={},spritesheets:K={}}=o,ie=qo(o,N),se;if(ie==="sprite"?se=oe[N]:ie==="video"?se=re[N]:ie==="spritesheet-animation"&&(se=K[N]),se){let v=ie==="video",_=ie==="spritesheet-animation",V={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...w},J={...To(t.background,{includeDefaultAlpha:!0}),...Ve(V,t.background)},z;_?z=Wo({id:Yt({resourceId:N,kind:ie}),resourceId:N,spritesheet:se,animationName:t.background.animationName,animationSpeed:t.background.animationSpeed,loop:t.background.loop,transform:J}):z={id:Yt({resourceId:N,kind:ie}),type:v?"video":"sprite",src:se.fileId,width:se.width,height:se.height,...J},v&&(z.loop=t.background.loop??!1,z.volume=se.volume??50),z&&k.children.push(z)}}if(N){let{layouts:oe={}}=o,re=oe[N];if(re){let K={id:Yt({resourceId:N,kind:"container"}),type:"container",children:re.elements,...To(t.background)};j&&Object.assign(K,Ve({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...w},t.background));let ie=ce(K,Ee({variables:a,runtime:l,saveSlots:A,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,characters:o.characters||{},skipTransitionsAndAnimations:c}),{functions:Re});k.children.push(Oe(je(ie,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:c}),o))}}let xe=Po({resources:o,resourceId:M,colorId:ee}),Y=Po({resources:o,resourceId:N,colorId:q}),G=Le({animationsDef:t.background.animations,resources:o,previousResourceId:xe.resourceId,currentResourceId:Y.resourceId,previousTargetId:xe.targetId,currentTargetId:Y.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});we({animationInstances:G,isLineCompleted:s,skipTransitionsAndAnimations:c,activePersistentAnimations:f,restoredPersistentAnimations:u,isAuthoredOnCurrentLine:P})&&S.push(...G)}return e},Gc=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:c,animations:a}=e;if(t.character&&n){let l=c.find(h=>h.id==="story");if(!l)return e;let f=t.character.items||[],u=r?.character?.items||[],d=Ro(f),p=Ro(u);for(let h=0;h<f.length;h++){let g=f[h],{transformId:y,sprites:b}=g,A=u.find(N=>N.id===g.id),x=u.findIndex(N=>N.id===g.id),S=A?.sprites&&A.sprites.length>0,P=b&&b.length>0,k=x>=0?qt(A,x,p):void 0,w=Le({animationsDef:g.animations,resources:n,previousResourceId:k,currentResourceId:P?qt(g,h,d):void 0,previousTargetId:k,currentTargetId:P?qt(g,h,d):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&S&&we({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...w);continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let j=qt(g,h,d),M=n.transforms[y];if(!M){console.warn("Transform not found:",y);continue}let ee={type:"container",id:j,...Ve(M,g),...bt(g),children:[]};for(let N of b){let q=Ho({id:`${j}-${N.id}`,item:N,resources:n});q&&ee.children.push(q)}l.children.push(ee),we({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...w)}}return e},ri=(e,t)=>{if(!qr.includes(e))throw new Error(`${t} must be one of: ${qr.join(", ")}.`)},Kc=(e,t)=>{let r=!!e.resourceId||fn(e),n=e.layer??(r?void 0:t?.layer)??zr;return ri(n,`Visual item "${e.id}" layer`),n},Jc=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:c,activePersistentAnimations:a,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,form:h,saveSlots:g=[],visualLayer:y})=>{let{elements:b,animations:A}=e;if(t.visual&&n){let x=b.find(w=>w.id==="story");if(!x)return e;let S=t.visual.items,P=r?.visual?.items||[],k=Ee({variables:s,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i});y!==void 0&&ri(y,"visualLayer");for(let w of S){let j=P.find(W=>W.id===w.id),M=Kc(w,j);if(y!==void 0&&M!==y)continue;if(Dc(w),w.text){let W=Wt(n,w),te={...structuredClone(w.text),id:`visual-${w.id}`,type:"text",...Ve(W,w)};Object.assign(te,bt(w)),x.children.push(Oe(ce(te,k,{functions:Re}),n))}if(w.resourceId){let{images:W={},videos:te={},spritesheets:xe={}}=n,Y=xe[w.resourceId];if(Y){let G=Wt(n,w),oe=w.animationName;if(oe){let re=Y.animations?.[oe];if(!re)throw new Error(`Animation '${oe}' not found in spritesheet resource '${w.resourceId}'`);let K=bt(w),ie={id:`visual-${w.id}`,type:"spritesheet-animation",...Ve(G,w),width:w.width??Y.width,height:w.height??Y.height,alpha:K.alpha??w.alpha??1,src:Y.fileId,atlas:Y.jsonData,playback:{frames:re.frames,animationSpeed:w.animationSpeed??re.animationSpeed??.5,loop:w.loop??re.loop??!0}};K.blur&&(ie.blur=K.blur),x.children.push(structuredClone(ie))}}else{let G=W[w.resourceId]||te[w.resourceId];if(G){let oe=te[w.resourceId]!==void 0,re=Wt(n,w),K={id:`visual-${w.id}`,type:oe?"video":"sprite",src:G.fileId,width:G.width,height:G.height,...Ve(re,w)};Object.assign(K,bt(w)),oe&&(K.loop=G.loop??!1,K.volume=G.volume??50),x.children.push(K)}}}if(w.resourceId){let{layouts:W={}}=n,te=W[w.resourceId];if(te){let xe=Wt(n,w),Y={id:`visual-${w.id}`,type:"container",children:structuredClone(te.elements),...Ve(xe,w)};Object.assign(Y,bt(w));let G=ce(Y,k,{functions:Re});x.children.push(Oe(je(G,{isLineCompleted:o,skipMode:f,skipTransitionsAndAnimations:i}),n))}}let ee=Do(j),N=Do(w),q=Le({animationsDef:w.animations,resources:n,previousResourceId:ee,currentResourceId:N,previousTargetId:ee?`visual-${w.id}`:void 0,currentTargetId:N?`visual-${w.id}`:void 0,animationPath:`visual.items[${w.id}].animations`,idPrefix:w.id});we({animationInstances:q,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:a})&&A.push(...q)}}return e},ot="dialogue-character-sprite",Fo=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,Xc=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=Ge(e.elements);if(!a)return e;let l=t.dialogue?.character?.sprite,f=r?.dialogue?.character?.sprite,u=Fo(l),d=Fo(f),p=Le({animationsDef:l?.animations,resources:n,previousResourceId:d?ot:void 0,currentResourceId:u?ot:void 0,previousTargetId:d?ot:void 0,currentTargetId:u?ot:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!u)return l?.animations&&d&&we({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e;let h=n.transforms?.[l.transformId];if(!h)return console.warn("Transform not found:",l.transformId),e;let g={type:"container",id:ot,...Ve(h),children:[]};for(let y of l.items){let b=Ho({id:`${ot}-${y.id}`,item:y,resources:n});b&&g.children.push(b)}return a.children.push(g),we({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e},Qc=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:f,skipOnlyViewedLines:u,isLineCompleted:d,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:y,saveSlots:b=[]})=>{let{elements:A,animations:x}=e;if(!t.dialogue||o)return e;let S=A.find(k=>k.id==="story");if(!S)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:k={}}=n,w=k[t.dialogue.ui.resourceId];if(w){let j={elements:w.elements},M=Ee({variables:h,runtime:g,saveSlots:b,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:d,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:f,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:u,skipTransitionsAndAnimations:p}),ee={functions:Re},N=Ht(j,M,ee),q=ce(N,M,ee),W=Oe(je(q?.elements,{isLineCompleted:d,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(W))for(let te of W)S.children.push(te);else W&&S.children.push(W)}}Xc(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let P=Le({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 we({animationInstances:P,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&x.push(...P),e},Zc=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:c,runtime:a,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:b,animations:A}=e;if(t.choice&&n){let x=Ge(b);if(!x)return e;let S=n?.layouts[t.choice.resourceId];if(S&&S.elements){let k={elements:S.elements},w=ce(k,{...Ee({variables:c,runtime:a,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:f,isChoiceVisible:u??!!t.choice,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:Re}),j=tn(Oe(je(w?.elements,{isLineCompleted:i,skipMode:f,skipTransitionsAndAnimations:s}),n));if(Array.isArray(j))for(let M of j)x.children.push(M);else j&&x.children.push(j)}let P=Le({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"});we({animationInstances:P,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&A.push(...P)}return e},el=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:c,runtime:a,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:b,animations:A}=e;if(!y?.resourceId||!n)return e;let x=Ge(b);if(!x)return e;let S=n?.layouts?.[y.resourceId];if(!S)return console.warn(`Form layout not found: ${y.resourceId}`),e;let P={id:"form-container",type:"container",x:0,y:0,children:S.elements||[]},k={...Ee({variables:c,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},w=ce(P,k,{functions:Re}),j=nn(Oe(je(rn(w,y),{isLineCompleted:i,skipMode:f,skipTransitionsAndAnimations:s}),n),y);j&&x.children.push(j);let M=Le({animationsDef:y.animations,resources:n,previousResourceId:r?.form?.resourceId,currentResourceId:y.resourceId,previousTargetId:r?.form?.resourceId?"form-container":void 0,currentTargetId:y.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return we({animationInstances:M,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(...M),e},tl=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,saveSlots:d=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=Wc(h.keyboard,h.keyup);if(g&&Object.keys(g).length>0&&(e.global.keyboard=g),!Array.isArray(h.elements)||h.elements.length===0)return e;let y=Ge(e.elements);if(!y)return e;let b={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(ti({container:b,resources:r,templateData:Ee({variables:n,runtime:o,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:c,skipTransitionsAndAnimations:p})),e},rl=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Ge(i))return e;let a=r.sounds[t.bgm.resourceId];if(!a)return e;let l=Ee({variables:o,runtime:n}).runtime;s.push({id:"bgm",type:"sound",src:a.fileId,loop:t.bgm.loop??!0,volume:jc(l,t.bgm.volume??a.volume??Jt),startDelayMs:t.bgm.startDelayMs??null})}return e},nl=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx.items;for(let[s,c]of i.entries()){let a=r.sounds?.[c.resourceId];a&&o.push({id:Fc({item:c,index:s}),type:"sound",src:a.fileId,loop:c.loop??a.loop??!1,volume:Vc(n,c.volume??a.volume??Jt),startDelayMs:c.startDelayMs??a.startDelayMs??null})}}return e},ol=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},il=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,sl=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let c=t.voice,{resourceId:a,loop:l,startDelayMs:f}=c,u=ol(r,n,a);if(!u)return e;let d=Ee({variables:i,runtime:o}).runtime;return s.push({id:`voice-${n}-${a}`,type:"sound",src:u.fileId,volume:il(c,d),loop:l??!1,startDelayMs:f??null}),e},al=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,saveSlots:d=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:b}=e;if(t.layout){let P=Ge(y);if(!P)return e;let k=n.layouts[t.layout.resourceId];if(!k)return e;Array.isArray(k.transitions)&&!p&&!h&&an({animations:b,transitions:k.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let w={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:k.elements||[]};P.children.push(ti({container:w,resources:n,templateData:Ee({variables:o,runtime:i,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:c,skipTransitionsAndAnimations:h}))}let A=r?.layout?.resourceId,x=t.layout?.resourceId,S=Le({animationsDef:t.layout?.animations,resources:n,previousResourceId:A,currentResourceId:x,previousTargetId:A?`layout-${A}`:void 0,currentTargetId:x?`layout-${x}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return we({animationInstances:S,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(...S),e},cl=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=t?.screen?.animations;if(!a)return e;let l=r!=null,f=Le({animationsDef:a,resources:n,previousResourceId:l?"story":void 0,currentResourceId:"story",previousTargetId:l?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return we({animationInstances:f,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...f),e},ll=(e,{presentationState:t})=>{let r=Ge(e.elements);return!r||!t?.screen||Object.assign(r,Jo(t.screen)),e},ul=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:f,overlayStack:u=[],dialogueHistory:d=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;return u&&u.length>0&&u.forEach((x,S)=>{let P=r.layouts[x.resourceId];if(!P){console.warn(`Overlay layout not found: ${x.resourceId}`);return}Array.isArray(P.transitions)&&(y||an({animations:A,transitions:P.transitions,defaultTargetId:`overlayStack-${S}`,idPrefix:`overlayStack-${S}`,animationPathPrefix:`overlayStack[${S}]`}));let k={id:`overlayStack-${S}`,type:"container",x:0,y:0,children:[Zo({id:`overlayStack-${S}-blocker`,screen:h}),...P.elements||[]]},w=ei(d,r.characters,n),j=Ee({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:f,historyDialogue:w,characters:r.characters||{},skipTransitionsAndAnimations:y}),M=ce(k,j,{functions:Re}),[ee,...N]=M.children||[],q=Oe(je({...M,children:N},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...q,children:ee?[ee,...q.children||[]]:q.children})}),e},fl=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,confirmDialog:d,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;if(!d?.resourceId)return e;let x=r.layouts?.[d.resourceId];if(!x)return console.warn(`ConfirmDialog layout not found: ${d.resourceId}`),e;Array.isArray(x.transitions)&&!y&&an({animations:A,transitions:x.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let S={id:"confirmDialog",type:"container",x:0,y:0,children:[Zo({id:"confirmDialog-blocker",screen:h}),...x.elements||[]]},P=ei(p,r.characters,n),k=ce(S,Ee({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,confirmDialog:d,historyDialogue:P,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:Re}),[w,...j]=k.children||[],M=Oe(je({...k,children:j},{isLineCompleted:g,skipMode:c,skipTransitionsAndAnimations:y}),r);return b.push({...M,children:w?[w,...M.children||[]]:M.children}),e},wt=e=>(t,r)=>Jc(t,{...r,visualLayer:e}),dl=wt(_e.BEHIND_BACKGROUND),pl=wt(_e.BEHIND_CHARACTER),hl=wt(_e.BEHIND_DIALOGUE),ml=wt(_e.BEHIND_CHOICE),gl=wt(_e.FOREGROUND),ni=e=>jt(Hc,[tl,dl,Yc,pl,Gc,hl,Qc,ml,Zc,el,al,gl,ll,cl,rl,nl,sl,ul,fl])(e);function oi(e,t=""){let r=[],n=e.length,o=0,i=0,s=-1,c=()=>{let a=0,l=0,f;do f=parseInt(e[o++],36),a+=(f&15)<<l,l+=4;while(f&16);return a};for(;o<n;){let a=s+1+c();s=a+c(),r.push([a,s,t?parseInt(t[i++],36):0])}return r}function ii(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 si="090001000h1v5g2903000hl2v6jh16ng1s210111110o35aa10u2k1g10l6600152113h2010u1q1r5aq3890o13181214r22k3158q2n1000v100h1k20000001207030001160721k171001h1j11610332010010321210090411021c1c02100o301201412230u1130b100h1j116111420120411001100k11l10051001h1j11611142011000321210072411021d0g10r3000000132120090o200200g1j11f2012031213711271t1001o301001000001121371b1f0c101h1l2011001031212000080a1t1001m40400102101600i11t301006c7i601008b6p41r10101041h3d0004115a1j290p3q223000511010100g1501010302003172030c0010016000e0i6v50n40n5tl12ir33s12t11u11cj30100060700010a90t220000l71i20m7203010241000502rd101004k300000006101027050920g3t22bk1300616g209030207u18c1000t10003010501b2o20000102000004g37070101o921c000640602001mcv3rg20000001o16d0c0m1fg6g2h30m10q55f1vm11c0ma0p1a42nc0ne1a090q3314902021204020112030318250105bb1201110i1021i15101131502141b15120511011k1155132040202510201010603060a1f02040104210b1g3290e0e0kn11vs12j11j3040pp12t80g6v1vmo7319g21g51gh103040n11010040j51i3f01q1h1d0m27p1a0000cs13200523j200010301010100v140018a4q2501010101c08000i1f12601011g3012215110u1a0001015000pcq181000100011000iji5fvc0u91g5bhg20ie0l94lo6002115303121s12240la1tj23h44tj11t45m4ah33q700000l3ep2021a200t220301012040a0i320j2040007f00100r20c100g3208000011531000s520201036020t900207l1101n311000000321210090a12634b910201l22001051020120011020000e1i520701020000n10h5001050000010000010001re0010323010001r11i520701000001q6000000107l600000230004gg12080001lc62027111n1000411230000000000t820321030030r10090n205001380800501020n2050c0001mc00002000000nc006150000i5l1100600010001q753011160000i441111000000rl11019100000c1h201043102n10ltk1f006eoss2b0202gs94r36si2033ku101m373h50b1rqs4113sli1t22m1uh2435070726u13k92rr7m34h380e0m141egl561g1261114k60ga6nn10t33sv13uf1jf0207150qt16t66pr60n23k6bf1f0e1l29g71c1e029j1n30p11ea0k1028139m16rb2v621122i52213040tf1u3b51n17127c0232041d120819052c28220104060306l5g3l4572g130152cqdl2c3o37a5o27u11c32d9m2cu2191obo57eh9gg1tv3",ai="262122424333333393233393339333333333393393bf3b3b3b3b3f3f3bffff33b3bb33ff3f33b3b3333333bffff3b33bb33f33bffff33b3bb33ff3f33b3bbb333b3ff33b333f33b3b3b3b3333b3bf33b3bb39333b33b33b3b3b333b333333b3b33333f3b33b3ffb3f3fff3f3b33f35dc33333f3b3b3b33323333b3bb3b33b3fb3b3333b33333bff3b3f33bfb3b3ff3b3b3b3b3b333b333b3323e22442344444444444444444444444444444444444444444444444444444444444444444444444444444443333333333b3b3bb33333b353bff3b3b3b3f3ff3b3b333bfff3f33333fb3bb3fb3b3bb33232333f333fff333333333b3b3333bb3b39393f3b3fbf33bb3b393b3b3b3333b33b33b3bbb33b33ffff3b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b3fffff3bb39b9b3b33b3bf3f3b33f3b3f93b33b3b3bb33b33b3b3b3333393b3b3b33b39bffb3b332333b333dd3b3333233332333333333333333333333333333444444444444a4444444444444344444444444444444444444444444444444444444444",ci="0001000000010010000000100000000000000000000000000001000000010014000100000001001000010101100101100000000000000000000100000001111000010000000110101001110111111111000100000021001000010000000100100001000000011010000100000001111000013000000100140001000000010010";var li=65535,dn=40960,Xt=126976,di=new Uint8Array(12288),pi=new Uint8Array(3072),hi=new Uint8Array(2816),mi,gi;{let e=(o,i,s,c,a)=>{let l=i+o.length-1;for(let f=s<i?i:s,u=c>l?l:c;f<=u;f++)o[f-i]=a},t=new Uint32Array(320),r=new Uint32Array(320),n=0;for(let[o,i,s]of oi(si,ai))e(di,0,o,i,s),e(pi,dn,o,i,s),e(hi,Xt,o,i,s),i>=65040&&!(o>=Xt&&i<=129791)&&(t[n]=o,r[n++]=i<<5|s);mi=t.slice(0,n),gi=r.slice(0,n)}function ui(e){return e<12288?di[e]:e<dn?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?pi[e-dn]: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>=Xt&&e<129792?hi[e-Xt]:e>=917504?e>921599?0:e>=917536&&e<917632||e>=917760&&e<918e3?3:2:ii(e,mi,gi)}var yi=Uint8Array.from(ci,Number);function yl(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 fi(e,t,r){switch(t){case 3:return e&24?r===8204?e&6:(e&24)===16||yl(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*bi(e){let t=e.length;if(t===0)return;let r=e.codePointAt(0),n=r>li?2:1,o=ui(r),i=50200>>o&1?fi(0,o,r):0,s=0,c=r,a=o;for(;n<t;){r=e.codePointAt(n);let l=r>li?2:1,f=ui(r),u=yi[o<<4|f],d;u===0?d=!0:u===1?d=!1:u===2?d=!(i&1):u===3?d=!(i&4):d=(i&24)!==16,i=50200>>f&1&&(i!==0||f!==3)?fi(i,f,r):0,d&&(yield{segment:e.slice(s,n),index:s,input:e,_hd:c,_catBegin:a===15?0:a,_catEnd:o===15?0:o},s=n,c=r,a=f),n+=l,o=f}yield{segment:e.slice(s),index:s,input:e,_hd:c,_catBegin:a===15?0:a,_catEnd:o===15?0:o}}function*Ii(e){for(let t of bi(e))yield t.segment}{let e=bi("_");yi._keep=[e,e.next()]}var Ai=1e3,bl=1,Il=60,Al=3,wl=.5,El=2e4,xl=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,vl=/^\s+$/u,wi,Cl=e=>{let t=`${e??""}`.normalize("NFC"),r=globalThis.Intl?.Segmenter;return typeof r!="function"?Array.from(Ii(t)):(wi??=new r(void 0,{granularity:"grapheme"}),Array.from(wi.segment(t),({segment:n})=>n))},Sl=e=>Cl(e).reduce((t,r)=>vl.test(r)?t+wl:xl.test(r)?t+Al:t+1,0),Ei=({text:e="",baseDelay:t=Ai,speed:r=bl}={})=>{let n=Number.isFinite(t)?Math.max(0,t):Ai,o=Number.isFinite(r)&&r>0?r:1,i=Sl(e)*Il/o,s=Math.max(n,El);return Math.min(n+i,s)};var Qt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},_i=1,rr="choice",Zt="form",nr=()=>({manual:{...Qt.manual},auto:{...Qt.auto},applyMode:Qt.applyMode}),pn=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...nr()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},D=e=>{let t=de(e)?ze(e):e;return structuredClone(t)},T=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),or=e=>String(e),Ri=()=>({sections:[],resources:[]}),_l=e=>T(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Ri(),Rl=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Ol=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:Rl(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),Ll=()=>({resourceId:void 0}),$l=e=>{if(!T(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},hn=(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}},Oi=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 c=r.get(s);if(c!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${c}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},Li=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},$i=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==_i)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},kl=(e,t={})=>{let r;try{r=$i(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:Li(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},Tl=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,kl(t,r)])),ki=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>_f(r));return t.length>0?t:void 0},Dl=e=>{!T(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!T(t))return;let r=ki(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},xi=(e,t,r,n="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!T(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}},Pl=(e,t="viewedRegistry")=>{if(e===void 0)return Ri();if(!T(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=xi(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=xi(o,"resources",i,t);return[s.resourceId,s]})))}},Ti=(e,t,r)=>{if(!T(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}=hn(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}},Nl=(e,t,r)=>{if(!T(e)||!Array.isArray(e.timeline))return Et({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((c,a)=>{if(!T(c))return[];try{let l=Ti(c,r,`rollback.timeline[${a}]`),f=tr({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:c.rollbackPolicy}),u=ki(D(c.executedActions));return u&&(f.executedActions=u),[f]}catch{return[]}});if(n.length===0)return Et({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):n.length-1;(o<0||o>=n.length)&&(o=n.length-1);let i=n[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let c=n.findLastIndex(a=>a.sectionId===t.sectionId&&a.lineId===t.lineId);c>=0?o=c:(n.push(tr({sectionId:t.sectionId,lineId:t.lineId})),o=n.length-1)}let s=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),o):0;return{currentIndex:o,isRestoring:!1,replayStartIndex:s,timeline:n}},Vl=(e,t,r)=>{if(!T(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=yn(t),o=Ti(e.pointers?.read,t,`contexts[${r}].pointers.read`);if(e.variables!==void 0&&!T(e.variables))throw new Error(`Malformed save slot contexts[${r}].variables entry.`);if(e.runtime!==void 0&&!T(e.runtime))throw new Error(`Malformed save slot contexts[${r}].runtime entry.`);let i=e.variables?tt(D(e.variables),t.resources?.variables??{}):{},s=Jl({loadedContextRuntime:T(e.runtime)?D(e.runtime):{}}),c={currentPointerMode:"read",pointers:{read:o},configuration:T(e.configuration)?D(e.configuration):{},views:Array.isArray(e.views)?D(e.views):[],bgm:T(e.bgm)?D(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:Nl(e.rollback,o,t)};return s&&(c.runtime=s),c},jl=(e,t)=>{if(!T(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)=>Vl(r,t,n))}},Fl=(e,t)=>{if(!T(e))throw new Error("Malformed save slot.");let r=$i(e.formatVersion);return{...e,formatVersion:r,state:jl(e.state,t)}},vi=(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},Ml=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:vi(e.confirmActions,"confirmActions",{required:!0}),cancelActions:vi(e.cancelActions,"cancelActions")}},st=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Ul=e=>(T(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),at=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},Di=e=>{if(!(!T(e)||!e.animations))return{animations:D(e.animations)}},Bl=(e,t)=>{let r=Di(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},zl=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},ql=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},er=e=>String(e??""),Pi=(e,t)=>{let r=er(t);return e?.trim===!0?r.trim():r},Wl=e=>T(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>T(t)).map(([t,r])=>[t,{id:t,...D(r)}])):{},Hl=(e,t)=>{if(!t||!T(e.global.formDrafts))return;let r=e.global.formDrafts[t];return T(r)?r:void 0},Ni=(e,t)=>{let r=Ul(e);T(r[t])||(r[t]={values:{},touched:{},errors:{},submitted:!1});let n=r[t];return T(n.values)||(n.values={}),T(n.touched)||(n.touched={}),T(n.errors)||(n.errors={}),typeof n.submitted!="boolean"&&(n.submitted=!1),n},mn=(e,t)=>{let r=Pi(e,t);return e?.required===!0&&r.length===0?"required":null},Yl=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=le({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:We(n.slice(0,o+1).map(i=>i.actions||{}))},Gl=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=zl(t),o=ql(r,n);if(!n||!o)return null;let i=Hl(e,o),s=Wl(t),c=sr({state:e}),a={},l=[],f={},u=!0;return Object.entries(s).forEach(([d,p])=>{let h=er(c?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},d)?er(i.values[d]):h,y=i?.touched?.[d]===!0,b=mn(p,g),A=i?.submitted||y?b:null,x=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,S={id:d,variableId:p.variableId,value:g,initialValue:h,valid:!b,error:A,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...x!==void 0?{maxLength:x}:{}};b&&(u=!1),a[d]=S,l.push(S),f[d]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:u,submitted:i?.submitted===!0,fields:a,fieldList:l,values:f,submitActions:{submitForm:{formKey:o,actions:D(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:D(t.cancelActions??{})}}}},Ke=[],Ci="line",gn="interaction",tr=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),yn=e=>{let{contextVariableDefaultValues:t}=Mt(e??{});return D(t)},Vi=()=>({...D(yt)}),ji=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:D(r),hasLoadedValues:!1};if(!T(e))throw new Error(`Malformed ${n}.`);let o=D(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Fi(s,D(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Kl=({loadedGlobalRuntime:e={}})=>ji({loadedRuntime:e,runtimeIds:Ur,defaults:Pe,path:"global.runtime"}).runtimeState,Jl=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=ji({loadedRuntime:e,runtimeIds:Br,defaults:Vi(),path:"context.runtime"});return r?t:void 0},ir=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Xl=e=>e.runtime?(Br.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=D(yt[t]))}),e.runtime):(e.runtime=Vi(),e.runtime),Ql=e=>So(e.global),Zl=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Ql(e)}})},eu=e=>Co[e],tu=(e,t)=>{let r=eu(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}"`)},Fi=(e,t)=>{if(tu(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},Mi=(e,t,r)=>{let n=Fi(t,r);if(t in yt){let o=ir(e);if(!o)return n;let i=Xl(o);return i[t]=n,n}return e.global[t]=n,n},Ui=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:D(e)},configuration:{},views:[],bgm:Ll(),variables:yn(t),rollback:Et({pointer:e})}),ct=e=>e?(e.currentPointerMode="read",T(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,ru=(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=Ui({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,nu(e,{queueRender:t}),o},nu=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,st(e),at(e),e.global.nextLineConfig=nr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},Bi=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},Et=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[tr({sectionId:e.sectionId,lineId:e.lineId})]:[]}},Qe=(e,t={})=>{if(e?.rollback)return Bi(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=Et({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},bn=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=Qe(r);if(n.isRestoring)return;n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1));let o=n.timeline[n.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){n.currentIndex=n.timeline.length-1;return}n.timeline.push(tr(t)),n.currentIndex=n.timeline.length-1},ou=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=Ke[Ke.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)},iu=({state:e},t={})=>{let r=t?.source===Ci?Ci:gn,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?(Ke.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Ke.push({checkpointIndex:o.currentIndex,source:r}),e)},su=({state:e})=>(Ke.pop(),e),Se=(e,t,r)=>{let o=Ke[Ke.length-1]?.source??gn;if(!Rf(t,o))return;let i=ou(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:D(r)}))},Si=(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:c}of n){let a=e.projectData.resources?.variables?.[o],l=a?.scope,f=a?.type;if(De(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Ut(l,o),Bt(f,i,o),Nr(f,i,s,o,{roundTo:c}),l==="context"&&(r.variables[o]=zt(r.variables[o],i,s,{roundTo:c}))}},au=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{Of(e,r,n)})},cu=(e,t)=>{let{sectionId:r,lineId:n}=t,s=le({state:e},{sectionId:r})?.lines?.find(c=>c.id===n)?.actions;s&&Object.entries(s).forEach(([c,a])=>{is(e,c,a)})},zi=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=Qe(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&ur({state:e}),e.global.skipMode&&Je({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=yn(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=D(Qt),e.global.overlayStack=[],st(e),at(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let c=i;c<=t;c++)c>i&&pn(e),cu(e,n.timeline[c]),au(e,n.timeline[c]);let s=ct(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(c=>c?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},lu=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;Oi(t);let c=t.story.initialSceneId,a=t.story.scenes[c],l=a.initialSectionId,f=a.sections[l],u={sceneId:c,sectionId:l,lineId:f.initialLineId??f.lines[0].id},{globalVariablesDefaultValues:d}=Mt(t),p={...d,...tt(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:Pl(s,"accountViewedRegistry"),nextLineConfig:nr(),saveSlots:Tl(n),overlayStack:[],variables:p,...Kl({loadedGlobalRuntime:i})},contexts:[Ui({pointer:u,projectData:t})]}},uu=({state:e})=>e.global.overlayStack||[],fu=({state:e})=>e.global.pendingEffects,qi=({state:e})=>e.global.skipMode,du=({state:e})=>e.global.autoMode,Wi=({state:e})=>e.global.dialogueUIHidden,Hi=({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=le({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),c=i.lines.slice(0,s+1),a=[],l={},f=mt({variables:{...e.global?.variables??{},...ir(e)?.variables??{}},runtime:He(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let u of c){let d=u.actions||{};if(l=We([l,d]),!d.dialogue)continue;let p=l.dialogue||{},h=Ft({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:f}),g=Ol({sectionId:n,lineId:u.id,content:d.dialogue.append===!0?p.content:d.dialogue.content,dialogueState:p,characterName:h});if(d.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},pu=({state:e})=>e.global.confirmDialog??null,xt=({state:e},{pointer:t}={})=>{let r=t??ye({state:e})?.pointer,n=Yl({state:e,pointer:r});return Gl({state:e,form:n.form,pointer:r})},hu=({state:e},{pointer:t}={})=>!!xt({state:e},{pointer:t}),be=({state:e},{pointer:t}={})=>{let r=xt({state:e},{pointer:t});if(r)return{source:Zt,formId:r.id,formKey:r.key};let n=Yi({state:e,pointer:t});return n?{source:rr,resourceId:n}:null},mu=({state:e,registry:t},r)=>{let{sectionId:n,lineId:o}=r,s=(Array.isArray(t?.sections)?t.sections:[]).find(f=>f.sectionId===n);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let c=le({state:e},{sectionId:n});if(!c||!c.lines||!Array.isArray(c.lines))return s.lastLineId===o;let a=c.lines.findIndex(f=>f.id===s.lastLineId),l=c.lines.findIndex(f=>f.id===o);return a===-1||l===-1?s.lastLineId===o:l<=a},gu=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},In=({state:e},t)=>mu({state:e,registry:e.global.accountViewedRegistry},t),yu=({state:e},t)=>gu({registry:e.global.accountViewedRegistry},t),bu=({state:e})=>e.global.nextLineConfig,Yi=({state:e,pointer:t}={})=>{let r=t??ye({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=le({state:e},{sectionId:n})?.lines||[],c=s.findIndex(l=>l.id===o);if(c<0)return;let a;for(let l of s.slice(0,c+1)){let f=l?.actions;if(f?.cleanAll&&(a=void 0),!f||!Object.prototype.hasOwnProperty.call(f,"choice")){a=void 0;continue}let u=f.choice;if(u?.resourceId){a=u.resourceId;continue}u?.animations||(a=void 0)}return a},Gi=({state:e})=>!!Yi({state:e}),Iu=({state:e})=>structuredClone(e),Ki=({state:e})=>e.global.saveSlots,Au=({state:e},t)=>{let r=t?.slotId,n=or(r);return e.global.saveSlots[n]},An=({state:e})=>He(e),wu=({state:e},t)=>Ne(e,t?.runtimeId),sr=({state:e})=>{let t={...e.global?.variables??{},...ir(e)?.variables??{}};return mt({variables:t,runtime:He(e),variableConfigs:e.projectData.resources?.variables??{}})},ye=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},le=({state:e},t)=>{let{sectionId:r}=t;return hn(e.projectData,r).section},ar=({state:e})=>{let t=ye({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=le({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},Ji=({state:e})=>{let{sectionId:t,lineId:r}=ye({state:e}).pointer,o=le({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===r),c=o.slice(0,i+1).map(l=>{let f=l.actions||{},u={};return Object.keys(f).forEach(d=>{u[d]=f[d]}),u});return We(c)},Eu=e=>{let t=ar({state:e})?.actions?.dialogue;if(t?.clear===!0||!Array.isArray(t?.content))return"";let r=sr({state:e});return t.content.map(n=>`${rt(n?.text,{variables:r})??""}`).join("")},cr=({state:e})=>Ei({text:Eu(e),baseDelay:Ne(e,"autoForwardDelay"),speed:Ne(e,"autoForwardSpeed")}),xu=({state:e})=>{let t=Xi({state:e}),n=ar({state:e})?.actions??{},o=We([t??{},n]);return Vr(t??{},o??{})},vu=({state:e},{sectionId:t})=>{let r=le({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},c=We([o,s]),a=Vr(o,c);n.push({id:i.id,changes:a,presentationState:c}),o=jr(c)}return n},Cu=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=vu({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},Xi=({state:e})=>{let{sectionId:t,lineId:r}=ye({state:e}).pointer,o=le({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===r);if(i<=0)return null;let c=o.slice(0,i).map(a=>{let l=a.actions||{},f={};return Object.keys(l).forEach(u=>{f[u]=l[u]}),f});return jr(We(c))},wn=({state:e},{slotsPerPage:t=6}={})=>{let o=((An({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let c=o+s,a=e.global.saveSlots&&e.global.saveSlots[or(c)]||{};i.push({...a,slotId:c})}return{saveSlots:i}},Su=Ki,_u=wn,Ru=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},Ou=({state:e},t={})=>{let r=Ji({state:e}),n=Xi({state:e}),o=ar({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:D(i)}:o,c=i?.animations&&n===null?{}:n,{sectionId:a}=ye({state:e}).pointer,{sceneId:l}=hn(e.projectData,a),f=An({state:e}),u=t?.activePersistentAnimations??[],d=t?.restoredPersistentAnimations??[],p=xt({state:e}),h=Gi({state:e}),g=sr({state:e}),{saveSlots:y}=wn({state:e}),b=Ru(e);return ni({presentationState:r,previousPresentationState:c,currentLineActions:s,resources:e.projectData.resources,currentSceneId:l,screen:e.projectData.screen,dialogueUIHidden:f.dialogueUIHidden,autoMode:f.autoMode,skipMode:f.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:as({state:e}),skipOnlyViewedLines:!f.skipUnseenText,isLineCompleted:f.isLineCompleted,skipTransitionsAndAnimations:!!f.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:Hi({state:e}),saveSlots:y,variables:g,runtime:f,activePersistentAnimations:u,restoredPersistentAnimations:d})},Lu=({state:e},t)=>(e.global.confirmDialog=Ml(t),e.global.pendingEffects.push({name:"render"}),e),$u=({state:e})=>(e.global.confirmDialog&&(st(e),e.global.pendingEffects.push({name:"render"})),e),ku=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Se(e,"pushOverlay",t),e),Tu=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Se(e,"popOverlay",void 0),e),Du=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),Se(e,"replaceLastOverlay",t),e),Pu=({state:e})=>(e.global.overlayStack=[],st(e),at(e),e.global.pendingEffects.push({name:"render"}),Se(e,"clearOverlays",void 0),e),Nu=e=>{e.global.autoMode&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.skipMode&&e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},lr=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,Bl(e,r),at(e);let n=be({state:e},{pointer:t}),o=n?.source===rr,i=n?.source===Zt;return n&&Nu(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},En=(e,t,r)=>{t?.source!==rr||r||!e.global.skipMode||e.global.pendingEffects.push({name:"startSkipNextTimer"})},Qi=({state:e})=>(be({state:e})||(e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.autoMode=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.isLineCompleted&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:cr({state:e})}}),e.global.pendingEffects.push({name:"render"})),e),ur=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Vu=({state:e})=>{let t=e.global.autoMode;return be({state:e})&&!t||(t?ur({state:e}):Qi({state:e})),e},Zi=({state:e})=>(be({state:e})||(e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode=!0,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"startSkipNextTimer"}),e.global.pendingEffects.push({name:"render"})),e),Je=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),ju=({state:e})=>{let t=qi({state:e});return be({state:e})&&!t||(t?Je({state:e}):Zi({state:e})),e},fr=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Se(e,"showDialogueUI",void 0),e),es=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Se(e,"hideDialogueUI",void 0),e),Fu=({state:e})=>(Wi({state:e})?fr({state:e}):es({state:e}),e),Fe=(e,t,r)=>(Mi(e,t,r),Zl(e),e.global.pendingEffects.push({name:"render"}),e),vt=(e,t,r,n)=>{let o=Mi(e,t,r);return e.global.pendingEffects.push({name:"render"}),Se(e,n,{value:o}),e},Mu=({state:e},t)=>Fe(e,"dialogueTextSpeed",t?.value),Uu=({state:e},t)=>Fe(e,"autoForwardDelay",t?.value),Bu=({state:e},t)=>Fe(e,"autoForwardSpeed",t?.value),zu=({state:e},t)=>Fe(e,"skipUnseenText",t?.value),qu=({state:e},t)=>Fe(e,"skipTransitionsAndAnimations",t?.value),Wu=({state:e},t)=>Fe(e,"soundVolume",t?.value),Hu=({state:e},t)=>Fe(e,"musicVolume",t?.value),Yu=({state:e},t)=>Fe(e,"muteAll",t?.value),Gu=({state:e},t)=>vt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),Ku=({state:e})=>{let t=Ne(e,"saveLoadPagination")+1;return vt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},Ju=({state:e})=>{let t=Ne(e,"saveLoadPagination")-1;return vt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},Xu=({state:e},t)=>vt(e,"menuPage",t?.value,"setMenuPage"),Qu=({state:e},t)=>vt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Zu=({state:e})=>(e.global.pendingEffects=[],e),ef=({state:e},t)=>(e.global.pendingEffects.push(t),e),ts=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!Di(n),i=le({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&&!ru(e,{queueRender:!o}))return e;let c=be({state:e});r&&e.global.skipMode&&Je({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let f=ct(a),u=f.read;r||Xe(e,{sectionId:u?.sectionId,lineId:u?.lineId}),a.rollback||Qe(a,{compatibilityAnchor:!0}),f.read={sectionId:t,lineId:s.id},r?a.rollback=Et({pointer:f.read}):bn(e,{sectionId:t,lineId:s.id})}let{activeInteraction:l}=lr(e,a?.pointers?.read,{screenTransition:n});return En(e,c,l),!r&&e.global.autoMode&&!c&&!l&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e},tf=({state:e},t)=>ts(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),rs=e=>(e.global.accountViewedRegistry=_l(e.global.accountViewedRegistry),e.global.accountViewedRegistry),xn=(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)}))}})},ns=(e,t)=>{xn(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:[]}}])},rf=(e,t,{sectionId:r,lineId:n})=>{if(!r||!n)return!1;let o=T(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=le({state:e},{sectionId:r});if(s?.lines){let c=s.lines.findIndex(l=>l.id===i.lastLineId),a=s.lines.findIndex(l=>l.id===n);if(c===-1||a>c)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},Xe=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;rf(e,rs(e),t)&&ns(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},nf=({state:e},t)=>(Xe(e,t),e.global.pendingEffects.push({name:"render"}),e),of=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=rs(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),ns(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},os=({state:e},t)=>{let r=$l(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,c=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,l=be({state:e});return!c&&!l&&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}}):!c&&a===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),Se(e,"setNextLineConfig",t),e},sf=({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=or(r),s=D(e.contexts);s?.forEach(l=>{ct(l),Bi(l.rollback),Dl(l.rollback)});let c={contexts:s},a={formatVersion:_i,slotId:Li(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:c};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},af=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=or(r),o=e.global.saveSlots[n];if(o){let i=Fl(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=nr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,st(e),at(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},cf=({state:e},t)=>{let{projectData:r}=t;Oi(r),e.projectData=r;let n=r?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=Mt(r??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...tt(e.global.variables,n)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...tt(s.variables,n)})}),st(e),at(e),e.global.pendingEffects.push({name:"render"}),e},lf=({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&&!le({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=le({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(u=>u.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let a=be({state:e}),l=ct(o);l.read={sectionId:i,lineId:n};let{activeInteraction:f}=lr(e,l.read);return En(e,a,f),e},uf=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return fr({state:e}),e;let r=be({state:e});if(r?.source===rr&&t?.bypassChoice!==!0||r?.source===Zt&&t?._interactionSource!==Zt)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let f=ye({state:e})?.pointer,u=f?.sectionId,d=f?.lineId;u&&d&&Xe(e,{sectionId:u,lineId:d}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&!r&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:cr({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=ye({state:e})?.pointer,o=n?.sectionId,i=le({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],c=i?.lines||[],l=c.findIndex(f=>f.id===n?.lineId)+1;if(l<c.length){let f=c[l],u=!Ne(e,"skipUnseenText");if(e.global.skipMode&&u&&!In({state:e},{sectionId:o,lineId:f.id}))return Je({state:e}),e;if(s&&!s.rollback&&Qe(s,{compatibilityAnchor:!0}),s){let h=ct(s),g=h.read?.lineId;g&&o&&Xe(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:f.id}}bn(e,{sectionId:o,lineId:f.id}),pn(e);let{activeInteraction:d}=lr(e,{sectionId:o,lineId:f.id});En(e,r,d);let p=e.global.nextLineConfig;p?.auto?.enabled&&!d&&p.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}})}else e.global.autoMode&&ur({state:e}),e.global.skipMode&&Je({state:e});return e},ff=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=be({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:cr({state:e})}});let r=ye({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&Xe(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},df=({state:e},t)=>ts(e,{sectionId:t?.sectionId,screen:t?.screen}),pf=({state:e})=>{if(e.global.dialogueUIHidden)return fr({state:e}),e;if(be({state:e}))return e;let t=ye({state:e})?.pointer,r=t?.sectionId,n=le({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],c=i.findIndex(a=>a.id===t?.lineId)+1;if(c<i.length){let a=i[c],l=!Ne(e,"skipUnseenText");if(e.global.skipMode&&l&&!In({state:e},{sectionId:r,lineId:a.id}))return Je({state:e}),e;if(o&&!o.rollback&&Qe(o,{compatibilityAnchor:!0}),o){let u=ct(o),d=u.read?.lineId;d&&r&&Xe(e,{sectionId:r,lineId:d}),u.read={sectionId:r,lineId:a.id}}bn(e,{sectionId:r,lineId:a.id}),pn(e);let{activeInteraction:f}=lr(e,{sectionId:r,lineId:a.id});e.global.nextLineConfig.auto?.enabled&&!f&&e.global.nextLineConfig.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})}else e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},vn=(e,t={})=>{let r=xt({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},hf=(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(De(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return Ut(n,t.variableId),Bt(o,"set",t.variableId),{variableConfig:r,scope:n}},mf=(e,t)=>({id:e.id,key:e.key,valid:!0,values:D(t),fields:D(e.fields),fieldList:D(e.fieldList)}),gf=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=ye({state:e})?.pointer,r=t?.sectionId,n=t?.lineId;r&&n&&Xe(e,{sectionId:r,lineId:n})},yf=({state:e},t={})=>{let r=vn(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=Ni(e,r.key),i=er(t.value),s=r.fields[n],c=mn(s,i);return o.values[n]=i,o.touched[n]=!0,c?o.errors[n]=c:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},bf=({state:e},t={})=>{let r=vn(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=Ni(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([u,d])=>{let p=Object.prototype.hasOwnProperty.call(n.values,u)?n.values[u]:d.value,h=mn(d,p);n.touched[u]=!0,h&&(i[u]=h),o[u]=Pi(d,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 c=!1,a=[],l=[];Object.entries(r.fields).forEach(([u,d])=>{let{scope:p}=hf(e,d),h=p==="context"?s.variables:e.global.variables,g=o[u];h[d.variableId]=zt(h[d.variableId],"set",g),p==="context"&&(c=!0,l.push({variableId:d.variableId,op:"set",value:g})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${d.variableId}`,op:"set",value:D(h[d.variableId])})}),c&&Se(e,"updateVariable",{id:"submitForm",operations:l}),xn(e,a);let f=mf(r,o);return gf(e),delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:f}},If=({state:e},t={})=>{let r=vn(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"}},Af=({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=[],c=[];return n.forEach(({variableId:a,op:l,value:f,roundTo:u})=>{let d=e.projectData.resources?.variables?.[a],p=d?.scope,h=d?.type;if(De(d))throw new Error(`Cannot update computed variable: ${a}`);if(d?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);Ut(p,a),Bt(h,l,a),Nr(h,l,f,a,{roundTo:u});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:a,op:l,value:f};u!==void 0&&(y.roundTo=u),c.push(y)}g[a]=zt(g[a],l,f,{roundTo:u}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:D(g[a])})}),i&&Se(e,"updateVariable",{id:r,operations:c}),xn(e,s),e.global.pendingEffects.push({name:"render"}),e},wf=e=>(t,r)=>e({state:t},r),Ef=e=>({variables:mt({variables:{...e.global?.variables??{},...ir(e)?.variables??{}},runtime:He(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:He(e)}),xf=e=>{if(!T(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")},vf=(e,t,r)=>{if(!T(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!T(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")},Cf=(e,t)=>{xf(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(vf(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!ht(n.when,Ef(e)))){Object.entries(n.actions).forEach(([i,s])=>{is(e,i,s)});return}}},Sf={conditional:{replayLine:Cf},updateVariable:{recordSources:[gn],replayLine:Si,replayRecorded:Si,persistInSaveSlot:!0},setNextLineConfig:{replayLine:wf(os)}},dr=e=>Sf[e]??null,_f=e=>dr(e)?.persistInSaveSlot===!0,Rf=(e,t)=>{let r=dr(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},Of=(e,t,r)=>{dr(t)?.replayRecorded?.(e,r)},is=(e,t,r)=>{dr(t)?.replayLine?.(e,r)},ss=({state:e},t)=>{let{offset:r}=t;if(r===void 0||typeof r!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let n=e.contexts[e.contexts.length-1];if(!n)return null;let o=n.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+r;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},as=({state:e})=>ss({state:e},{offset:-1})!==null,Lf=({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=Qe(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:zi(e,i)},$f=({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=Qe(o,{compatibilityAnchor:!o.rollback}),c=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===r&&a.lineId===n);if(c===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return c===i.currentIndex?e:zi(e,c)},cs=e=>{let t=lu(e);return co(t,{selectPendingEffects:fu,selectSkipMode:qi,selectAutoMode:du,selectIsChoiceVisible:Gi,selectIsFormVisible:hu,selectActiveInteraction:be,selectActiveForm:xt,selectDialogueUIHidden:Wi,selectDialogueHistory:Hi,selectConfirmDialog:pu,selectIsLineAccountViewed:In,selectIsResourceAccountViewed:yu,selectNextLineConfig:bu,selectSystemState:Iu,selectSaveSlotMap:Ki,selectSaveSlots:Su,selectSaveSlot:Au,selectRuntime:An,selectRuntimeValue:wu,selectAllVariables:sr,selectCurrentPointer:ye,selectSection:le,selectCurrentLine:ar,selectPresentationState:Ji,selectAutoForwardTimerDelay:cr,selectPresentationChanges:xu,selectSectionLineChanges:Cu,selectSaveSlotPage:wn,selectCurrentPageSlots:_u,selectRenderState:Ou,selectOverlayStack:uu,selectLineIdByOffset:ss,selectCanRollback:as,startAutoMode:Qi,stopAutoMode:ur,toggleAutoMode:Vu,startSkipMode:Zi,stopSkipMode:Je,toggleSkipMode:ju,showDialogueUI:fr,hideDialogueUI:es,toggleDialogueUI:Fu,setDialogueTextSpeed:Mu,setAutoForwardDelay:Uu,setAutoForwardSpeed:Bu,setSkipUnseenText:zu,setSkipTransitionsAndAnimations:qu,setSoundVolume:Wu,setMusicVolume:Hu,setMuteAll:Yu,setSaveLoadPagination:Gu,incrementSaveLoadPagination:Ku,decrementSaveLoadPagination:Ju,setMenuPage:Xu,setMenuEntryPoint:Qu,showConfirmDialog:Lu,hideConfirmDialog:$u,resetStoryAtSection:tf,clearPendingEffects:Zu,appendPendingEffect:ef,beginRollbackActionBatch:iu,endRollbackActionBatch:su,addViewedLine:nf,addViewedResource:of,setNextLineConfig:os,saveSlot:sf,loadSlot:af,updateProjectData:cf,sectionTransition:df,jumpToLine:lf,nextLine:uf,markLineCompleted:ff,rollbackToLine:$f,rollbackByOffset:Lf,pushOverlay:ku,popOverlay:Tu,replaceLastOverlay:Du,clearOverlays:Pu,updateFormField:yf,submitForm:bf,cancelForm:If,updateVariable:Af,nextLineFromSystem:pf},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var kf="route-engine",Tf="projectPersistence";var us=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),ne=e=>Object.prototype.toString.call(e)==="[object Object]",ls="variables.",Df=(e={})=>{let t=ne(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!ne(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)}:!ne(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Pf=(e={})=>{let t=ne(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!ne(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)}:!ne(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Nf=(e,t)=>{let r=Pf(e),n=Df(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let c=o.find(a=>a.sectionId===s.sectionId);if(!c){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(c.lastLineId!==void 0){if(s.lineId===void 0){delete c.lastLineId;return}c.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},fs=(e={})=>{let t=ne(e)?e:{};return{saveSlots:ne(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:ne(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:ne(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:ne(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:ne(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Vf=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!ne(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(ls)?t.path.slice(ls.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}].`)})},jf=(e,t)=>{let r={};return Vf(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=Nf(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},Cn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},Ff=e=>{let t=Cn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Mf=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},Uf=({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}".`))}}),Bf=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.`))}})},Ct=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let c=o.transaction(t,"readwrite"),a=c.objectStore(t),l=a.get(r),f=!1,u=p=>{f||(f=!0,s(p))},d=()=>{f||(f=!0,i())};l.onerror=()=>{u(l.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},l.onsuccess=()=>{let p=fs(l.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...us(),...p,...h},y=a.put(g);y.onerror=()=>{u(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},c.oncomplete=()=>{d()},c.onerror=()=>{u(c.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},c.onabort=()=>{u(c.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},zf=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),l=!1,f=d=>{l||(l=!0,i(d))},u=()=>{l||(l=!0,o())};a.onerror=()=>{f(a.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{u()},s.onerror=()=>{f(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{f(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},Sn=(e={})=>{let{indexedDB:t,databaseName:r=kf,objectStoreName:n=Tf,namespace:o}=e,i=Mf(t),s=Ff(o),c=Uf({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let a=await Bf({databasePromise:c,objectStoreName:n,namespace:s});return{...us(),...fs(a)}},clear:async()=>zf({databasePromise:c,objectStoreName:n,namespace:s}),saveSlots:async a=>Ct({databasePromise:c,objectStoreName:n,namespace:s,patch:{saveSlots:ne(a)?a:{}}}),saveGlobalDeviceVariables:async a=>Ct({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:ne(a)?a:{}}}),saveGlobalAccountVariables:async a=>Ct({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalAccountVariables:ne(a)?a:{}}}),saveGlobalRuntime:async a=>Ct({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalRuntime:ne(a)?a:{}}}),applyScopedDataUpdates:async a=>Ct({databasePromise:c,objectStoreName:n,namespace:s,patch:l=>jf(l,a)})}},qf=Sn;var Wf=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Hf=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),ds="conditional",_n="form",Yf=new Set(["submitForm","cancelForm"]),St=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function Rn(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:c}=e,a=(I=new Map,C=Date.now())=>new Map(Array.from(I.entries()).filter(([,R])=>C<R.expiresAt).map(([R,F])=>[R,{animation:structuredClone(F.animation),startedAt:F.startedAt,expiresAt:F.expiresAt}])),l=(I=new Map)=>Array.from(I.values()).map(C=>structuredClone(C.animation)),f=(I=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,C])=>I<C.expiresAt))},u=()=>{for(;t.selectPendingEffects().length>0;){let I=[...t.selectPendingEffects()];t.clearPendingEffects();try{c(I)}catch(C){throw t.clearPendingEffects(),I.forEach(R=>{t.appendPendingEffect(R)}),C}}},d=({initialState:I,namespace:C})=>{t=cs(I),r=0,n=Cn(C),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),u()},p=()=>n,h=()=>t.selectPresentationState(),g=()=>t.selectPresentationChanges(),y=I=>t.selectSectionLineChanges(I),b=(I={})=>{r+=1;let C=Date.now();f(C);let R=i.size>0,F=a(o,C),B=R?a(i,C):new Map,ve={...t.selectRenderState({activePersistentAnimations:l(F),restoredPersistentAnimations:l(B)}),id:`render-${r}`};return s.set(ve.id,{builtAt:C,persistentAnimationSessions:new Map([...B.entries(),...F.entries()]),usedRestoredPersistentAnimationSessions:R}),ve},A=(I={})=>b(I),x=(I={})=>b(I),S=I=>{let C=typeof I?.id=="string"&&I.id.length>0?I.id:null,R=C?s.get(C):null;C&&s.delete(C);let F=new Map;Uo(I?.animations).forEach(B=>{let he=Gt(B);if(!he)return;let ve=R?.persistentAnimationSessions?.get(he)??o.get(he),_t=Math.max(0,zo(B)),Ln=ve?.startedAt??R?.builtAt??Date.now();F.set(he,{animation:structuredClone(B),startedAt:Ln,expiresAt:Ln+_t})}),o=F,R?.usedRestoredPersistentAnimationSessions&&(i=new Map)},P=()=>t.selectSystemState(),k=()=>t.selectSaveSlotMap(),w=I=>t.selectSaveSlot(I),j=I=>t.selectSaveSlotPage(I),M=()=>t.selectSkipMode(),ee=()=>t.selectAutoMode(),N=()=>t.selectRuntime(),q=()=>t.selectIsChoiceVisible(),W=()=>t.selectIsFormVisible(),te=()=>t.selectActiveInteraction(),xe=(I,C,R={})=>!St(C)||I!=="nextLine"?C:R.bypassChoice===!0?{...C,bypassChoice:!0}:R.interactionSource===_n?{...C,_interactionSource:_n}:C,Y=(I,C)=>{if(!t[I])return;Wf.has(I)&&(Hf.has(I)?i=a(o):i=new Map,o=new Map);let R=t[I](C);return u(),R},G=(I,C,R,F={})=>{if(I===ds){let B=re(R),he=Fr({[I]:C},B);se(he[I],R,F);return}Y(I,C)},oe=(I,C)=>{G(I,C)},re=I=>{if(!I)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(I,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:C,...R}=I,F=t.selectAllVariables?t.selectAllVariables():void 0;return{...R,_event:C,variables:F,runtime:t.selectRuntime?t.selectRuntime():{}}},K=I=>{if(!St(I))throw new Error("conditional action payload must be an object");if(!Array.isArray(I.branches))throw new Error("conditional action requires branches array");if(I.branches.length===0)throw new Error("conditional action requires at least one branch")},ie=(I,C,R)=>{if(!St(I))throw new Error(`conditional branch at index ${C} must be an object`);if(!St(I.actions))throw new Error(`conditional branch at index ${C} requires actions object`);if(!Object.prototype.hasOwnProperty.call(I,"when")&&C!==R-1)throw new Error("conditional else branch must be the last branch")},se=(I,C,R)=>{K(I);for(let F=0;F<I.branches.length;F+=1){let B=I.branches[F];ie(B,F,I.branches.length);let he=re(C);if(!(Object.prototype.hasOwnProperty.call(B,"when")&&!ht(B.when,he))){J(B.actions,C,R);return}}},v=(I,C)=>({...I??{},_form:C}),_=(I,C,R,F)=>{let B=Y(I,C),he=B?.submitted===!0&&B.valid===!0,ve=B?.cancelled===!0;!he&&!ve||St(C.actions)&&J(C.actions,v(R,B.form),{...F,interactionSource:_n})},V=(I,C,R,F)=>{let B=re(R),ve=Fr({[I]:C},B)[I];if(I===ds){se(ve,R,F);return}let _t=xe(I,ve,F);if(Yf.has(I)){_(I,_t,R,F);return}Y(I,_t)},J=(I,C,R)=>{Object.entries(I).forEach(([F,B])=>{V(F,B,C,R)})},z=(I,C,R={})=>{t.beginRollbackActionBatch({source:R.rollbackSource});try{J(I,C,R)}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:G,handleInternalAction:oe,handleActions:z,selectRenderState:A,prepareRenderState:x,commitRenderState:S,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:P,selectSaveSlotMap:k,selectSaveSlot:w,selectSaveSlotPage:j,selectSaveSlots:k,selectRuntime:N,selectIsChoiceVisible:q,selectIsFormVisible:W,selectActiveInteraction:te,handleLineActions:()=>{let I=t.selectCurrentLine();return I?.actions?(z(I.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var On=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},Gf=80,hs=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},Kf=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&hs({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},Jf=({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 c=n.delay??1e3;r.getElapsed()>=c&&(t.remove(i),r.setCallback(null),r.setElapsed(0),pr(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},Xf=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Qf=({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 c=n?.delay??Gf;r.getElapsed()>=c&&(r.setElapsed(0),pr(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},Zf=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},ed=({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 c=n.delay??1e3;r.getElapsed()>=c&&(r.setElapsed(0),pr(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},td=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},rd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},nd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},od=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},id=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},sd=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},ps={render:hs,saveSlots:rd,saveGlobalDeviceVariables:nd,saveGlobalAccountVariables:od,saveGlobalRuntime:id,applyScopedDataUpdates:sd,handleLineActions:Kf,startAutoNextTimer:Jf,clearAutoNextTimer:Xf,startSkipNextTimer:Qf,clearSkipNextTimer:Zf,nextLineConfigTimer:ed,clearNextLineConfigTimer:td},ad=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),pr=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},cd=(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(!ad.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},ld=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:c})=>{let a=On(),l=On(),f=On(),u=s??null,d=Promise.resolve(),p=null,h=null,g=!1,y=0,b=v=>{if(o){o(v);return}console.error("RouteEngine persistence write failed.",v)},A=()=>{if(u)return u;let v=e();return u=Sn({indexedDB:i,namespace:c??v?.getNamespace?.()}),u},x=v=>{d=d.catch(()=>{}).then(()=>{let _=A();return v(_)}).catch(_=>{b(_)})},S=v=>{let _=typeof v?.id=="string"&&v.id.length>0?v.id:null;y+=1,p=_,g=!1},P=()=>y,k=(v={})=>{if(v?.aborted===!0)return!1;let _=typeof v?.id=="string"&&v.id.length>0?v.id:null;return _?_!==p||_===h?!1:(h=_,!0):p!==null||g?!1:(g=!0,!0)},w=(v,_={})=>{if(v!=="renderComplete"||!k(_))return!1;let V=e();return pr(V,"markLineCompleted",{}),!0},j=new Set(["updateFormField","submitForm","cancelForm"]),M=new Set(["updateVariable"]),ee=v=>typeof v?.selectActiveInteraction=="function"?v.selectActiveInteraction():typeof v?.selectIsChoiceVisible=="function"&&v.selectIsChoiceVisible()?{source:"choice"}:null,N=v=>v?._formKey??v?.formKey,q=(v,_)=>N(v)===_?.formKey,W=(v,_)=>!v||typeof v!="object"||Array.isArray(v)?!1:v._interactionSource===_?.source,te=(v,_)=>W(v,_)?_.source==="form"?q(v,_):!0:!1,xe=(v,_)=>!v||typeof v!="object"||Array.isArray(v)||_?.source!=="form"?!1:q(v,_),Y=(v={})=>Object.keys(v).some(_=>j.has(_)),G=(v={},_)=>Object.entries(v).some(([V,J])=>j.has(V)&&xe(J,_)),oe=(v={})=>Object.keys(v).length>0&&Object.keys(v).every(_=>M.has(_)),re=(v={},_)=>{let V=v?.actions;return _?.source==="form"?!V||typeof V!="object"||Array.isArray(V)?!1:G(V,_)?!0:Y(V)?!1:oe(V):te(v,_)?!0:!V||typeof V!="object"||Array.isArray(V)?!1:Object.values(V).some(J=>te(J,_))},K=(v,_={})=>{if(!_?.actions)return!1;let V=ee(v);return!V||V.source==="choice"?!1:!re(_,V)},ie=({preprocessPayload:v,onEvent:_}={})=>async(V,J={})=>{let z=e();if(K(z,J))return _?.(V,J);let X=await v?.(V,J)??J;if(K(z,X))return _?.(V,X);if(w(V,X),X?.actions){let I=X?._event?{_event:X._event}:X?.event?{_event:X.event}:void 0,C;X?.bypassChoice===!0?C={bypassChoice:!0}:X?._interactionSource&&(C={interactionSource:X._interactionSource}),C?z.handleActions(X.actions,I,C):z.handleActions(X.actions,I)}return _?.(V,X)},se=v=>{let _=e(),V=cd(v);V.forEach(z=>{if(!ps[z.name]&&!n)throw new Error(`Unhandled pending effect "${z.name}".`)});let J={engine:_,routeGraphics:t,ticker:r,autoTimer:a,skipTimer:l,nextLineConfigTimerState:f,trackRenderDispatch:S,getRenderDispatchCount:P,enqueuePersistenceWrite:x};for(let z of V){let X=ps[z.name];if(X){X(J,z.payload);continue}n(z,J)}};return se.handleRouteGraphicsEvent=w,se.createRouteGraphicsEventHandler=ie,se},ud=ld;var fd=(e,t={})=>{let{resources:r={}}=t;return un(e,r)};var Bp=Rn;export{zr as DEFAULT_VISUAL_LAYER,nt as RENDER_LAYER,_e as VISUAL_LAYER,ud as createEffectsHandler,qf as createIndexedDbPersistence,Bp as default,Ea as resolveComputedVariables,fd as resolveLayoutReferences};
|
|
1
|
+
var ws=Object.defineProperty;var Es=(e,t)=>{for(var r in t)ws(e,r,{get:t[r],enumerable:!0})};var Bn=Symbol.for("immer-nothing"),Vn=Symbol.for("immer-draftable"),fe=Symbol.for("immer-state");function Ie(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var et=Object.getPrototypeOf;function de(e){return!!e&&!!e[fe]}function Me(e){return e?zn(e)||Array.isArray(e)||!!e[Vn]||!!e.constructor?.[Vn]||Tt(e)||Nt(e):!1}var xs=Object.prototype.constructor.toString();function zn(e){if(!e||typeof e!="object")return!1;let t=et(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)===xs}function Lt(e,t){Dt(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function Dt(e){let t=e[fe];return t?t.type_:Array.isArray(e)?1:Tt(e)?2:Nt(e)?3:0}function Ir(e,t){return Dt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function qn(e,t,r){let n=Dt(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function vs(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Tt(e){return e instanceof Map}function Nt(e){return e instanceof Set}function Fe(e){return e.copy_||e.base_}function Ar(e,t){if(Tt(e))return new Map(e);if(Nt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=zn(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[fe];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],c=n[s];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(n[s]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[s]})}return Object.create(et(e),n)}else{let n=et(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function Sr(e,t=!1){return Pt(e)||de(e)||!Me(e)||(Dt(e)>1&&(e.set=e.add=e.clear=e.delete=Ss),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>Sr(n,!0))),e}function Ss(){Ie(2)}function Pt(e){return Object.isFrozen(e)}var Cs={};function Ue(e){let t=Cs[e];return t||Ie(0,e),t}var ut;function Wn(){return ut}function _s(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function jn(e,t){t&&(Ue("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function wr(e){Er(e),e.drafts_.forEach(Rs),e.drafts_=null}function Er(e){e===ut&&(ut=e.parent_)}function Fn(e){return ut=_s(ut,e)}function Rs(e){let t=e[fe];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Mn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[fe].modified_&&(wr(t),Ie(4)),Me(e)&&(e=$t(t,e),t.parent_||kt(t,e)),t.patches_&&Ue("Patches").generateReplacementPatches_(r[fe].base_,e,t.patches_,t.inversePatches_)):e=$t(t,r,[]),wr(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Bn?e:void 0}function $t(e,t,r){if(Pt(t))return t;let n=t[fe];if(!n)return Lt(t,(o,i)=>Un(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return kt(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),Lt(i,(c,a)=>Un(e,n,o,c,a,r,s)),kt(e,o,!1),r&&e.patches_&&Ue("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function Un(e,t,r,n,o,i,s){if(de(o)){let c=i&&t&&t.type_!==3&&!Ir(t.assigned_,n)?i.concat(n):void 0,a=$t(e,o,c);if(qn(r,n,a),de(a))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(Me(o)&&!Pt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;$t(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&kt(e,o)}}function kt(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Sr(t,r)}function Os(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:Wn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=Cr;r&&(o=[n],i=ft);let{revoke:s,proxy:c}=Proxy.revocable(o,i);return n.draft_=c,n.revoke_=s,c}var Cr={get(e,t){if(t===fe)return e;let r=Fe(e);if(!Ir(r,t))return Ls(e,r,t);let n=r[t];return e.finalized_||!Me(n)?n:n===yr(e.base_,t)?(br(e),e.copy_[t]=vr(n,e)):n},has(e,t){return t in Fe(e)},ownKeys(e){return Reflect.ownKeys(Fe(e))},set(e,t,r){let n=Hn(Fe(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=yr(Fe(e),t),i=o?.[fe];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(vs(r,o)&&(r!==void 0||Ir(e.base_,t)))return!0;br(e),xr(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 yr(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,br(e),xr(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Fe(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 et(e.base_)},setPrototypeOf(){Ie(12)}},ft={};Lt(Cr,(e,t)=>{ft[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ft.deleteProperty=function(e,t){return ft.set.call(this,e,t,void 0)};ft.set=function(e,t,r){return Cr.set.call(this,e[0],t,r,e[0])};function yr(e,t){let r=e[fe];return(r?Fe(r):e)[t]}function Ls(e,t,r){let n=Hn(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function Hn(e,t){if(!(t in e))return;let r=et(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=et(r)}}function xr(e){e.modified_||(e.modified_=!0,e.parent_&&xr(e.parent_))}function br(e){e.copy_||(e.copy_=Ar(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var $s=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,...l){return s.produce(a,u=>r.call(this,u,...l))}}typeof r!="function"&&Ie(6),n!==void 0&&typeof n!="function"&&Ie(7);let o;if(Me(t)){let i=Fn(this),s=vr(t,void 0),c=!0;try{o=r(s),c=!1}finally{c?wr(i):Er(i)}return jn(i,n),Mn(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===Bn&&(o=void 0),this.autoFreeze_&&Sr(o,!0),n){let i=[],s=[];Ue("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,...c)=>this.produceWithPatches(s,a=>t(a,...c));let n,o;return[this.produce(t,r,(s,c)=>{n=s,o=c}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Me(e)||Ie(8),de(e)&&(e=Be(e));let t=Fn(this),r=vr(e,void 0);return r[fe].isManual_=!0,Er(t),r}finishDraft(e,t){let r=e&&e[fe];(!r||!r.isManual_)&&Ie(9);let{scope_:n}=r;return jn(n,t),Mn(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=Ue("Patches").applyPatches_;return de(e)?n(e,t):this.produce(e,o=>n(o,t))}};function vr(e,t){let r=Tt(e)?Ue("MapSet").proxyMap_(e,t):Nt(e)?Ue("MapSet").proxySet_(e,t):Os(e,t);return(t?t.scope_:Wn()).drafts_.push(r),r}function Be(e){return de(e)||Ie(10,e),Yn(e)}function Yn(e){if(!Me(e)||Pt(e))return e;let t=e[fe],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=Ar(e,t.scope_.immer_.useStrictShallowCopy_)}else r=Ar(e,!0);return Lt(r,(n,o)=>{qn(r,n,Yn(o))}),t&&(t.finalized_=!1),r}var pe=new $s,_r=pe.produce,wd=pe.produceWithPatches.bind(pe),Ed=pe.setAutoFreeze.bind(pe),xd=pe.setUseStrictShallowCopy.bind(pe),vd=pe.applyPatches.bind(pe),Sd=pe.createDraft.bind(pe),Cd=pe.finishDraft.bind(pe);var m={LITERAL:0,VARIABLE:1,INTERPOLATION:2,FUNCTION:3,BINARY:4,UNARY:5,CONDITIONAL:6,LOOP:7,OBJECT:8,ARRAY:9,PARTIAL:10,PATH_REFERENCE:11},O={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},tt={NOT:0};var E=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 Rr=e=>{if(!e||e.trim()==="")throw new E("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new E(`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 E(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Gn=e=>{if(e.trim().endsWith(" in"))throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new E(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new E(`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 E(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new E(`Invalid loop syntax (got: '$for ${e}')`)}};var Kn=(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}'`)},Jn=(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 ks=(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=L(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},L=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return Y(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return Y(e.path,r,n);if(e.type===m.INTERPOLATION)return Ts(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return Qn(e,t,r,n);case m.BINARY:return Zn(e,t,r,n);case m.UNARY:return eo(e,t,r,n);case m.CONDITIONAL:return Ps(e,t,r,n);case m.LOOP:return Us(e,t,r,n);case m.OBJECT:return zs(e,t,r,n);case m.ARRAY:return qs(e,t,r,n);case m.PARTIAL:return Ws(e,t,r,n);case m.PATH_REFERENCE:return Hs(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Xn=new Map,Ds=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 c=s.slice(1,-1);t.push({type:"property",value:c})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},Y=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=Xn.get(e);if(!n){let i=[],s="",c=0;for(let a=0;a<e.length;a++){let l=e[a];l==="["?(c++,s+=l):l==="]"?(c--,s+=l):l==="."&&c===0?s&&(i.push(s),s=""):s+=l}s&&i.push(s),n=[];for(let a of i){let l=Ds(a.trim());n.push(...l)}Xn.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},Ts=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},Qn=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Jn(e.name,o);let s=e.args.map(c=>L(c,t,r,n));return i(...s)},$e=(e,t,r,n)=>{if(e.var&&!e.type)return Y(e.var,r,n);switch(e.type){case m.VARIABLE:return Y(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return Zn(e,t,r,n);case m.UNARY:return eo(e,t,r,n);case m.FUNCTION:return Qn(e,t,r,n);default:return L(e,t,r,n)}},Zn=(e,t,r,n)=>{if(e.op===O.AND||e.op===O.OR){let s=$e(e.left,t,r,n),c=$e(e.right,t,r,n);switch(e.op){case O.AND:return s&&c;case O.OR:return s||c}}let o=L(e.left,t,r,n),i=L(e.right,t,r,n);switch(e.op){case O.EQ:return o==i;case O.NEQ:return o!=i;case O.GT:return o>i;case O.LT:return o<i;case O.GTE:return o>=i;case O.LTE:return o<=i;case O.IN:return Array.isArray(i)?i.includes(o):!1;case O.ADD:if(typeof o!="number"||typeof i!="number")throw new ue(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case O.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}`)}},eo=(e,t,r,n)=>{let o=e.op===tt.NOT?$e(e.operand,t,r,n):L(e.operand,t,r,n);if(e.op===tt.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Ns=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(Y(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let c={};for(let a of s.properties){let l=a.parsedKey?L(a.parsedKey,t,r,n):a.key,u=a.value;if(u.type===m.LITERAL)c[l]=u.value;else if(u.type===m.VARIABLE)c[l]=Y(u.path,r,n);else if(u.type===m.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===m.VARIABLE){let p=Y(d.path,r,n);f.push(p!=null?String(p):"")}else{let p=L(d,t,r,n);f.push(p!=null?String(p):"")}c[l]=f.join("")}else c[l]=L(u,t,r,n)}return c}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let c={};for(let a of s.properties){let l=a.parsedKey?L(a.parsedKey,t,r,n):a.key,u=a.value;if(u.type===m.LITERAL)c[l]=u.value;else if(u.type===m.VARIABLE)c[l]=Y(u.path,r,n);else if(u.type===m.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===m.VARIABLE){let p=Y(d.path,r,n);f.push(p!=null?String(p):"")}else{let p=L(d,t,r,n);f.push(p!=null?String(p):"")}c[l]=f.join("")}else c[l]=L(u,t,r,n)}return c}}}return null},Ps=(e,t,r,n)=>{let o=Ns(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||$e(s,t,r,n))return L(e.bodies[i],t,r,n)}return to},Vs=(e,t)=>{let r=e.body,n=e.itemVar;if(r.type===m.CONDITIONAL&&r.conditions.length===1&&r.conditions[0].type===m.VARIABLE){let o=r.conditions[0].path,i=r.bodies[0];if(o.startsWith(n+".")){let s=o.substring(n.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let a of i.properties)if(a.parsedKey)return null;let c=[];for(let a=0;a<t.length;a++){let l=t[a];if(l[s]){let u={};for(let f of i.properties){let d=f.key,p=f.value;if(p.type===m.LITERAL)u[d]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)u[d]=l;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);u[d]=l[g]}else return null}else if(p.type===m.INTERPOLATION){let h=[],g=!0;for(let y of p.parts)if(typeof y=="string")h.push(y);else if(y.type===m.VARIABLE){let b=y.path;if(b===n)h.push(l!=null?String(l):"");else if(b.startsWith(n+".")){let A=b.substring(n.length+1),x=l[A];h.push(x!=null?String(x):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[d]=h.join("")}else return null}c.push(u)}}return c}}}return null},js=(e,t)=>{let r=e.body,n=e.itemVar,o=Vs(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let c of r.properties)if(c.parsedKey)return null;let i=[],s=!0;for(let c of r.properties){let a=c.key,l=c.value;if(l.type===m.LITERAL)i.push({key:a,type:"literal",value:l.value});else if(l.type===m.VARIABLE){let u=l.path;if(u===n)i.push({key:a,type:"item"});else if(u.startsWith(n+".")){let f=u.substring(n.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:a,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(l.type===m.INTERPOLATION&&l.parts.length===1){let u=l.parts[0];if(u.type===m.VARIABLE){let f=u.path;if(f===n)i.push({key:a,type:"item_string"});else if(f.startsWith(n+".")){let d=f.substring(n.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:a,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let c=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 l=t[a];c[a]={id:l.id,title:l.title!=null?String(l.title):"",completed:l.completed}}else for(let a=0;a<t.length;a++){let l=t[a],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=l;else if(f.type==="prop")u[f.key]=l[f.prop];else if(f.type==="item_string")u[f.key]=l!=null?String(l):"";else if(f.type==="prop_string"){let d=l[f.prop];u[f.key]=d!=null?String(d):""}c[a]=u}return c}}return null},Fs=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let c=e.itemVar,a=e.indexVar;for(let l=0;l<o.length;l++){let u=o[l],f={},d={...n,[c]:u,...a&&{[a]:l}};d.__paths__||(d.__paths__=n.__paths__||{});let p=e.iterable.path||"";if(n&&n.__paths__&&p){let h=p.split("."),g=h[0];g in n.__paths__&&(p=n.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}d.__paths__={...d.__paths__,[c]:`${p}[${l}]`,...a&&{[a]:l}};for(let h of s.properties){let g=h.parsedKey?L(h.parsedKey,t,r,d):h.key,y=h.value;if(y.type===m.LITERAL)f[g]=y.value;else if(y.type===m.VARIABLE){let b=y.path;if(b===c)f[g]=u;else if(b===a)f[g]=l;else if(b.startsWith(c+".")){let A=b.substring(c.length+1);!A.includes(".")&&!A.includes("[")?f[g]=u[A]:f[g]=Y(b,r,{...n,[c]:u,...a&&{[a]:l}})}else f[g]=Y(b,r,{...n,[c]:u,...a&&{[a]:l}})}else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let x=A.path,C;if(x===c)C=u;else if(x===a)C=l;else if(x.startsWith(c+".")){let N=x.substring(c.length+1);!N.includes(".")&&!N.includes("[")?C=u[N]:C=Y(x,r,{...n,[c]:u,...a&&{[a]:l}})}else C=Y(x,r,{...n,[c]:u,...a&&{[a]:l}});b.push(C!=null?String(C):"")}else{let x={...n,[c]:u,...a&&{[a]:l}},C=L(A,t,r,x);b.push(C!=null?String(C):"")}f[g]=b.join("")}else{let b={...n,[c]:u,...a&&{[a]:l}};f[g]=L(y,t,r,b)}}i.push(f)}return i}return null},Ms=(e,t,r)=>{let n=e.body;if(n.type===m.OBJECT&&n.properties.length===1&&n.properties[0].key==="$if item.visible"){let i=n.properties[0].value;if(i.type===m.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===m.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===m.OBJECT&&s.properties.length===2){let c=s.properties[0],a=s.properties[1];if(c.key==="id"&&c.value.type===m.VARIABLE&&c.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===m.CONDITIONAL){let l=[];for(let u=0;u<t.length;u++){let f=t[u];if(f.visible){let d={id:f.id};f.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${f.name}`):(d.highlight=!1,d.message=f.name),l.push(d)}}return l}}}}return null},Us=(e,t,r,n)=>{let o=L(e.iterable,t,r,n);if(!Array.isArray(o)){let l,u=!1;if(e.iterable.type===m.FUNCTION){u=!0;let d=e.iterable.args.map(p=>p.type===m.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===m.VARIABLE?p.path:p.type===m.FUNCTION?`${p.name}(...)`:"?").join(", ");l=`${e.iterable.name}(${d})`}else l=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw Kn(f,o,u)}if(!e.indexVar){let l=Ms(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=js(e,o);if(l!==null)return l}let i=Fs(e,t,r,n,o);if(i!==null)return i;let s=[],c=e.iterable.path||"";if(n&&n.__paths__&&c){let l=c.split("."),u=l[0];u in n.__paths__&&(c=n.__paths__[u],l.length>1&&(c+="."+l.slice(1).join(".")))}let a=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(l=>l.type===m.OBJECT&&l.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let l=0;l<o.length;l++){let u=e.indexVar?{...n,[e.itemVar]:o[l],[e.indexVar]:l}:{...n,[e.itemVar]:o[l]};u.__paths__||(u.__paths__=n.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${c}[${l}]`},e.indexVar&&(u.__paths__[e.indexVar]=l);let f=L(e.body,t,r,u);if(Array.isArray(f)&&f.length===1&&!a){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},Bs=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(o.parsedKey,t,r,n):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let c={},a={},l=!0;for(let u of s.properties){let f=u.parsedKey?L(u.parsedKey,t,r,n):u.key,d=u.value;if(d.type===m.LITERAL)a[f]=d.value;else if(d.type===m.VARIABLE)a[f]=Y(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=Y(h.path,r,n);p.push(g!=null?String(g):"")}else{l=!1;break}if(!l)break;a[f]=p.join("")}else if(d.type===m.OBJECT&&d.properties.length<=5){let p={};for(let h of d.properties){let g=h.key,y=h.value;if(y.type===m.LITERAL)p[g]=y.value;else if(y.type===m.VARIABLE)p[g]=Y(y.path,r,n);else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let x=Y(A.path,r,n);b.push(x!=null?String(x):"")}else{l=!1;break}if(!l)break;p[g]=b.join("")}else{l=!1;break}}if(!l)break;a[f]=p}else{l=!1;break}}if(l)return c[i]=a,c}}return null},zs=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!$e(e.whenCondition,o,r,n))return;let i=Bs(e,t,r,n);if(i!==null)return i;if(e.fast){let l={};for(let u of e.properties){let f=u.parsedKey?L(u.parsedKey,t,r,n):u.key,d=u.value;if(d.type===m.LITERAL)l[f]=d.value;else if(d.type===m.VARIABLE)l[f]=Y(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=Y(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=L(h,t,r,n);p.push(g!=null?String(g):"")}l[f]=p.join("")}else l[f]=L(d,t,r,n)}return l}let s={},c=null,a=!1;for(let l of e.properties)if(!l.key.startsWith("$if ")&&!l.key.match(/^\$if\s+\w+.*:?$/)&&!l.key.startsWith("$elif")&&!l.key.startsWith("$else")&&!l.key.startsWith("$for ")){a=!0;break}for(let l of e.properties)if(l.key.startsWith("$if ")||l.key.match(/^\$if\s+\w+.*:?$/)){let u=L(l.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(l.key.startsWith("$for ")){if(e.properties.length===1)return L(l.value,t,r,n)}else{let u=l.value;if(u&&u.type===m.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=L(f.value,t,r,n);d!==void 0&&(s[l.key]=d)}else{let d=L(l.value,t,r,n);d!==void 0&&(s[l.key]=d)}}else{let f=l.parsedKey?L(l.parsedKey,t,r,n):l.key,d=L(l.value,t,r,n);d!==void 0&&(s[f]=d)}}return s},to={},qs=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=L(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,r,n);s!==to&&s!==void 0&&o.push(s)}return o},Ws=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,c=t.partials||{},a=t.functions||t;if(s&&!$e(s,a,r,n))return;if(!c[o])throw new ue(`Partial '${o}' is not defined`);let l=n._partialStack||[];if(l.includes(o))throw new ue(`Circular partial reference detected: ${o}`);let u=c[o],f=r,d={...n,_partialStack:[...l,o]};if(n){f={...r};for(let p of Object.keys(n))p.startsWith("_")||(f[p]=n[p])}if(i){let p=L(i,t,r,n);f={...f,...p}}return L(u,t,f,d)},Hs=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],c=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(c.length>0)throw new ue(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return c.length>0&&(a+="."+c.join(".")),a};var Or=ks;var Ys=/\$\{([^}]*)\}/g,Gs=/#\{([^}]*)\}/g,no=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=Ks(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},Ks=(e,t={})=>e.trim()?Js(e).map(n=>Xs(n.trim(),t)):[],Js=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let c=e[s],a=s>0?e[s-1]:"";!o&&(c==='"'||c==="'")?(o=!0,i=c,r+=c):o&&c===i&&a!=="\\"?(o=!1,i="",r+=c):!o&&c==="("?(n++,r+=c):!o&&c===")"?(n--,r+=c):!o&&c===","&&n===0?(t.push(r),r=""):r+=c}return r&&t.push(r),t},Xs=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:m.LITERAL,value:parseFloat(e)};if(e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};let r=no(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:c,type:a}of o){let l=0;for(;l<n.length;){let u=ze(n.substring(l),c);if(u===-1)break;let f=l+u;f>i&&(i=f,s={op:c,type:a}),l=f+c.length}}if(i!==-1)try{return Z(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},oo=/^\w+\(.*\)$/,Qs=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Zs=e=>{if(!(!e||e.trim()===""||oo.test(e))&&Qs.test(e))throw e.includes("?")&&e.includes(":")?new E(`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 E(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new E(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},ro=e=>{let t=e.trim();if(oo.test(t))throw new E(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new E(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new E(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new E(`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 E(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:m.PATH_REFERENCE,path:t}},dt=(e,t={})=>{let r=e.trim();Zs(r);let n=no(r,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};if(r.includes("[")&&!/[\s+\-*/%|&?:]/.test(r)){let o=0;for(let i of r)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:r}},Lr=(e,t={})=>{let r=e,n=[];(e.includes("\\${")||e.includes("\\#{"))&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),r=r.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\(#\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(Ys)],i=[...r.matchAll(Gs)],s=[...o.map(l=>({match:l,type:"variable"})),...i.map(l=>({match:l,type:"pathref"}))].sort((l,u)=>l.match.index-u.match.index);if(s.length===0){let l=r;for(let u=0;u<n.length;u++)l=l.replace(`__ESCAPED_${u}__`,n[u]);return{type:m.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:l,type:u}=s[0];try{return u==="variable"?dt(l[1],t):ro(l[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw f}}let c=[],a=0;for(let{match:l,type:u}of s){let[f,d]=l,p=l.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&&c.push(h)}try{let h;u==="variable"?h=dt(d.trim(),t):h=ro(d.trim()),c.push(h)}catch(h){if(h.message==="Invalid array index syntax")c.push(f);else throw h}a=p+f.length}if(a<r.length){let l=r.substring(a);for(let u=0;u<n.length;u++)l=l.replace(`__ESCAPED_${u}__`,n[u]);l&&c.push(l)}return{type:m.INTERPOLATION,parts:c}};var Dr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ao=e=>Object.keys(e),ae=e=>e.join("."),ke=(e,t,r)=>{let n=ao(e).filter(o=>!t.has(o));if(n.length>0)throw new E(`Unexpected key '${n[0]}' in condition JSON at '${ae(r)}'`)},De=(e,t)=>typeof e=="string"?Lr(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?ta(e,t):ra(e,t):{type:m.LITERAL,value:e},ea=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new E("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new E("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new E("Empty $each body not allowed");if(r.$partial!==void 0)throw new E("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${n}`]:r}},ta=(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=ea(i),l=Object.keys(a);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let u=so(l[0],a[l[0]],t,!0);r.push(u),n=!0;continue}}catch(a){throw a instanceof E?a:new E(a.message)}let c=Object.keys(i);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let a=so(c[0],i[c[0]],t);r.push(a),n=!0;continue}}let s=De(i,t);r.push(s),(s.type===m.FUNCTION||s.type===m.CONDITIONAL||s.type===m.LOOP||s.type===m.PARTIAL||s.type===m.OBJECT&&!s.fast||s.type===m.ARRAY&&!s.fast)&&(n=!0)}return{type:m.ARRAY,items:r,fast:!n}},ra=(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 E("$partial value must be a string");if(e.$partial.trim()==="")throw new E("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],l=[];for(let[b]of i)for(let A of a)if(b===A||b.startsWith(A+" ")||b.startsWith(A+"#")){l.push(A);break}if(l.length>0)throw new E(`Cannot use $partial with ${l.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...d}=e,p={},h=!1;for(let[b,A]of Object.entries(d)){let x=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(x=b.slice(1)),p[x]=A,h=!0}let g=null;if(h&&(g=De(p,t),g.type===m.OBJECT)){let b=!1;for(let A of g.properties)if(A.value.type===m.VARIABLE||A.value.type===m.INTERPOLATION||A.value.type===m.FUNCTION||A.value.type===m.CONDITIONAL||A.value.type===m.OBJECT&&!A.value.fast||A.value.type===m.ARRAY&&!A.value.fast){b=!0;break}b&&(g.fast=!1)}let y={type:m.PARTIAL,name:u,data:g};return f!==void 0&&(y.whenCondition=io(f,t)),y}for(let[a,l]of i)if(a==="$when"){if(o!==null)throw new E("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new E("Missing condition expression after '$when'");o=io(l,t),n=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new E("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[a,l]=i[s];if(a==="$when"){s++;continue}if(a==="$each")throw new E("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let u=na(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]||"",f=u?`:${u}`:"";throw new E(`$for loops must be inside arrays - use '- $for${f} item in items:' instead of '$for${f} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(a.startsWith("$elif ")||a.startsWith("$else"))throw new E(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new E("Missing condition expression after '$if'");{let u=De(l,t);(u.type===m.FUNCTION||u.type===m.CONDITIONAL||u.type===m.PARTIAL||u.type===m.OBJECT&&!u.fast||u.type===m.ARRAY&&!u.fast)&&(n=!0);let f=Lr(a,t),d={key:a,value:u};(f.type!==m.LITERAL||f.value!==a)&&(d.parsedKey=f),r.push(d),s++}}}let c={type:m.OBJECT,properties:r,fast:!n};return o&&(c.whenCondition=o),c},na=(e,t,r={})=>{let n=[],o=[],i=t,[s,c]=e[i],a=null,l;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)a=f[1],l=f[2];else throw new E(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());Rr(l);let u=Z(l,r);for(n.push(u),o.push(De(c,r)),i++;i<e.length;){let[f,d]=e[i],p=!1,h;if(a?f.startsWith(`$elif#${a} `)?(h=f.substring(`$elif#${a} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f===`$else#${a}`||f===`$else#${a}:`)&&(p=!0,h=null):f.startsWith("$elif ")?(h=f.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f==="$else"||f==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{Rr(h);let g=Z(h,r);n.push(g)}if(o.push(De(d,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:a},nextIndex:i}},$r={eq:O.EQ,neq:O.NEQ,gt:O.GT,gte:O.GTE,lt:O.LT,lte:O.LTE,in:O.IN,add:O.ADD,sub:O.SUBTRACT},kr={all:O.AND,any:O.OR},oa=new Set(["var","literal","call","not",...Object.keys($r),...Object.keys(kr)]),ia=(e,t,r)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${ae(r)}' requires an array`);if(e.length!==2)throw new E(`Condition JSON operator '${t}' at '${ae(r)}' requires exactly 2 operands`);return e},sa=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${ae(o)}' requires an array`);if(e.length===0)throw new E(`Condition JSON operator '${t}' at '${ae(o)}' requires at least 1 condition`);return e.map((s,c)=>Se(s,n,[...o,c])).reduce((s,c)=>({type:m.BINARY,op:r,left:s,right:c}))},aa=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],ke(e,new Set(["call","args"]),r);else if(Dr(e.call))n=e.call.name,o=e.call.args??[],ke(e,new Set(["call"]),r),ke(e.call,new Set(["name","args"]),[...r,"call"]);else throw new E(`Condition JSON call at '${ae(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new E(`Condition JSON call at '${ae(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new E(`Invalid condition JSON function name '${n}' at '${ae(r)}'`);if(!Array.isArray(o))throw new E(`Condition JSON call '${n}' at '${ae(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>Se(i,t,[...r,"args",s]))}},Se=(e,t={},r=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:m.LITERAL,value:e};if(Array.isArray(e))throw new E(`Condition JSON array at '${ae(r)}' must be wrapped in an operator or { literal: [...] }`);if(!Dr(e))throw new E(`Invalid condition JSON value at '${ae(r)}'`);let n=ao(e);if(n.length===0)throw new E(`Condition JSON object at '${ae(r)}' must contain an operator`);let o=n.filter(s=>oa.has(s));if(o.length===0)throw new E(`Unknown condition JSON operator '${n[0]}' at '${ae(r)}'`);if(o.length>1)throw new E(`Condition JSON at '${ae(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(ke(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new E(`Condition JSON var at '${ae(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return ke(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return aa(e,t,r);if(i==="not")return ke(e,new Set(["not"]),r),{type:m.UNARY,op:tt.NOT,operand:Se(e.not,t,[...r,"not"])};if(i in kr)return ke(e,new Set([i]),r),sa(e[i],i,kr[i],t,[...r,i]);if(i in $r){ke(e,new Set([i]),r);let s=ia(e[i],i,[...r,i]);return{type:m.BINARY,op:$r[i],left:Se(s[0],t,[...r,i,0]),right:Se(s[1],t,[...r,i,1])}}throw new E(`Unknown condition JSON operator '${i}' at '${ae(r)}'`)},io=(e,t={})=>{if(e==null)throw new E("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression after '$when'");return Z(e,t)}return Dr(e)||Array.isArray(e)?Se(e,t):{type:m.LITERAL,value:e}},Z=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let l=e.slice(1,-1),u=0,f=!0;for(let d=0;d<l.length;d++)if(l[d]==="("?u++:l[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return Z(l,t)}let r=ze(e,"||");if(r!==-1)return{type:m.BINARY,op:O.OR,left:Z(e.substring(0,r).trim(),t),right:Z(e.substring(r+2).trim(),t)};let n=ze(e,"&&");if(n!==-1)return{type:m.BINARY,op:O.AND,left:Z(e.substring(0,n).trim(),t),right:Z(e.substring(n+2).trim(),t)};let o=[{op:">=",type:O.GTE},{op:"<=",type:O.LTE},{op:"==",type:O.EQ},{op:"!=",type:O.NEQ},{op:">",type:O.GT},{op:"<",type:O.LT},{op:" in ",type:O.IN}];for(let{op:l,type:u}of o){let f=ze(e,l);if(f!==-1)return{type:m.BINARY,op:u,left:Z(e.substring(0,f).trim(),t),right:Z(e.substring(f+l.length).trim(),t)}}let i=-1,s=null,c=[{op:" + ",type:O.ADD},{op:" - ",type:O.SUBTRACT}];for(let{op:l,type:u}of c){let f=0;for(;f<e.length;){let d=ze(e.substring(f),l);if(d===-1)break;let p=f+d;p>i&&(i=p,s={op:l,type:u}),f=p+l.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:Z(e.substring(0,i).trim(),t),right:Z(e.substring(i+s.op.length).trim(),t)};let a=[" * "," / "," % "];for(let l of a)if(ze(e,l)!==-1)throw new E(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:m.UNARY,op:tt.NOT,operand:Z(e.substring(1).trim(),t)}:co(e,t)},ze=(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},ca=e=>{if(e=e.trim(),e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:m.LITERAL,value:""};if(e==="{}")return{type:m.LITERAL,value:{}};if(e==="[]")return{type:m.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:m.LITERAL,value:t}:{type:m.VARIABLE,path:e}},co=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return dt(r,t);let o=ca(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return dt(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},la=(e,t=!1)=>{let r=t?"$each":"$for";try{Gn(e)}catch(n){if(n instanceof E&&t){let o=n.message.replace(/\$for/g,"$each");throw new E(o.replace("Parse Error: ",""))}throw n}},so=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new E(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],c=i[2].trim();la(c,n);let a=c.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let y=n?"$each":"$for";throw new E(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${c}')`)}let l=a[1].trim(),u=a[2].trim(),f,d=null;if(l.includes(",")){let y=l.split(",").map(b=>b.trim());if(y.length!==2)throw new E(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);f=y[0],d=y[1]}else f=l;let p=["this","undefined","null","true","false"];if(p.includes(f))throw new E(`Reserved variable name: ${f}`);if(d&&p.includes(d))throw new E(`Reserved variable name: ${d}`);let h=co(u,r),g=De(t,r);return{type:m.LOOP,itemVar:f,indexVar:d,iterable:h,body:g,flatten:s!=="nested"}};var ua=(e,t={})=>{let{functions:r={}}=t;return De(e,r)},Vt=ua;var pt={};Es(pt,{now:()=>fa});var fa=()=>Date.now();var da=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...pt,...n},s=Vt(e,{functions:i}),c={};for(let[a,l]of Object.entries(o))c[a]=Vt(l,{functions:i});return Or(s,t,{functions:i,partials:c})},ce=da;var pa=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",ha=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,ma=(e,t)=>{if(pa(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression");return Z(e,t)}return Se(e,t)},ga=(e,t={},r={})=>{let n=ha(r),o={...pt,...n},i=ma(e,o);return!!$e(i,{functions:o,partials:{}},t,{})},Tr=ga;var mt=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return Tr(e,t)},mo=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=a=>a,transformActionFirstArgument:c=a=>a}=r;for(let[a,l]of Object.entries(t))a!=="createInitialState"&&(a.startsWith("select")?o[a]=(...u)=>l(s(n),...u):i[a]=(...u)=>{let f;return n=_r(n,p=>{let h=l(c(p),...u);f=h!==void 0&&!de(h)?h:void 0}),f});return{...o,...i}},Mt=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return _r(n,i=>{o.forEach(s=>{t.forEach(c=>{c(i,s)})})})};var ya=(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{}}},ge=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),ht=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),go=e=>{let t=de(e)?Be(e):e;return structuredClone(t)},ba=({characterId:e,resourceCharacter:t,variables:r={}}={})=>{if(!ge(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},Ut=({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=ba({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},Te=e=>ge(e,"computed"),rt=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Te(t[r]))),Ia=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),Nr=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},Aa=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=Ia(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 Nr(s,i)}return n==="runtime"?Nr(t.runtime,r.slice(1)):Nr(t,r)},wa=(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)`)},lo=(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`)},Ea=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},Ae=(e,t,r,n)=>(wa(e,t,n),t.map(o=>Ft(o,r))),me=(e,t,r,n)=>{let o=Ae(e,t,r,n);return o.forEach(i=>Ea(e,i)),o},xa=(e,t,r)=>{switch(e){case"var":return Aa(t,r);case"add":{let[n,o]=me(e,t,r,2);return n+o}case"sub":{let[n,o]=me(e,t,r,2);return n-o}case"mul":{let[n,o]=me(e,t,r,2);return n*o}case"div":{let[n,o]=me(e,t,r,2);return n/o}case"mod":{let[n,o]=me(e,t,r,2);return n%o}case"neg":{let[n]=me(e,t,r,1);return-n}case"round":{let[n]=me(e,t,r,1);return Math.round(n)}case"floor":{let[n]=me(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=me(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=me(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=me(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=me(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=Ae(e,t,r,2);return n==o}case"neq":{let[n,o]=Ae(e,t,r,2);return n!=o}case"gt":{let[n,o]=Ae(e,t,r,2);return n>o}case"gte":{let[n,o]=Ae(e,t,r,2);return n>=o}case"lt":{let[n,o]=Ae(e,t,r,2);return n<o}case"lte":{let[n,o]=Ae(e,t,r,2);return n<=o}case"in":{let[n,o]=Ae(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return lo(e,t),t.every(n=>!!Ft(n,r));case"or":case"any":return lo(e,t),t.some(n=>!!Ft(n,r));case"not":{let[n]=Ae(e,t,r,1);return!n}case"length":{let[n]=Ae(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:ht(n)?Object.keys(n).length:0}case"includes":{let[n,o]=Ae(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return go(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},Ft=(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 xa(n,o,t)},va=(e,t={})=>mt(e,{variables:t.variables,runtime:t.runtime}),Sa=(e,t)=>{if(!ht(e))throw new Error(`${t} must be an object`);let r=ge(e,"expr"),n=ge(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},Pr=(e,t,r)=>(Sa(e,t),ge(e,"value")?go(e.value):Ft(e.expr,r)),Ca=(e,t={},r="unknown")=>{if(!ht(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=ge(e,"expr"),o=ge(e,"value");if(ge(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(!ht(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let c=e.branches[s];if(!ht(c))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!ge(c,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(va(c.when,t))return Pr(c,`Computed variable "${r}" branch ${s}`,t)}return Pr(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 Pr(e,`Computed variable "${r}"`,t)},_a=(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}`)}},gt=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=rt(e,r),i=Object.entries(r).filter(([,f])=>Te(f)).map(([f])=>f),s={},c=[],a=f=>{if(ge(s,f))return s[f];let d=r[f];if(!Te(d))return o[f];let p=c.indexOf(f);if(p>=0){let h=[...c.slice(p),f].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}c.push(f);try{let h=Ca(d.computed,u,f);return _a(f,d.type,h),s[f]=h,h}finally{c.pop()}},l=new Proxy({},{get:(f,d)=>{if(typeof d=="string")return a(d)},has:(f,d)=>typeof d=="string"&&(ge(o,d)||i.includes(d)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(f,d)=>{if(!(typeof d!="string"||!ge(o,d)&&!i.includes(d)))return{enumerable:!0,configurable:!0}}}),u={variables:l,runtime:t,resolveVariable:a};return n?(i.forEach(f=>{a(f)}),{...o,...s}):l},Ra=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>gt({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),Bt=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(Te(o))return;let i=ya(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},zt=(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(", ")}`)},qt=(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(", ")}`)},Oa=2,uo=12,yo=(e=Oa)=>{if(!Number.isInteger(e)||e<0||e>uo)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${uo}.`);return e},La=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},jt=e=>typeof e=="number"&&Number.isFinite(e),Fr=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!jt(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!jt(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!jt(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}".`);yo(o.roundTo)}}},Wt=(e,t,r,n={})=>{let o=(s,c,a)=>{let l=s??c;if(!jt(l))throw new Error(`Operation "${t}" requires ${a} to be a number.`);return l},i=s=>{let c=o(s,void 0,"value");if(c===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return c};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return La(o(e,0,"current value")/i(r),yo(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 bo=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let r=new Date(e),n=o=>String(o).padStart(2,"0");return t.replace("DD",n(r.getDate())).replace("MM",n(r.getMonth()+1)).replace("YYYY",r.getFullYear()).replace("YY",String(r.getFullYear()).slice(-2)).replace("HH",n(r.getHours())).replace("mm",n(r.getMinutes())).replace("ss",n(r.getSeconds()))},$a=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let c=i.character?.sprite;return c&&Object.keys(c).length>0&&(s.sprite=c),Object.keys(s).length>0?s:void 0},n=r(e),o=r(t);return JSON.stringify(n)===JSON.stringify(o)?null:n&&!o?{changeType:"delete",data:e}:o&&!n?{changeType:"add",data:t}:o&&n?{changeType:"update",data:t}:null},fo=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},po=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},ho=(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,ka=(e,t)=>{let r={},n=ho(fo(e),fo(t)),o=ho(po(e),po(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},Mr=(e={},t={})=>{let r={},n=["sfx","voice"],o=c=>{let a=e[c],l=t[c];l&&!a?r[c]={changeType:"add",data:l}:a&&!l?n.includes(c)||(r[c]={changeType:"delete",data:a}):a&&l&&JSON.stringify(a)!==JSON.stringify(l)&&(r[c]={changeType:"update",data:l})},i=ka(e.background,t.background);i&&(r.background=i),o("screen"),o("bgm"),o("voice");let s=$a(e.dialogue,t.dialogue);return s&&(r.dialogue=s),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),r},Ur=(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(c=>{let a={...c};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},Da=(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},Ta=(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=Da(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},Na={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"])},Io=(e,t)=>{let r=e[e.length-1];return r?Na[r]?.has(t)===!0:!1},Vr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Vr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Io(r,n)?o:Vr(o,t,[...r,n])])):Ta(e,t),jr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>jr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Io(r,n)?o:jr(o,t,[...r,n])])):typeof e=="string"?ce(e,t):e,Br=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let r=Vr(e,t._event);return jr(r,t)};var q=e=>structuredClone(de(e)?Be(e):e),U=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ao=e=>e?.animations?.playback?.continuity==="persistent",$=(e,t)=>U(e??{},t)&&e[t]!==void 0,yt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:q(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Pa=e=>$(e,"opacity")||$(e,"blur"),vo=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],So=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],zr=["animationName","animationSpeed","loop"],Va=e=>vo.some(t=>$(e,t)),Co=e=>e?.text&&$(e.text,"content")&&$(e.text,"textStyleId"),_o=e=>$(e,"text"),ja=(e,t)=>e.resourceId?!0:Co(e)?!t?.text:!1,Fa=(e,t)=>{let r={...q(e),...t};return t.text&&e.text&&(r.text={...q(e.text),...q(t.text)}),r},Ma=(e,t)=>{if(_o(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!Co(e)&&!t?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},wo=e=>So.some(t=>$(e,t)),Eo=e=>zr.some(t=>$(e,t)),Ua=(e,t,{hasAuthoredTransformId:r=!1}={})=>{if(!t)return e;for(let n of So)!r&&!$(e,n)&&$(t,n)&&(e[n]=t[n]),U(e,n)&&e[n]===void 0&&delete e[n];return e},Ro=(e,t,r)=>{let n=e[r];return n?.id===t?.id?n:e.find(o=>o.id===t?.id)},Ba=(e,t)=>{if(!t)return e;for(let r of vo)!$(e,r)&&$(t,r)&&(e[r]=t[r]),U(e,r)&&e[r]===void 0&&delete e[r];return e},za=(e,t)=>(t&&(!$(e,"opacity")&&$(t,"opacity")&&(e.opacity=t.opacity),!$(e,"blur")&&$(t,"blur")&&(e.blur=q(t.blur)),U(e,"opacity")&&e.opacity===void 0&&delete e.opacity,U(e,"blur")&&e.blur===void 0&&delete e.blur),e),Oo=(e,t,r=[],{hasPatchFn:n=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,c)=>{let a=Ro(r,s,c),l=t(s,a),u=Pa(s),f=Va(s),d=n(s),p=U(s,"animations"),h=q(s);return!l&&(u||f||d)&&a&&(h=o?o(a,h):{...q(a),...h},p||delete h.animations),za(Ba(h,a),a)}).filter(s=>t(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},qa=e=>{if(e){if(e.character&&U(e.character,"name"))return e.character.name;if(U(e,"characterName"))return e.characterName}},Lo=e=>!!e?.character&&U(e.character,"sprite"),Wa=e=>{let t={},r=!1,n=qa(e);return n!==void 0&&(t.name=n,r=!0),Lo(e)&&(t.sprite=q(e.character.sprite),r=!0),r?t:void 0},xo=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Ha=({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=>q(o)):delete e.initialRevealedContent,e.content=[...n,...t]},Ya=()=>({}),Ga=(e,t)=>{if(!t.screen)return;let r=$(t.screen,"opacity"),n=$(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:$(i,"opacity")&&(s.opacity=i.opacity),n?s.blur=q(t.screen.blur):$(i,"blur")&&(s.blur=q(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},Ka=(e,t)=>{if(t.background){let r=$(t.background,"resourceId"),n=$(t.background,"colorId"),o=$(t.background,"opacity"),i=$(t.background,"blur"),s=$(t.background,"transformId"),c=wo(t.background),a=Eo(t.background),{animationsOnly:l,state:u}=yt(t.background,p=>$(p,"resourceId")||$(p,"colorId")||$(p,"opacity")||$(p,"blur")||$(p,"transformId")||wo(p)||Eo(p));if(l){e.background=e.background?{...q(e.background),...u}:u;return}if(!r&&!n&&!o&&!i&&!s&&!c&&!a){delete e.background;return}let f=e.background,d=q(t.background);if(!r&&f?.resourceId){d.resourceId=f.resourceId,!U(d,"transformId")&&f.transformId&&(d.transformId=f.transformId);for(let p of zr)!$(d,p)&&$(f,p)&&(d[p]=f[p])}Ua(d,f,{hasAuthoredTransformId:s}),!n&&f?.colorId&&(d.colorId=f.colorId),!o&&$(f,"opacity")&&(d.opacity=f.opacity),!i&&$(f,"blur")&&(d.blur=q(f.blur)),U(d,"resourceId")&&d.resourceId===void 0&&delete d.resourceId,U(d,"colorId")&&d.colorId===void 0&&delete d.colorId,U(d,"animations")&&d.animations===void 0&&delete d.animations,U(d,"transformId")&&d.transformId===void 0&&delete d.transformId,U(d,"opacity")&&d.opacity===void 0&&delete d.opacity,U(d,"blur")&&d.blur===void 0&&delete d.blur;for(let p of zr)U(d,p)&&d[p]===void 0&&delete d[p];if(!d.resourceId&&!d.colorId){delete e.background;return}f?.resourceId===d.resourceId&&f?.transformId===d.transformId&&!U(d,"animations")&&Ao(f)&&(d.animations=q(f.animations)),e.background=d}else e.background?.animations&&!Ao(e.background)&&(e.background.animations={})},Ja=(e,t)=>{if(!t.dialogue){e.dialogue&&(xo(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,delete e.dialogue.textSpeed,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let r=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:l,state:u}=yt(t.dialogue.ui,f=>!!f.resourceId);l?e.dialogue.ui={...e.dialogue.ui,...u}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let n=t.dialogue.append===!0&&r!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&Ha({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=U(t.dialogue,"characterId"),s=Wa(t.dialogue),c=s!==void 0,a=Lo(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,c?e.dialogue.character=!i&&o&&e.dialogue.character?{...q(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,a||xo(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let l={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.textSpeed!==void 0&&(l.textSpeed=e.dialogue.textSpeed),e.dialogue.character&&(l.character=q(e.dialogue.character)),e.dialogue.lines.push(l)}},Xa=(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=q(t.sfx)}else e.sfx&&delete e.sfx},Qa=(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=q(t.bgm),t.bgm.resourceId&&(e.bgm.loop=t.bgm.loop??!0)}},Za=(e,t)=>{if(t.visual){let r=e.visual?.items||[];t.visual.items?.forEach((i,s)=>{Ma(i,Ro(r,i,s))});let{hasValidItems:n,processedItems:o}=Oo(t.visual.items,ja,r,{hasPatchFn:_o,mergeItemFn:Fa});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))},ec=(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}=Oo(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},tc=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},rc=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=yt(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},nc=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=yt(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},oc=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=yt(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=q(t.form)}else e.form&&delete e.form},ic=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},sc=(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=q(t.voice)}else e.voice&&delete e.voice},ac=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},qe=e=>Mt(Ya,[ac,Ga,Ka,Xa,Qa,Za,Ja,ec,tc,rc,nc,oc,ic,sc])(e);var nt=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=ce(e,t);return r&&typeof r=="object"?e:r};var cc=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"}}),We=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}),bt=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),$o=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"}),qr=Object.freeze(["dialogueTextSpeed","autoForwardDelay","autoForwardSpeed","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Wr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),lc=(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]}},He=e=>Object.fromEntries(Object.entries(cc).map(([t,r])=>{let n=lc(e,r.source),o=n!==void 0?n:We[t]??bt[t];return[t,o]})),Ne=(e,t)=>He(e)[t],ko=(e={})=>Object.fromEntries(qr.map(t=>[t,e[t]??We[t]]));var ot=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:ot.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:ot.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:ot.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:ot.VISUAL_BEHIND_CHOICE,FOREGROUND:ot.VISUAL_FOREGROUND}),Hr=_e.BEHIND_DIALOGUE,Yr=Object.freeze(Object.values(_e).sort((e,t)=>e-t));var Re={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:bo},uc=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,fc=(e,t)=>{let r=String(t||"").trim();if(!r)return;let n=r.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of n){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},Kt=(e,t,r)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),c=uc.exec(s);if(c){let[,a,l,u]=c,f=fc(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((p,h)=>{let g={...t,[a]:p};l&&(g[l]=h),d.forEach(y=>{let b=Kt(y,g,r),A=ce(b,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(Kt(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=Kt(i,t,r)}),n},ln=({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".`)},dc=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);if(ln({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n!==void 0){let s=gc(n,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},pc=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return ln({animationType:e.type,animationId:t,animationPath:r}),e.type},hc=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},mc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},gc=(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},yc=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},Ye=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ho=e=>e?.playback?.continuity==="persistent",Zr=e=>Array.isArray(e)?e.map(Zr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=Zr(e[r]),t),{}),Xt=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(Zr(t))},Yo=(e=[])=>e.filter(t=>Ho(t)).map(t=>structuredClone(t)),Go=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,Gr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,Go(r)),0),Ko=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(Gr(e.tween),Gr(e.prev?.tween),Gr(e.next?.tween),Go(e.mask?.progress))/yc(e),Do=({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(Xt).filter(Boolean));return e.some(n=>{if(!Ho(n))return!1;let o=Xt(n);return o?r.has(o):!1})},we=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||Do({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:Do({animationInstances:e,activePersistentAnimations:o}),bc=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Ic=(e,t)=>{if(bc(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},Ac=({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?dc({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},wc=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return ln({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},un=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(wc(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},en=(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},Ec=({content:e,path:t,variables:r})=>en(e,t).reduce((n,o)=>{let i=nt(o.text,{variables:r});return n+`${i??""}`.length},0),To=(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))},Ht=(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("-")}`},Yt=(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},xc=(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},vc=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Sc=(e={})=>vc.some(t=>Ye(e,t)),Jo=(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"}},Jt=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Cc=(e={})=>e.textStyles||{},_c=(e={})=>e.images||{},Rc=.5,Oc=(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]},Xo=({id:e,resourceId:t,spritesheet:r,animationName:n,animationSpeed:o,loop:i,transform:s={}}={})=>{let c=Oc(r,n,t),a=c?r.animations?.[c]: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??Rc,loop:i??a.loop??!0}}},Qo=({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 Xo({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}`)},Lc=(e={})=>e.colors||{},$c=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,wt=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,st=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},No=(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},fn=(e,t)=>{if(typeof e!="string"||!$c.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},Po=(e,t,r)=>{let n=fn(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})`},kc=(e={},t)=>{let r=Cc(e)?.[t];if(!r)throw new Error(`Text style "${t}" not found`);let n=e.fonts?.[r.fontId];if(!n)throw new Error(`Font "${r.fontId}" not found for text style "${t}"`);let o=e.colors?.[r.colorId];if(!o)throw new Error(`Color "${r.colorId}" not found for text style "${t}"`);let i=No(r.colorAlpha,"colorAlpha",t),s={fontFamily:n.fileId,fontSize:r.fontSize??16,fontWeight:r.fontWeight??"400",fontStyle:r.fontStyle??"normal",lineHeight:r.lineHeight??1.2,fill:Po(o.hex,i,`Color "${r.colorId}" for text style "${t}"`)};if(r.align!==void 0&&(s.align=r.align),r.wordWrap!==void 0&&(s.wordWrap=r.wordWrap),r.breakWords!==void 0&&(s.breakWords=r.breakWords),r.wordWrapWidth!==void 0&&(s.wordWrapWidth=r.wordWrapWidth),r.strokeColorId){let c=e.colors?.[r.strokeColorId];if(!c)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let a=No(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=Po(c.hex,a,`Stroke color "${r.strokeColorId}" for text style "${t}"`)}else if(r.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return r.strokeWidth!==void 0&&(s.strokeWidth=r.strokeWidth),s},tn=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>tn(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]=tn(i,t,wt(r,o)));return e.textStyleId!==void 0&&(st(e.textStyleId,r,"textStyleId"),n.textStyle=kc(t,e.textStyleId)),n},dn=(e={},t)=>{let r=Lc(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return fn(r.hex,`Color "${t}"`)},Zo=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Kr=(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 ${Zo(`${t}.fill`)} instead`)},Dc=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Et(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]=Et(i,t,wt(r,o)));return e.colorId!==void 0&&(st(e.colorId,r,"colorId"),n.fill=dn(t,e.colorId)),n},Et=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Et(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 ${Zo("fill")} instead`);Kr(e,"hover",r),Kr(e,"click",r),Kr(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]=Dc(i,t,wt(r,o));continue}n[o]=Et(i,t,wt(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(st(e.colorId,r,"colorId"),n.fill=dn(t,e.colorId)),n},Jr=(e={},t)=>{let r=_c(e)?.[t];return r||null},ei=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",Vo=(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 ${ei(`${t}.${n}`)} instead`)},jo=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},rn=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>rn(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 ${ei(o)} instead`);Vo(e,"hover",r,"src"),Vo(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]=rn(i,t,wt(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){st(e.imageId,r,"imageId");let o=Jr(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&&(st(e.hoverImageId,r,"hoverImageId"),jo(n,"hover",Jr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(st(e.clickImageId,r,"clickImageId"),jo(n,"click",Jr(t,e.clickImageId)?.fileId??e.clickImageId)),n},pn=(e,t={},r="root")=>rn(Et(tn(e,t,r),t,r),t,r),Oe=pn,Ke=(e=[])=>e.find(t=>t.id==="story"),Tc="#000000",nn="bg-cg-background-color",Nc=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?fn(r?.backgroundColor??Tc,"screen.backgroundColor"):dn(e,t.colorId),ti=(e={})=>{if(Ye(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Pc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Fo=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=ti(e),n=Pc(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},Vc=(e={})=>{if(Ye(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},jc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},ri=(e={})=>{let t=Vc(e),r=jc(e),n={};return t!==void 0&&(n.alpha=t),r&&(n.blur=r),n},It=(e={})=>ri(e),Pe=(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},Fc=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],hn=(e={})=>e.text&&Ye(e.text,"content")&&Ye(e.text,"textStyleId"),Mo=(e={})=>{if(e.resourceId)return e.resourceId;if(hn(e))return"text"},Mc=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 Fc)if(Ye(e.text,t))throw new Error(`Visual item "${e.id}" text.${t} is reserved for the visual item`)}},Uc=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:nn,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:Nc({resources:e,background:t,screen:r})};if(n){let i=ti(t);i!==void 0&&(o.alpha=i)}return o},Bc=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.spritesheets?.[t]||e.layouts?.[t]):!1,Uo=({resources:e={},resourceId:t,colorId:r})=>{let n=Jo(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:Jt({resourceId:t,kind:n})}:r!==void 0?{resourceId:nn,targetId:nn}:{resourceId:void 0,targetId:void 0}},ni=100,Ge=ni,zc="channel:bgm",qc="channel:voice",Wc="default",Hc=e=>String(e).replaceAll("%","%25").replaceAll(":","%3A"),At=(...e)=>e.map(Hc).join(":"),Qt=(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)})},Yc=(e,t)=>e*t/ni,oi=(e={},t)=>e?.[t]??We[t],mn=(e={},t,r=Ge)=>Yc(r,oi(e,t)),gn=({id:e,volume:t,muted:r,pan:n,children:o,runtime:i})=>({id:e,type:"audio-channel",volume:t,muted:!!i?.muteAll||(r??!1),pan:n??0,children:o}),Gt=(e,t,r,n)=>e[r]!==void 0?e[r]:t[r]!==void 0?t[r]:n,Gc=["muted","pan","playbackRate","startAt","endAt"],yn=({id:e,sound:t,resource:r,defaultLoop:n=!1})=>{let o={id:e,type:"sound",src:r.fileId,loop:Gt(t,r,"loop",n),volume:Gt(t,r,"volume",Ge),startDelayMs:Gt(t,r,"startDelayMs",0)};Gc.forEach(s=>{let c=Gt(t,r,s,void 0);c!==void 0&&(o[s]=c)});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},Ee=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:u,confirmDialog:f,form:d,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:b}={})=>{let A={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??c??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},x=Zc({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e,runtime:A}),C={variables:e,runtime:A,saveSlots:r,isChoiceVisible:a,isFormVisible:l,canRollback:u,confirmDialog:f,form:d,historyDialogue:p,characters:h};return x&&(C.dialogue=x,C.dialogueLines=x.lines),C},Bo=100,Zt=(e,t)=>{if(Array.isArray(e))return e.map(n=>Zt(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=Zt(r[n],t)}),r.type==="text-revealing"?t(r):r},Kc=e=>Zt(e,t=>({...t,revealEffect:"none"})),Jc=e=>Zt(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,Bo):Bo;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),Ve=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?Kc(e):r?Jc(e):e,ii=({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:{}}}}),on=e=>{if(Array.isArray(e))return e.map(on);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=on(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}}:{}}}}},Xc=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),zo="submit",Xr=(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}}},sn=(e,t,r={})=>{if(Array.isArray(e))return e.map(l=>sn(l,t,r));if(!e||typeof e!="object")return e;let n=typeof e.type=="string",o=n&&e.formRole===zo,i=n&&r.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},c={};for(let[l,u]of Object.entries(e))c[l]=sn(u,t,l==="children"?s:{});let a=c;if(a.type==="input"&&typeof a.field=="string"){let l=t?.fields?.[a.field];if(l){let u={updateFormField:{formKey:t.key,field:l.id,value:"_event.value"}};a={...a,value:l.value,placeholder:a.placeholder===void 0?l.placeholder:a.placeholder,multiline:a.multiline===void 0?l.multiline:a.multiline,...a.maxLength===void 0&&l.maxLength!==void 0?{maxLength:l.maxLength}:{},change:Xr(a.change,u),submit:Xr(a.submit,t.submitActions)}}}return a.formRole===zo||i?{...a,click:Xr(a.click,t.submitActions,{replaceActions:!0})}:a},an=(e,t)=>{if(Array.isArray(e))return e.map(n=>an(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=an(o,t);for(let n of Xc){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form"}})}return r},cn=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0,s=Ut({characterId:e,character:t,characterName:r,characters:n,variables:o});return{...i||{},...t||{},name:s}},si=(e=[],t={},r={})=>e.map(n=>{let o=cn({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}}),Qc=e=>!(!e||e.mode==="adv"&&e.content===void 0),Zc=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n,runtime:o}={})=>{if(!t&&!Qc(e))return;let i=e.content===void 0?[{text:""}]:en(e.content,"dialogue.content"),s=e.content===void 0?0:Ec({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),c=o?.dialogueTextSpeed??We.dialogueTextSpeed,a=e.textSpeed??c,l=(e.lines||[]).map((f,d)=>{let p=en(f.content,`dialogue.lines[${d}].content`),h=cn({characterId:f.characterId,character:f.character,characterName:f.characterName,characters:r,variables:n});return{...f,textSpeed:f.textSpeed??c,content:p.map(g=>({...g,text:nt(g.text,{variables:n})})),character:h,characterName:h.name}}),u=cn({characterId:e.characterId,character:e.character,characters:r,variables:n});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:u,textSpeed:a,content:i.map(f=>({...f,text:nt(f.text,{variables:n})})),initialRevealedCharacters:s,lines:l}},ai=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=ce(e,r,{functions:Re});return Oe(Ve(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},Qr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),qo=({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:Qr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:Qr(o.keyup)});return}e[n]={...i,[r]:{payload:Qr(o)}}})},el=(e={},t={})=>{let r={};return qo({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),qo({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},Le=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:c})=>{if(!e)return[];let a=[],l=({instanceId:b,targetId:A})=>{let x=Ac({resources:t,animationId:p,playback:h,instanceId:b,targetId:A,animationPath:s});x&&a.push(x)},u=r!=null&&r!==!1,f=n!=null&&n!==!1,d=o&&i&&o===i;Ic(e,s);let p=hc(e),h=mc(e),g=t?.animations?.[p],y=pc(g,{animationId:p,animationPath:s});if(y==="update")return f&&i?l({instanceId:`${c}-animation-update`,targetId:i}):u&&o&&l({instanceId:`${c}-animation-update`,targetId:o}),a;if(y==="transition"){let b=`${c}-animation-transition`,A=h?.continuity==="persistent"?b:`${c}-animation-in`;if(u&&f&&d)return l({instanceId:b,targetId:i}),a;u&&l({instanceId:`${c}-animation-out`,targetId:o}),f&&l({instanceId:A,targetId:i})}return a},tl=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),rl=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:c,variables:a,runtime:l,activePersistentAnimations:u,restoredPersistentAnimations:f,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,saveSlots:A=[]})=>{let{elements:x,animations:C}=e;if(t.background){let N=n===void 0?!0:Ye(n?.background??{},"animations"),k=x.find(oe=>oe.id==="story");if(!k)return e;let w=xc(o,t.background),j=w||Sc(t.background),M=r?.background?.resourceId,ee=r?.background?.colorId,P=t.background.resourceId??(t.background.animations?M:void 0),W=t.background.colorId??(t.background.animations?ee:void 0),H=Bc(o,P),te={...t.background,colorId:W};if((W!==void 0||H)&&k.children.push(Uc({resources:o,background:te,screen:i,includeOpacity:!H})),P){let{images:oe={},videos:re={},spritesheets:J={}}=o,ie=Jo(o,P),se;if(ie==="sprite"?se=oe[P]:ie==="video"?se=re[P]:ie==="spritesheet-animation"&&(se=J[P]),se){let v=ie==="video",_=ie==="spritesheet-animation",V={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...w},X={...Fo(t.background,{includeDefaultAlpha:!0}),...Pe(V,t.background)},z;_?z=Xo({id:Jt({resourceId:P,kind:ie}),resourceId:P,spritesheet:se,animationName:t.background.animationName,animationSpeed:t.background.animationSpeed,loop:t.background.loop,transform:X}):z={id:Jt({resourceId:P,kind:ie}),type:v?"video":"sprite",src:se.fileId,width:se.width,height:se.height,...X},v&&(z.loop=t.background.loop??!1,z.volume=se.volume??50),z&&k.children.push(z)}}if(P){let{layouts:oe={}}=o,re=oe[P];if(re){let J={id:Jt({resourceId:P,kind:"container"}),type:"container",children:re.elements,...Fo(t.background)};j&&Object.assign(J,Pe({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...w},t.background));let ie=ce(J,Ee({variables:a,runtime:l,saveSlots:A,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,characters:o.characters||{},skipTransitionsAndAnimations:c}),{functions:Re});k.children.push(Oe(Ve(ie,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:c}),o))}}let xe=Uo({resources:o,resourceId:M,colorId:ee}),G=Uo({resources:o,resourceId:P,colorId:W}),K=Le({animationsDef:t.background.animations,resources:o,previousResourceId:xe.resourceId,currentResourceId:G.resourceId,previousTargetId:xe.targetId,currentTargetId:G.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});we({animationInstances:K,isLineCompleted:s,skipTransitionsAndAnimations:c,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:N})&&C.push(...K)}return e},nl=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:c,animations:a}=e;if(t.character&&n){let l=c.find(h=>h.id==="story");if(!l)return e;let u=t.character.items||[],f=r?.character?.items||[],d=To(u),p=To(f);for(let h=0;h<u.length;h++){let g=u[h],{transformId:y,sprites:b}=g,A=f.find(P=>P.id===g.id),x=f.findIndex(P=>P.id===g.id),C=A?.sprites&&A.sprites.length>0,N=b&&b.length>0,k=x>=0?Ht(A,x,p):void 0,w=Le({animationsDef:g.animations,resources:n,previousResourceId:k,currentResourceId:N?Ht(g,h,d):void 0,previousTargetId:k,currentTargetId:N?Ht(g,h,d):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&C&&we({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...w);continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let j=Ht(g,h,d),M=n.transforms[y];if(!M){console.warn("Transform not found:",y);continue}let ee={type:"container",id:j,...Pe(M,g),...It(g),children:[]};for(let P of b){let W=Qo({id:`${j}-${P.id}`,item:P,resources:n});W&&ee.children.push(W)}l.children.push(ee),we({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...w)}}return e},ci=(e,t)=>{if(!Yr.includes(e))throw new Error(`${t} must be one of: ${Yr.join(", ")}.`)},ol=(e,t)=>{let r=!!e.resourceId||hn(e),n=e.layer??(r?void 0:t?.layer)??Hr;return ci(n,`Visual item "${e.id}" layer`),n},il=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:c,activePersistentAnimations:a,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,saveSlots:g=[],visualLayer:y})=>{let{elements:b,animations:A}=e;if(t.visual&&n){let x=b.find(w=>w.id==="story");if(!x)return e;let C=t.visual.items,N=r?.visual?.items||[],k=Ee({variables:s,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i});y!==void 0&&ci(y,"visualLayer");for(let w of C){let j=N.find(H=>H.id===w.id),M=ol(w,j);if(y!==void 0&&M!==y)continue;if(Mc(w),w.text){let H=Yt(n,w),te={...structuredClone(w.text),id:`visual-${w.id}`,type:"text",...Pe(H,w)};Object.assign(te,It(w)),x.children.push(Oe(ce(te,k,{functions:Re}),n))}if(w.resourceId){let{images:H={},videos:te={},spritesheets:xe={}}=n,G=xe[w.resourceId];if(G){let K=Yt(n,w),oe=w.animationName;if(oe){let re=G.animations?.[oe];if(!re)throw new Error(`Animation '${oe}' not found in spritesheet resource '${w.resourceId}'`);let J=It(w),ie={id:`visual-${w.id}`,type:"spritesheet-animation",...Pe(K,w),width:w.width??G.width,height:w.height??G.height,alpha:J.alpha??w.alpha??1,src:G.fileId,atlas:G.jsonData,playback:{frames:re.frames,animationSpeed:w.animationSpeed??re.animationSpeed??.5,loop:w.loop??re.loop??!0}};J.blur&&(ie.blur=J.blur),x.children.push(structuredClone(ie))}}else{let K=H[w.resourceId]||te[w.resourceId];if(K){let oe=te[w.resourceId]!==void 0,re=Yt(n,w),J={id:`visual-${w.id}`,type:oe?"video":"sprite",src:K.fileId,width:K.width,height:K.height,...Pe(re,w)};Object.assign(J,It(w)),oe&&(J.loop=K.loop??!1,J.volume=K.volume??50),x.children.push(J)}}}if(w.resourceId){let{layouts:H={}}=n,te=H[w.resourceId];if(te){let xe=Yt(n,w),G={id:`visual-${w.id}`,type:"container",children:structuredClone(te.elements),...Pe(xe,w)};Object.assign(G,It(w));let K=ce(G,k,{functions:Re});x.children.push(Oe(Ve(K,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),n))}}let ee=Mo(j),P=Mo(w),W=Le({animationsDef:w.animations,resources:n,previousResourceId:ee,currentResourceId:P,previousTargetId:ee?`visual-${w.id}`:void 0,currentTargetId:P?`visual-${w.id}`:void 0,animationPath:`visual.items[${w.id}].animations`,idPrefix:w.id});we({animationInstances:W,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:a})&&A.push(...W)}}return e},it="dialogue-character-sprite",Wo=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,sl=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=Ke(e.elements);if(!a)return e;let l=t.dialogue?.character?.sprite,u=r?.dialogue?.character?.sprite,f=Wo(l),d=Wo(u),p=Le({animationsDef:l?.animations,resources:n,previousResourceId:d?it:void 0,currentResourceId:f?it:void 0,previousTargetId:d?it:void 0,currentTargetId:f?it:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!f)return l?.animations&&d&&we({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e;let h=n.transforms?.[l.transformId];if(!h)return console.warn("Transform not found:",l.transformId),e;let g={type:"container",id:it,...Pe(h),children:[]};for(let y of l.items){let b=Qo({id:`${it}-${y.id}`,item:y,resources:n});b&&g.children.push(b)}return a.children.push(g),we({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e},al=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:u,skipOnlyViewedLines:f,isLineCompleted:d,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:y,saveSlots:b=[]})=>{let{elements:A,animations:x}=e;if(!t.dialogue||o)return e;let C=A.find(k=>k.id==="story");if(!C)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:k={}}=n,w=k[t.dialogue.ui.resourceId];if(w){let j={elements:w.elements},M=Ee({variables:h,runtime:g,saveSlots:b,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:d,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:u,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:f,skipTransitionsAndAnimations:p}),ee={functions:Re},P=Kt(j,M,ee),W=ce(P,M,ee),H=Oe(Ve(W?.elements,{isLineCompleted:d,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(H))for(let te of H)C.children.push(te);else H&&C.children.push(H)}}sl(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let N=Le({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 we({animationInstances:N,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&x.push(...N),e},cl=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:c,runtime:a,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:b,animations:A}=e;if(t.choice&&n){let x=Ke(b);if(!x)return e;let C=n?.layouts[t.choice.resourceId];if(C&&C.elements){let k={elements:C.elements},w=ce(k,{...Ee({variables:c,runtime:a,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:u,isChoiceVisible:f??!!t.choice,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:Re}),j=on(Oe(Ve(w?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n));if(Array.isArray(j))for(let M of j)x.children.push(M);else j&&x.children.push(j)}let N=Le({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"});we({animationInstances:N,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&A.push(...N)}return e},ll=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:c,runtime:a,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:b,animations:A}=e;if(!y?.resourceId||!n)return e;let x=Ke(b);if(!x)return e;let C=n?.layouts?.[y.resourceId];if(!C)return console.warn(`Form layout not found: ${y.resourceId}`),e;let N={id:"form-container",type:"container",x:0,y:0,children:C.elements||[]},k={...Ee({variables:c,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},w=ce(N,k,{functions:Re}),j=an(Oe(Ve(sn(w,y),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n),y);j&&x.children.push(j);let M=Le({animationsDef:y.animations,resources:n,previousResourceId:r?.form?.resourceId,currentResourceId:y.resourceId,previousTargetId:r?.form?.resourceId?"form-container":void 0,currentTargetId:y.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return we({animationInstances:M,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(...M),e},ul=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:u,form:f,saveSlots:d=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=el(h.keyboard,h.keyup);if(g&&Object.keys(g).length>0&&(e.global.keyboard=g),!Array.isArray(h.elements)||h.elements.length===0)return e;let y=Ke(e.elements);if(!y)return e;let b={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(ai({container:b,resources:r,templateData:Ee({variables:n,runtime:o,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:u,form:f,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:c,skipTransitionsAndAnimations:p})),e},fl=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Ke(i))return e;let a=t.bgm,l=!Array.isArray(a.sounds),u=l?a.resourceId?[{id:"default",resourceId:a.resourceId,loop:a.loop??!0,volume:a.volume,startDelayMs:a.startDelayMs??0}]:[]:a.sounds,f=[];if(l||Qt(u,"BGM sound"),u.forEach(p=>{let h=r.sounds?.[p.resourceId];h&&f.push(yn({id:At("bgm",l?"default":p.id),sound:p,resource:h,defaultLoop:!0}))}),f.length===0)return e;let d=Ee({variables:o,runtime:n}).runtime;s.push(gn({id:zc,volume:mn(d,"musicVolume",l?Ge:a.volume??Ge),muted:a.muted,pan:a.pan,children:f,runtime:d}))}return e},dl=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx,s=!Array.isArray(i.channels),c=s?[{id:Wc,sounds:i.items??[]}]:i.channels;s||Qt(c,"SFX channel"),c.forEach(a=>{let l=[];s||Qt(a.sounds,"SFX sound",`SFX channel "${a.id}"`),a.sounds.forEach((u,f)=>{let d=r.sounds?.[u.resourceId];d&&l.push(yn({id:s?At("sfx","default",f,u.id):At("sfx",a.id,u.id),sound:u,resource:d}))}),l.length!==0&&o.push(gn({id:At("channel","sfx",a.id),volume:mn(n,"soundVolume",a.volume??Ge),muted:a.muted,pan:a.pan,children:l,runtime:n}))})}return e},pl=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},hl=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let c=t.voice,a=!Array.isArray(c.sounds),l=a?c.resourceId?[{id:"default",resourceId:c.resourceId,loop:c.loop??!1,volume:Ge,startDelayMs:c.startDelayMs??0}]:[]:c.sounds,u=[];if(a||Qt(l,"Voice sound"),l.forEach(d=>{let p=pl(r,n,d.resourceId);p&&u.push(yn({id:At("voice",n,a?"default":d.id),sound:d,resource:p}))}),u.length===0)return e;let f=Ee({variables:i,runtime:o}).runtime;return s.push(gn({id:qc,volume:a?c.volume??oi(f,"soundVolume"):mn(f,"soundVolume",c.volume??Ge),muted:c.muted,pan:c.pan,children:u,runtime:f})),e},ml=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:u,form:f,saveSlots:d=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:b}=e;if(t.layout){let N=Ke(y);if(!N)return e;let k=n.layouts[t.layout.resourceId];if(!k)return e;Array.isArray(k.transitions)&&!p&&!h&&un({animations:b,transitions:k.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let w={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:k.elements||[]};N.children.push(ai({container:w,resources:n,templateData:Ee({variables:o,runtime:i,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:u,form:f,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:c,skipTransitionsAndAnimations:h}))}let A=r?.layout?.resourceId,x=t.layout?.resourceId,C=Le({animationsDef:t.layout?.animations,resources:n,previousResourceId:A,currentResourceId:x,previousTargetId:A?`layout-${A}`:void 0,currentTargetId:x?`layout-${x}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return we({animationInstances:C,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(...C),e},gl=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=t?.screen?.animations;if(!a)return e;let l=r!=null,u=Le({animationsDef:a,resources:n,previousResourceId:l?"story":void 0,currentResourceId:"story",previousTargetId:l?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return we({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...u),e},yl=(e,{presentationState:t})=>{let r=Ke(e.elements);return!r||!t?.screen||Object.assign(r,ri(t.screen)),e},bl=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:u,overlayStack:f=[],dialogueHistory:d=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;return f&&f.length>0&&f.forEach((x,C)=>{let N=r.layouts[x.resourceId];if(!N){console.warn(`Overlay layout not found: ${x.resourceId}`);return}Array.isArray(N.transitions)&&(y||un({animations:A,transitions:N.transitions,defaultTargetId:`overlayStack-${C}`,idPrefix:`overlayStack-${C}`,animationPathPrefix:`overlayStack[${C}]`}));let k={id:`overlayStack-${C}`,type:"container",x:0,y:0,children:[ii({id:`overlayStack-${C}-blocker`,screen:h}),...N.elements||[]]},w=si(d,r.characters,n),j=Ee({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:u,historyDialogue:w,characters:r.characters||{},skipTransitionsAndAnimations:y}),M=ce(k,j,{functions:Re}),[ee,...P]=M.children||[],W=Oe(Ve({...M,children:P},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...W,children:ee?[ee,...W.children||[]]:W.children})}),e},Il=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:u,form:f,confirmDialog:d,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;if(!d?.resourceId)return e;let x=r.layouts?.[d.resourceId];if(!x)return console.warn(`ConfirmDialog layout not found: ${d.resourceId}`),e;Array.isArray(x.transitions)&&!y&&un({animations:A,transitions:x.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let C={id:"confirmDialog",type:"container",x:0,y:0,children:[ii({id:"confirmDialog-blocker",screen:h}),...x.elements||[]]},N=si(p,r.characters,n),k=ce(C,Ee({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:u,form:f,confirmDialog:d,historyDialogue:N,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:Re}),[w,...j]=k.children||[],M=Oe(Ve({...k,children:j},{isLineCompleted:g,skipMode:c,skipTransitionsAndAnimations:y}),r);return b.push({...M,children:w?[w,...M.children||[]]:M.children}),e},xt=e=>(t,r)=>il(t,{...r,visualLayer:e}),Al=xt(_e.BEHIND_BACKGROUND),wl=xt(_e.BEHIND_CHARACTER),El=xt(_e.BEHIND_DIALOGUE),xl=xt(_e.BEHIND_CHOICE),vl=xt(_e.FOREGROUND),li=e=>Mt(tl,[ul,Al,rl,wl,nl,El,al,xl,cl,ll,ml,vl,yl,gl,fl,dl,hl,bl,Il])(e);function ui(e,t=""){let r=[],n=e.length,o=0,i=0,s=-1,c=()=>{let a=0,l=0,u;do u=parseInt(e[o++],36),a+=(u&15)<<l,l+=4;while(u&16);return a};for(;o<n;){let a=s+1+c();s=a+c(),r.push([a,s,t?parseInt(t[i++],36):0])}return r}function fi(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 di="090001000h1v5g2903000hl2v6jh16ng1s210111110o35aa10u2k1g10l6600152113h2010u1q1r5aq3890o13181214r22k3158q2n1000v100h1k20000001207030001160721k171001h1j11610332010010321210090411021c1c02100o301201412230u1130b100h1j116111420120411001100k11l10051001h1j11611142011000321210072411021d0g10r3000000132120090o200200g1j11f2012031213711271t1001o301001000001121371b1f0c101h1l2011001031212000080a1t1001m40400102101600i11t301006c7i601008b6p41r10101041h3d0004115a1j290p3q223000511010100g1501010302003172030c0010016000e0i6v50n40n5tl12ir33s12t11u11cj30100060700010a90t220000l71i20m7203010241000502rd101004k300000006101027050920g3t22bk1300616g209030207u18c1000t10003010501b2o20000102000004g37070101o921c000640602001mcv3rg20000001o16d0c0m1fg6g2h30m10q55f1vm11c0ma0p1a42nc0ne1a090q3314902021204020112030318250105bb1201110i1021i15101131502141b15120511011k1155132040202510201010603060a1f02040104210b1g3290e0e0kn11vs12j11j3040pp12t80g6v1vmo7319g21g51gh103040n11010040j51i3f01q1h1d0m27p1a0000cs13200523j200010301010100v140018a4q2501010101c08000i1f12601011g3012215110u1a0001015000pcq181000100011000iji5fvc0u91g5bhg20ie0l94lo6002115303121s12240la1tj23h44tj11t45m4ah33q700000l3ep2021a200t220301012040a0i320j2040007f00100r20c100g3208000011531000s520201036020t900207l1101n311000000321210090a12634b910201l22001051020120011020000e1i520701020000n10h5001050000010000010001re0010323010001r11i520701000001q6000000107l600000230004gg12080001lc62027111n1000411230000000000t820321030030r10090n205001380800501020n2050c0001mc00002000000nc006150000i5l1100600010001q753011160000i441111000000rl11019100000c1h201043102n10ltk1f006eoss2b0202gs94r36si2033ku101m373h50b1rqs4113sli1t22m1uh2435070726u13k92rr7m34h380e0m141egl561g1261114k60ga6nn10t33sv13uf1jf0207150qt16t66pr60n23k6bf1f0e1l29g71c1e029j1n30p11ea0k1028139m16rb2v621122i52213040tf1u3b51n17127c0232041d120819052c28220104060306l5g3l4572g130152cqdl2c3o37a5o27u11c32d9m2cu2191obo57eh9gg1tv3",pi="262122424333333393233393339333333333393393bf3b3b3b3b3f3f3bffff33b3bb33ff3f33b3b3333333bffff3b33bb33f33bffff33b3bb33ff3f33b3bbb333b3ff33b333f33b3b3b3b3333b3bf33b3bb39333b33b33b3b3b333b333333b3b33333f3b33b3ffb3f3fff3f3b33f35dc33333f3b3b3b33323333b3bb3b33b3fb3b3333b33333bff3b3f33bfb3b3ff3b3b3b3b3b333b333b3323e22442344444444444444444444444444444444444444444444444444444444444444444444444444444443333333333b3b3bb33333b353bff3b3b3b3f3ff3b3b333bfff3f33333fb3bb3fb3b3bb33232333f333fff333333333b3b3333bb3b39393f3b3fbf33bb3b393b3b3b3333b33b33b3bbb33b33ffff3b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b3fffff3bb39b9b3b33b3bf3f3b33f3b3f93b33b3b3bb33b33b3b3b3333393b3b3b33b39bffb3b332333b333dd3b3333233332333333333333333333333333333444444444444a4444444444444344444444444444444444444444444444444444444444",hi="0001000000010010000000100000000000000000000000000001000000010014000100000001001000010101100101100000000000000000000100000001111000010000000110101001110111111111000100000021001000010000000100100001000000011010000100000001111000013000000100140001000000010010";var mi=65535,bn=40960,er=126976,bi=new Uint8Array(12288),Ii=new Uint8Array(3072),Ai=new Uint8Array(2816),wi,Ei;{let e=(o,i,s,c,a)=>{let l=i+o.length-1;for(let u=s<i?i:s,f=c>l?l:c;u<=f;u++)o[u-i]=a},t=new Uint32Array(320),r=new Uint32Array(320),n=0;for(let[o,i,s]of ui(di,pi))e(bi,0,o,i,s),e(Ii,bn,o,i,s),e(Ai,er,o,i,s),i>=65040&&!(o>=er&&i<=129791)&&(t[n]=o,r[n++]=i<<5|s);wi=t.slice(0,n),Ei=r.slice(0,n)}function gi(e){return e<12288?bi[e]:e<bn?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?Ii[e-bn]: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>=er&&e<129792?Ai[e-er]:e>=917504?e>921599?0:e>=917536&&e<917632||e>=917760&&e<918e3?3:2:fi(e,wi,Ei)}var xi=Uint8Array.from(hi,Number);function Sl(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 yi(e,t,r){switch(t){case 3:return e&24?r===8204?e&6:(e&24)===16||Sl(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*vi(e){let t=e.length;if(t===0)return;let r=e.codePointAt(0),n=r>mi?2:1,o=gi(r),i=50200>>o&1?yi(0,o,r):0,s=0,c=r,a=o;for(;n<t;){r=e.codePointAt(n);let l=r>mi?2:1,u=gi(r),f=xi[o<<4|u],d;f===0?d=!0:f===1?d=!1:f===2?d=!(i&1):f===3?d=!(i&4):d=(i&24)!==16,i=50200>>u&1&&(i!==0||u!==3)?yi(i,u,r):0,d&&(yield{segment:e.slice(s,n),index:s,input:e,_hd:c,_catBegin:a===15?0:a,_catEnd:o===15?0:o},s=n,c=r,a=u),n+=l,o=u}yield{segment:e.slice(s),index:s,input:e,_hd:c,_catBegin:a===15?0:a,_catEnd:o===15?0:o}}function*Si(e){for(let t of vi(e))yield t.segment}{let e=vi("_");xi._keep=[e,e.next()]}var Ci=1e3,Cl=1,_l=60,Rl=3,Ol=.5,Ll=2e4,$l=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,kl=/^\s+$/u,_i,Dl=e=>{let t=`${e??""}`.normalize("NFC"),r=globalThis.Intl?.Segmenter;return typeof r!="function"?Array.from(Si(t)):(_i??=new r(void 0,{granularity:"grapheme"}),Array.from(_i.segment(t),({segment:n})=>n))},Tl=e=>Dl(e).reduce((t,r)=>kl.test(r)?t+Ol:$l.test(r)?t+Rl:t+1,0),Ri=({text:e="",baseDelay:t=Ci,speed:r=Cl}={})=>{let n=Number.isFinite(t)?Math.max(0,t):Ci,o=Number.isFinite(r)&&r>0?r:1,i=Tl(e)*_l/o,s=Math.max(n,Ll);return Math.min(n+i,s)};var tr={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Di=1,ir="choice",rr="form",sr=()=>({manual:{...tr.manual},auto:{...tr.auto},applyMode:tr.applyMode}),In=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...sr()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},T=e=>{let t=de(e)?Be(e):e;return structuredClone(t)},D=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ar=e=>String(e),Ti=()=>({sections:[],resources:[]}),Nl=e=>D(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Ti(),Pl=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Vl=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:Pl(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),jl=()=>({resourceId:void 0}),Fl=e=>{if(!D(e))return e;let t={...e};return Object.prototype.hasOwnProperty.call(t,"requireComplete")&&!Object.prototype.hasOwnProperty.call(t,"requireLineCompleted")&&(t.requireLineCompleted=t.requireComplete),delete t.requireComplete,t},An=(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}},Ni=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 c=r.get(s);if(c!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${c}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},Pi=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Vi=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Di)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Ml=(e,t={})=>{let r;try{r=Vi(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:Pi(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},Ul=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Ml(t,r)])),ji=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Nf(r));return t.length>0?t:void 0},Bl=e=>{!D(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!D(t))return;let r=ji(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},Oi=(e,t,r,n="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!D(e))throw new Error(`Malformed ${n}.${t}[${r}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${n}.${t}[${r}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${n}.sections[${r}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},zl=(e,t="viewedRegistry")=>{if(e===void 0)return Ti();if(!D(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let r=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Oi(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Oi(o,"resources",i,t);return[s.resourceId,s]})))}},Fi=(e,t,r)=>{if(!D(e))throw new Error(`Malformed save slot ${r}.`);let{sectionId:n,lineId:o}=e;if(typeof n!="string"||n.length===0)throw new Error(`Malformed save slot ${r}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${r}: missing lineId.`);let{sceneId:i,section:s}=An(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}},ql=(e,t,r)=>{if(!D(e)||!Array.isArray(e.timeline))return vt({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((c,a)=>{if(!D(c))return[];try{let l=Fi(c,r,`rollback.timeline[${a}]`),u=or({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:c.rollbackPolicy}),f=ji(T(c.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(n.length===0)return vt({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):n.length-1;(o<0||o>=n.length)&&(o=n.length-1);let i=n[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let c=n.findLastIndex(a=>a.sectionId===t.sectionId&&a.lineId===t.lineId);c>=0?o=c:(n.push(or({sectionId:t.sectionId,lineId:t.lineId})),o=n.length-1)}let s=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),o):0;return{currentIndex:o,isRestoring:!1,replayStartIndex:s,timeline:n}},Wl=(e,t,r)=>{if(!D(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=xn(t),o=Fi(e.pointers?.read,t,`contexts[${r}].pointers.read`);if(e.variables!==void 0&&!D(e.variables))throw new Error(`Malformed save slot contexts[${r}].variables entry.`);if(e.runtime!==void 0&&!D(e.runtime))throw new Error(`Malformed save slot contexts[${r}].runtime entry.`);let i=e.variables?rt(T(e.variables),t.resources?.variables??{}):{},s=ou({loadedContextRuntime:D(e.runtime)?T(e.runtime):{}}),c={currentPointerMode:"read",pointers:{read:o},configuration:D(e.configuration)?T(e.configuration):{},views:Array.isArray(e.views)?T(e.views):[],bgm:D(e.bgm)?T(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:ql(e.rollback,o,t)};return s&&(c.runtime=s),c},Hl=(e,t)=>{if(!D(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((r,n)=>Wl(r,t,n))}},Yl=(e,t)=>{if(!D(e))throw new Error("Malformed save slot.");let r=Vi(e.formatVersion);return{...e,formatVersion:r,state:Hl(e.state,t)}},Li=(e,t,{required:r=!1}={})=>{if(e===void 0){if(r)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let n=T(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},Gl=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Li(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Li(e.cancelActions,"cancelActions")}},at=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Kl=e=>(D(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),ct=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},Mi=e=>{if(!(!D(e)||!e.animations))return{animations:T(e.animations)}},Jl=(e,t)=>{let r=Mi(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},Xl=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},Ql=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},nr=e=>String(e??""),Ui=(e,t)=>{let r=nr(t);return e?.trim===!0?r.trim():r},Zl=e=>D(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>D(t)).map(([t,r])=>[t,{id:t,...T(r)}])):{},eu=(e,t)=>{if(!t||!D(e.global.formDrafts))return;let r=e.global.formDrafts[t];return D(r)?r:void 0},Bi=(e,t)=>{let r=Kl(e);D(r[t])||(r[t]={values:{},touched:{},errors:{},submitted:!1});let n=r[t];return D(n.values)||(n.values={}),D(n.touched)||(n.touched={}),D(n.errors)||(n.errors={}),typeof n.submitted!="boolean"&&(n.submitted=!1),n},wn=(e,t)=>{let r=Ui(e,t);return e?.required===!0&&r.length===0?"required":null},tu=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=le({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:qe(n.slice(0,o+1).map(i=>i.actions||{}))},ru=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=Xl(t),o=Ql(r,n);if(!n||!o)return null;let i=eu(e,o),s=Zl(t),c=lr({state:e}),a={},l=[],u={},f=!0;return Object.entries(s).forEach(([d,p])=>{let h=nr(c?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},d)?nr(i.values[d]):h,y=i?.touched?.[d]===!0,b=wn(p,g),A=i?.submitted||y?b:null,x=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,C={id:d,variableId:p.variableId,value:g,initialValue:h,valid:!b,error:A,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...x!==void 0?{maxLength:x}:{}};b&&(f=!1),a[d]=C,l.push(C),u[d]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:f,submitted:i?.submitted===!0,fields:a,fieldList:l,values:u,submitActions:{submitForm:{formKey:o,actions:T(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:T(t.cancelActions??{})}}}},Je=[],$i="line",En="interaction",or=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),xn=e=>{let{contextVariableDefaultValues:t}=Bt(e??{});return T(t)},zi=()=>({...T(bt)}),qi=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:T(r),hasLoadedValues:!1};if(!D(e))throw new Error(`Malformed ${n}.`);let o=T(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Wi(s,T(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},nu=({loadedGlobalRuntime:e={}})=>qi({loadedRuntime:e,runtimeIds:qr,defaults:We,path:"global.runtime"}).runtimeState,ou=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=qi({loadedRuntime:e,runtimeIds:Wr,defaults:zi(),path:"context.runtime"});return r?t:void 0},cr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},iu=e=>e.runtime?(Wr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=T(bt[t]))}),e.runtime):(e.runtime=zi(),e.runtime),su=e=>ko(e.global),au=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:su(e)}})},cu=e=>$o[e],lu=(e,t)=>{let r=cu(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}"`)},Wi=(e,t)=>{if(lu(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},Hi=(e,t,r)=>{let n=Wi(t,r);if(t in bt){let o=cr(e);if(!o)return n;let i=iu(o);return i[t]=n,n}return e.global[t]=n,n},Yi=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:T(e)},configuration:{},views:[],bgm:jl(),variables:xn(t),rollback:vt({pointer:e})}),lt=e=>e?(e.currentPointerMode="read",D(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,uu=(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=Yi({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,fu(e,{queueRender:t}),o},fu=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,at(e),ct(e),e.global.nextLineConfig=sr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},Gi=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},vt=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[or({sectionId:e.sectionId,lineId:e.lineId})]:[]}},Ze=(e,t={})=>{if(e?.rollback)return Gi(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=vt({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},vn=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=Ze(r);if(n.isRestoring)return;n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1));let o=n.timeline[n.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){n.currentIndex=n.timeline.length-1;return}n.timeline.push(or(t)),n.currentIndex=n.timeline.length-1},du=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=Je[Je.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)},pu=({state:e},t={})=>{let r=t?.source===$i?$i:En,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?(Je.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Je.push({checkpointIndex:o.currentIndex,source:r}),e)},hu=({state:e})=>(Je.pop(),e),Ce=(e,t,r)=>{let o=Je[Je.length-1]?.source??En;if(!Pf(t,o))return;let i=du(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:T(r)}))},ki=(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:c}of n){let a=e.projectData.resources?.variables?.[o],l=a?.scope,u=a?.type;if(Te(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);zt(l,o),qt(u,i,o),Fr(u,i,s,o,{roundTo:c}),l==="context"&&(r.variables[o]=Wt(r.variables[o],i,s,{roundTo:c}))}},mu=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{Vf(e,r,n)})},gu=(e,t)=>{let{sectionId:r,lineId:n}=t,s=le({state:e},{sectionId:r})?.lines?.find(c=>c.id===n)?.actions;s&&Object.entries(s).forEach(([c,a])=>{fs(e,c,a)})},Ki=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=Ze(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&pr({state:e}),e.global.skipMode&&Xe({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=xn(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=T(tr),e.global.overlayStack=[],at(e),ct(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let c=i;c<=t;c++)c>i&&In(e),gu(e,n.timeline[c]),mu(e,n.timeline[c]);let s=lt(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(c=>c?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},yu=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;Ni(t);let c=t.story.initialSceneId,a=t.story.scenes[c],l=a.initialSectionId,u=a.sections[l],f={sceneId:c,sectionId:l,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:d}=Bt(t),p={...d,...rt(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:zl(s,"accountViewedRegistry"),nextLineConfig:sr(),saveSlots:Ul(n),overlayStack:[],variables:p,...nu({loadedGlobalRuntime:i})},contexts:[Yi({pointer:f,projectData:t})]}},bu=({state:e})=>e.global.overlayStack||[],Iu=({state:e})=>e.global.pendingEffects,Ji=({state:e})=>e.global.skipMode,Au=({state:e})=>e.global.autoMode,Xi=({state:e})=>e.global.dialogueUIHidden,Qi=({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=le({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(f=>f.id===o),c=i.lines.slice(0,s+1),a=[],l={},u=gt({variables:{...e.global?.variables??{},...cr(e)?.variables??{}},runtime:He(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let f of c){let d=f.actions||{};if(l=qe([l,d]),!d.dialogue)continue;let p=l.dialogue||{},h=Ut({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:u}),g=Vl({sectionId:n,lineId:f.id,content:d.dialogue.append===!0?p.content:d.dialogue.content,dialogueState:p,characterName:h});if(d.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},wu=({state:e})=>e.global.confirmDialog??null,St=({state:e},{pointer:t}={})=>{let r=t??ye({state:e})?.pointer,n=tu({state:e,pointer:r});return ru({state:e,form:n.form,pointer:r})},Eu=({state:e},{pointer:t}={})=>!!St({state:e},{pointer:t}),be=({state:e},{pointer:t}={})=>{let r=St({state:e},{pointer:t});if(r)return{source:rr,formId:r.id,formKey:r.key};let n=Zi({state:e,pointer:t});return n?{source:ir,resourceId:n}:null},xu=({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 c=le({state:e},{sectionId:n});if(!c||!c.lines||!Array.isArray(c.lines))return s.lastLineId===o;let a=c.lines.findIndex(u=>u.id===s.lastLineId),l=c.lines.findIndex(u=>u.id===o);return a===-1||l===-1?s.lastLineId===o:l<=a},vu=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},Sn=({state:e},t)=>xu({state:e,registry:e.global.accountViewedRegistry},t),Su=({state:e},t)=>vu({registry:e.global.accountViewedRegistry},t),Cu=({state:e})=>e.global.nextLineConfig,Zi=({state:e,pointer:t}={})=>{let r=t??ye({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=le({state:e},{sectionId:n})?.lines||[],c=s.findIndex(l=>l.id===o);if(c<0)return;let a;for(let l of s.slice(0,c+1)){let u=l?.actions;if(u?.cleanAll&&(a=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){a=void 0;continue}let f=u.choice;if(f?.resourceId){a=f.resourceId;continue}f?.animations||(a=void 0)}return a},es=({state:e})=>!!Zi({state:e}),_u=({state:e})=>structuredClone(e),ts=({state:e})=>e.global.saveSlots,Ru=({state:e},t)=>{let r=t?.slotId,n=ar(r);return e.global.saveSlots[n]},Cn=({state:e})=>He(e),Ou=({state:e},t)=>Ne(e,t?.runtimeId),lr=({state:e})=>{let t={...e.global?.variables??{},...cr(e)?.variables??{}};return gt({variables:t,runtime:He(e),variableConfigs:e.projectData.resources?.variables??{}})},ye=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},le=({state:e},t)=>{let{sectionId:r}=t;return An(e.projectData,r).section},ur=({state:e})=>{let t=ye({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=le({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},rs=({state:e})=>{let{sectionId:t,lineId:r}=ye({state:e}).pointer,o=le({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===r),c=o.slice(0,i+1).map(l=>{let u=l.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return qe(c)},Lu=e=>{let t=ur({state:e})?.actions?.dialogue;if(t?.clear===!0||!Array.isArray(t?.content))return"";let r=lr({state:e});return t.content.map(n=>`${nt(n?.text,{variables:r})??""}`).join("")},fr=({state:e})=>Ri({text:Lu(e),baseDelay:Ne(e,"autoForwardDelay"),speed:Ne(e,"autoForwardSpeed")}),$u=({state:e})=>{let t=ns({state:e}),n=ur({state:e})?.actions??{},o=qe([t??{},n]);return Mr(t??{},o??{})},ku=({state:e},{sectionId:t})=>{let r=le({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},c=qe([o,s]),a=Mr(o,c);n.push({id:i.id,changes:a,presentationState:c}),o=Ur(c)}return n},Du=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=ku({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},ns=({state:e})=>{let{sectionId:t,lineId:r}=ye({state:e}).pointer,o=le({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===r);if(i<=0)return null;let c=o.slice(0,i).map(a=>{let l=a.actions||{},u={};return Object.keys(l).forEach(f=>{u[f]=l[f]}),u});return Ur(qe(c))},_n=({state:e},{slotsPerPage:t=6}={})=>{let o=((Cn({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let c=o+s,a=e.global.saveSlots&&e.global.saveSlots[ar(c)]||{};i.push({...a,slotId:c})}return{saveSlots:i}},Tu=ts,Nu=_n,Pu=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},Vu=({state:e},t={})=>{let r=rs({state:e}),n=ns({state:e}),o=ur({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:T(i)}:o,c=i?.animations&&n===null?{}:n,{sectionId:a}=ye({state:e}).pointer,{sceneId:l}=An(e.projectData,a),u=Cn({state:e}),f=t?.activePersistentAnimations??[],d=t?.restoredPersistentAnimations??[],p=St({state:e}),h=es({state:e}),g=lr({state:e}),{saveSlots:y}=_n({state:e}),b=Pu(e);return li({presentationState:r,previousPresentationState:c,currentLineActions:s,resources:e.projectData.resources,currentSceneId:l,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:ps({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:Qi({state:e}),saveSlots:y,variables:g,runtime:u,activePersistentAnimations:f,restoredPersistentAnimations:d})},ju=({state:e},t)=>(e.global.confirmDialog=Gl(t),e.global.pendingEffects.push({name:"render"}),e),Fu=({state:e})=>(e.global.confirmDialog&&(at(e),e.global.pendingEffects.push({name:"render"})),e),Mu=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Ce(e,"pushOverlay",t),e),Uu=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Ce(e,"popOverlay",void 0),e),Bu=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),Ce(e,"replaceLastOverlay",t),e),zu=({state:e})=>(e.global.overlayStack=[],at(e),ct(e),e.global.pendingEffects.push({name:"render"}),Ce(e,"clearOverlays",void 0),e),qu=e=>{e.global.autoMode&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.skipMode&&e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},dr=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,Jl(e,r),ct(e);let n=be({state:e},{pointer:t}),o=n?.source===ir,i=n?.source===rr;return n&&qu(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},Rn=(e,t,r)=>{t?.source!==ir||r||!e.global.skipMode||e.global.pendingEffects.push({name:"startSkipNextTimer"})},os=({state:e})=>(be({state:e})||(e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.autoMode=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.isLineCompleted&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:fr({state:e})}}),e.global.pendingEffects.push({name:"render"})),e),pr=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Wu=({state:e})=>{let t=e.global.autoMode;return be({state:e})&&!t||(t?pr({state:e}):os({state:e})),e},is=({state:e})=>(be({state:e})||(e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode=!0,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"startSkipNextTimer"}),e.global.pendingEffects.push({name:"render"})),e),Xe=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Hu=({state:e})=>{let t=Ji({state:e});return be({state:e})&&!t||(t?Xe({state:e}):is({state:e})),e},hr=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Ce(e,"showDialogueUI",void 0),e),ss=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Ce(e,"hideDialogueUI",void 0),e),Yu=({state:e})=>(Xi({state:e})?hr({state:e}):ss({state:e}),e),je=(e,t,r)=>(Hi(e,t,r),au(e),e.global.pendingEffects.push({name:"render"}),e),Ct=(e,t,r,n)=>{let o=Hi(e,t,r);return e.global.pendingEffects.push({name:"render"}),Ce(e,n,{value:o}),e},Gu=({state:e},t)=>je(e,"dialogueTextSpeed",t?.value),Ku=({state:e},t)=>je(e,"autoForwardDelay",t?.value),Ju=({state:e},t)=>je(e,"autoForwardSpeed",t?.value),Xu=({state:e},t)=>je(e,"skipUnseenText",t?.value),Qu=({state:e},t)=>je(e,"skipTransitionsAndAnimations",t?.value),Zu=({state:e},t)=>je(e,"soundVolume",t?.value),ef=({state:e},t)=>je(e,"musicVolume",t?.value),tf=({state:e},t)=>je(e,"muteAll",t?.value),rf=({state:e},t)=>Ct(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),nf=({state:e})=>{let t=Ne(e,"saveLoadPagination")+1;return Ct(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},of=({state:e})=>{let t=Ne(e,"saveLoadPagination")-1;return Ct(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},sf=({state:e},t)=>Ct(e,"menuPage",t?.value,"setMenuPage"),af=({state:e},t)=>Ct(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),cf=({state:e})=>(e.global.pendingEffects=[],e),lf=({state:e},t)=>(e.global.pendingEffects.push(t),e),as=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!Mi(n),i=le({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&&!uu(e,{queueRender:!o}))return e;let c=be({state:e});r&&e.global.skipMode&&Xe({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let u=lt(a),f=u.read;r||Qe(e,{sectionId:f?.sectionId,lineId:f?.lineId}),a.rollback||Ze(a,{compatibilityAnchor:!0}),u.read={sectionId:t,lineId:s.id},r?a.rollback=vt({pointer:u.read}):vn(e,{sectionId:t,lineId:s.id})}let{activeInteraction:l}=dr(e,a?.pointers?.read,{screenTransition:n});return Rn(e,c,l),!r&&e.global.autoMode&&!c&&!l&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e},uf=({state:e},t)=>as(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),cs=e=>(e.global.accountViewedRegistry=Nl(e.global.accountViewedRegistry),e.global.accountViewedRegistry),On=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(r=>({scope:r.scope,path:r.path,op:r.op,value:T(r.value)}))}})},ls=(e,t)=>{On(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:[]}}])},ff=(e,t,{sectionId:r,lineId:n})=>{if(!r||!n)return!1;let o=D(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===r);if(i){if(i.lastLineId===void 0)return!1;let s=le({state:e},{sectionId:r});if(s?.lines){let c=s.lines.findIndex(l=>l.id===i.lastLineId),a=s.lines.findIndex(l=>l.id===n);if(c===-1||a>c)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},Qe=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;ff(e,cs(e),t)&&ls(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},df=({state:e},t)=>(Qe(e,t),e.global.pendingEffects.push({name:"render"}),e),pf=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=cs(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),ls(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},us=({state:e},t)=>{let r=Fl(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,c=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,l=be({state:e});return!c&&!l&&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}}):!c&&a===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),Ce(e,"setNextLineConfig",t),e},hf=({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=ar(r),s=T(e.contexts);s?.forEach(l=>{lt(l),Gi(l.rollback),Bl(l.rollback)});let c={contexts:s},a={formatVersion:Di,slotId:Pi(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:c};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},mf=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=ar(r),o=e.global.saveSlots[n];if(o){let i=Yl(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=sr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,at(e),ct(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},gf=({state:e},t)=>{let{projectData:r}=t;Ni(r),e.projectData=r;let n=r?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=Bt(r??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...rt(e.global.variables,n)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...rt(s.variables,n)})}),at(e),ct(e),e.global.pendingEffects.push({name:"render"}),e},yf=({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&&!le({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=le({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(f=>f.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let a=be({state:e}),l=lt(o);l.read={sectionId:i,lineId:n};let{activeInteraction:u}=dr(e,l.read);return Rn(e,a,u),e},bf=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return hr({state:e}),e;let r=be({state:e});if(r?.source===ir&&t?.bypassChoice!==!0||r?.source===rr&&t?._interactionSource!==rr)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=ye({state:e})?.pointer,f=u?.sectionId,d=u?.lineId;f&&d&&Qe(e,{sectionId:f,lineId:d}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&!r&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:fr({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=ye({state:e})?.pointer,o=n?.sectionId,i=le({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],c=i?.lines||[],l=c.findIndex(u=>u.id===n?.lineId)+1;if(l<c.length){let u=c[l],f=!Ne(e,"skipUnseenText");if(e.global.skipMode&&f&&!Sn({state:e},{sectionId:o,lineId:u.id}))return Xe({state:e}),e;if(s&&!s.rollback&&Ze(s,{compatibilityAnchor:!0}),s){let h=lt(s),g=h.read?.lineId;g&&o&&Qe(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:u.id}}vn(e,{sectionId:o,lineId:u.id}),In(e);let{activeInteraction:d}=dr(e,{sectionId:o,lineId:u.id});Rn(e,r,d);let p=e.global.nextLineConfig;p?.auto?.enabled&&!d&&p.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}})}else e.global.autoMode&&pr({state:e}),e.global.skipMode&&Xe({state:e});return e},If=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=be({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:fr({state:e})}});let r=ye({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&Qe(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},Af=({state:e},t)=>as(e,{sectionId:t?.sectionId,screen:t?.screen}),wf=({state:e})=>{if(e.global.dialogueUIHidden)return hr({state:e}),e;if(be({state:e}))return e;let t=ye({state:e})?.pointer,r=t?.sectionId,n=le({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],c=i.findIndex(a=>a.id===t?.lineId)+1;if(c<i.length){let a=i[c],l=!Ne(e,"skipUnseenText");if(e.global.skipMode&&l&&!Sn({state:e},{sectionId:r,lineId:a.id}))return Xe({state:e}),e;if(o&&!o.rollback&&Ze(o,{compatibilityAnchor:!0}),o){let f=lt(o),d=f.read?.lineId;d&&r&&Qe(e,{sectionId:r,lineId:d}),f.read={sectionId:r,lineId:a.id}}vn(e,{sectionId:r,lineId:a.id}),In(e);let{activeInteraction:u}=dr(e,{sectionId:r,lineId:a.id});e.global.nextLineConfig.auto?.enabled&&!u&&e.global.nextLineConfig.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})}else e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},Ln=(e,t={})=>{let r=St({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},Ef=(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(Te(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return zt(n,t.variableId),qt(o,"set",t.variableId),{variableConfig:r,scope:n}},xf=(e,t)=>({id:e.id,key:e.key,valid:!0,values:T(t),fields:T(e.fields),fieldList:T(e.fieldList)}),vf=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=ye({state:e})?.pointer,r=t?.sectionId,n=t?.lineId;r&&n&&Qe(e,{sectionId:r,lineId:n})},Sf=({state:e},t={})=>{let r=Ln(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=Bi(e,r.key),i=nr(t.value),s=r.fields[n],c=wn(s,i);return o.values[n]=i,o.touched[n]=!0,c?o.errors[n]=c:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},Cf=({state:e},t={})=>{let r=Ln(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=Bi(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([f,d])=>{let p=Object.prototype.hasOwnProperty.call(n.values,f)?n.values[f]:d.value,h=wn(d,p);n.touched[f]=!0,h&&(i[f]=h),o[f]=Ui(d,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:T(i),form:{id:r.id,key:r.key,values:T(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let c=!1,a=[],l=[];Object.entries(r.fields).forEach(([f,d])=>{let{scope:p}=Ef(e,d),h=p==="context"?s.variables:e.global.variables,g=o[f];h[d.variableId]=Wt(h[d.variableId],"set",g),p==="context"&&(c=!0,l.push({variableId:d.variableId,op:"set",value:g})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${d.variableId}`,op:"set",value:T(h[d.variableId])})}),c&&Ce(e,"updateVariable",{id:"submitForm",operations:l}),On(e,a);let u=xf(r,o);return vf(e),delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},_f=({state:e},t={})=>{let r=Ln(e,t);return r?(delete e.global.formDrafts?.[r.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:r.id,key:r.key,values:T(r.values),fields:T(r.fields),fieldList:T(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},Rf=({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=[],c=[];return n.forEach(({variableId:a,op:l,value:u,roundTo:f})=>{let d=e.projectData.resources?.variables?.[a],p=d?.scope,h=d?.type;if(Te(d))throw new Error(`Cannot update computed variable: ${a}`);if(d?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);zt(p,a),qt(h,l,a),Fr(h,l,u,a,{roundTo:f});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:a,op:l,value:u};f!==void 0&&(y.roundTo=f),c.push(y)}g[a]=Wt(g[a],l,u,{roundTo:f}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:T(g[a])})}),i&&Ce(e,"updateVariable",{id:r,operations:c}),On(e,s),e.global.pendingEffects.push({name:"render"}),e},Of=e=>(t,r)=>e({state:t},r),Lf=e=>({variables:gt({variables:{...e.global?.variables??{},...cr(e)?.variables??{}},runtime:He(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:He(e)}),$f=e=>{if(!D(e))throw new Error("conditional action payload must be an object");if(!Array.isArray(e.branches))throw new Error("conditional action requires branches array");if(e.branches.length===0)throw new Error("conditional action requires at least one branch")},kf=(e,t,r)=>{if(!D(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!D(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==r-1)throw new Error("conditional else branch must be the last branch")},Df=(e,t)=>{$f(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(kf(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!mt(n.when,Lf(e)))){Object.entries(n.actions).forEach(([i,s])=>{fs(e,i,s)});return}}},Tf={conditional:{replayLine:Df},updateVariable:{recordSources:[En],replayLine:ki,replayRecorded:ki,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Of(us)}},mr=e=>Tf[e]??null,Nf=e=>mr(e)?.persistInSaveSlot===!0,Pf=(e,t)=>{let r=mr(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},Vf=(e,t,r)=>{mr(t)?.replayRecorded?.(e,r)},fs=(e,t,r)=>{mr(t)?.replayLine?.(e,r)},ds=({state:e},t)=>{let{offset:r}=t;if(r===void 0||typeof r!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let n=e.contexts[e.contexts.length-1];if(!n)return null;let o=n.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+r;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},ps=({state:e})=>ds({state:e},{offset:-1})!==null,jf=({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=Ze(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:Ki(e,i)},Ff=({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=Ze(o,{compatibilityAnchor:!o.rollback}),c=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===r&&a.lineId===n);if(c===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return c===i.currentIndex?e:Ki(e,c)},hs=e=>{let t=yu(e);return mo(t,{selectPendingEffects:Iu,selectSkipMode:Ji,selectAutoMode:Au,selectIsChoiceVisible:es,selectIsFormVisible:Eu,selectActiveInteraction:be,selectActiveForm:St,selectDialogueUIHidden:Xi,selectDialogueHistory:Qi,selectConfirmDialog:wu,selectIsLineAccountViewed:Sn,selectIsResourceAccountViewed:Su,selectNextLineConfig:Cu,selectSystemState:_u,selectSaveSlotMap:ts,selectSaveSlots:Tu,selectSaveSlot:Ru,selectRuntime:Cn,selectRuntimeValue:Ou,selectAllVariables:lr,selectCurrentPointer:ye,selectSection:le,selectCurrentLine:ur,selectPresentationState:rs,selectAutoForwardTimerDelay:fr,selectPresentationChanges:$u,selectSectionLineChanges:Du,selectSaveSlotPage:_n,selectCurrentPageSlots:Nu,selectRenderState:Vu,selectOverlayStack:bu,selectLineIdByOffset:ds,selectCanRollback:ps,startAutoMode:os,stopAutoMode:pr,toggleAutoMode:Wu,startSkipMode:is,stopSkipMode:Xe,toggleSkipMode:Hu,showDialogueUI:hr,hideDialogueUI:ss,toggleDialogueUI:Yu,setDialogueTextSpeed:Gu,setAutoForwardDelay:Ku,setAutoForwardSpeed:Ju,setSkipUnseenText:Xu,setSkipTransitionsAndAnimations:Qu,setSoundVolume:Zu,setMusicVolume:ef,setMuteAll:tf,setSaveLoadPagination:rf,incrementSaveLoadPagination:nf,decrementSaveLoadPagination:of,setMenuPage:sf,setMenuEntryPoint:af,showConfirmDialog:ju,hideConfirmDialog:Fu,resetStoryAtSection:uf,clearPendingEffects:cf,appendPendingEffect:lf,beginRollbackActionBatch:pu,endRollbackActionBatch:hu,addViewedLine:df,addViewedResource:pf,setNextLineConfig:us,saveSlot:hf,loadSlot:mf,updateProjectData:gf,sectionTransition:Af,jumpToLine:yf,nextLine:bf,markLineCompleted:If,rollbackToLine:Ff,rollbackByOffset:jf,pushOverlay:Mu,popOverlay:Uu,replaceLastOverlay:Bu,clearOverlays:zu,updateFormField:Sf,submitForm:Cf,cancelForm:_f,updateVariable:Rf,nextLineFromSystem:wf},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var Mf="route-engine",Uf="projectPersistence";var gs=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),ne=e=>Object.prototype.toString.call(e)==="[object Object]",ms="variables.",Bf=(e={})=>{let t=ne(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!ne(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)}:!ne(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},zf=(e={})=>{let t=ne(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!ne(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)}:!ne(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},qf=(e,t)=>{let r=zf(e),n=Bf(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let c=o.find(a=>a.sectionId===s.sectionId);if(!c){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(c.lastLineId!==void 0){if(s.lineId===void 0){delete c.lastLineId;return}c.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},ys=(e={})=>{let t=ne(e)?e:{};return{saveSlots:ne(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:ne(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:ne(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:ne(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:ne(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Wf=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!ne(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(ms)?t.path.slice(ms.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}].`)})},Hf=(e,t)=>{let r={};return Wf(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=qf(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},$n=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},Yf=e=>{let t=$n(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Gf=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},Kf=({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}".`))}}),Jf=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.`))}})},_t=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let c=o.transaction(t,"readwrite"),a=c.objectStore(t),l=a.get(r),u=!1,f=p=>{u||(u=!0,s(p))},d=()=>{u||(u=!0,i())};l.onerror=()=>{f(l.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},l.onsuccess=()=>{let p=ys(l.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...gs(),...p,...h},y=a.put(g);y.onerror=()=>{f(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},c.oncomplete=()=>{d()},c.onerror=()=>{f(c.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},c.onabort=()=>{f(c.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},Xf=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),l=!1,u=d=>{l||(l=!0,i(d))},f=()=>{l||(l=!0,o())};a.onerror=()=>{u(a.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{f()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},kn=(e={})=>{let{indexedDB:t,databaseName:r=Mf,objectStoreName:n=Uf,namespace:o}=e,i=Gf(t),s=Yf(o),c=Kf({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let a=await Jf({databasePromise:c,objectStoreName:n,namespace:s});return{...gs(),...ys(a)}},clear:async()=>Xf({databasePromise:c,objectStoreName:n,namespace:s}),saveSlots:async a=>_t({databasePromise:c,objectStoreName:n,namespace:s,patch:{saveSlots:ne(a)?a:{}}}),saveGlobalDeviceVariables:async a=>_t({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:ne(a)?a:{}}}),saveGlobalAccountVariables:async a=>_t({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalAccountVariables:ne(a)?a:{}}}),saveGlobalRuntime:async a=>_t({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalRuntime:ne(a)?a:{}}}),applyScopedDataUpdates:async a=>_t({databasePromise:c,objectStoreName:n,namespace:s,patch:l=>Hf(l,a)})}},Qf=kn;var Zf=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),ed=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),bs="conditional",Dn="form",td=new Set(["submitForm","cancelForm"]),Rt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function Tn(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:c}=e,a=(I=new Map,S=Date.now())=>new Map(Array.from(I.entries()).filter(([,R])=>S<R.expiresAt).map(([R,F])=>[R,{animation:structuredClone(F.animation),startedAt:F.startedAt,expiresAt:F.expiresAt}])),l=(I=new Map)=>Array.from(I.values()).map(S=>structuredClone(S.animation)),u=(I=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,S])=>I<S.expiresAt))},f=()=>{for(;t.selectPendingEffects().length>0;){let I=[...t.selectPendingEffects()];t.clearPendingEffects();try{c(I)}catch(S){throw t.clearPendingEffects(),I.forEach(R=>{t.appendPendingEffect(R)}),S}}},d=({initialState:I,namespace:S})=>{t=hs(I),r=0,n=$n(S),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),f()},p=()=>n,h=()=>t.selectPresentationState(),g=()=>t.selectPresentationChanges(),y=I=>t.selectSectionLineChanges(I),b=(I={})=>{r+=1;let S=Date.now();u(S);let R=i.size>0,F=a(o,S),B=R?a(i,S):new Map,ve={...t.selectRenderState({activePersistentAnimations:l(F),restoredPersistentAnimations:l(B)}),id:`render-${r}`};return s.set(ve.id,{builtAt:S,persistentAnimationSessions:new Map([...B.entries(),...F.entries()]),usedRestoredPersistentAnimationSessions:R}),ve},A=(I={})=>b(I),x=(I={})=>b(I),C=I=>{let S=typeof I?.id=="string"&&I.id.length>0?I.id:null,R=S?s.get(S):null;S&&s.delete(S);let F=new Map;Yo(I?.animations).forEach(B=>{let he=Xt(B);if(!he)return;let ve=R?.persistentAnimationSessions?.get(he)??o.get(he),Ot=Math.max(0,Ko(B)),Pn=ve?.startedAt??R?.builtAt??Date.now();F.set(he,{animation:structuredClone(B),startedAt:Pn,expiresAt:Pn+Ot})}),o=F,R?.usedRestoredPersistentAnimationSessions&&(i=new Map)},N=()=>t.selectSystemState(),k=()=>t.selectSaveSlotMap(),w=I=>t.selectSaveSlot(I),j=I=>t.selectSaveSlotPage(I),M=()=>t.selectSkipMode(),ee=()=>t.selectAutoMode(),P=()=>t.selectRuntime(),W=()=>t.selectIsChoiceVisible(),H=()=>t.selectIsFormVisible(),te=()=>t.selectActiveInteraction(),xe=(I,S,R={})=>!Rt(S)||I!=="nextLine"?S:R.bypassChoice===!0?{...S,bypassChoice:!0}:R.interactionSource===Dn?{...S,_interactionSource:Dn}:S,G=(I,S)=>{if(!t[I])return;Zf.has(I)&&(ed.has(I)?i=a(o):i=new Map,o=new Map);let R=t[I](S);return f(),R},K=(I,S,R,F={})=>{if(I===bs){let B=re(R),he=Br({[I]:S},B);se(he[I],R,F);return}G(I,S)},oe=(I,S)=>{K(I,S)},re=I=>{if(!I)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(I,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:S,...R}=I,F=t.selectAllVariables?t.selectAllVariables():void 0;return{...R,_event:S,variables:F,runtime:t.selectRuntime?t.selectRuntime():{}}},J=I=>{if(!Rt(I))throw new Error("conditional action payload must be an object");if(!Array.isArray(I.branches))throw new Error("conditional action requires branches array");if(I.branches.length===0)throw new Error("conditional action requires at least one branch")},ie=(I,S,R)=>{if(!Rt(I))throw new Error(`conditional branch at index ${S} must be an object`);if(!Rt(I.actions))throw new Error(`conditional branch at index ${S} requires actions object`);if(!Object.prototype.hasOwnProperty.call(I,"when")&&S!==R-1)throw new Error("conditional else branch must be the last branch")},se=(I,S,R)=>{J(I);for(let F=0;F<I.branches.length;F+=1){let B=I.branches[F];ie(B,F,I.branches.length);let he=re(S);if(!(Object.prototype.hasOwnProperty.call(B,"when")&&!mt(B.when,he))){X(B.actions,S,R);return}}},v=(I,S)=>({...I??{},_form:S}),_=(I,S,R,F)=>{let B=G(I,S),he=B?.submitted===!0&&B.valid===!0,ve=B?.cancelled===!0;!he&&!ve||Rt(S.actions)&&X(S.actions,v(R,B.form),{...F,interactionSource:Dn})},V=(I,S,R,F)=>{let B=re(R),ve=Br({[I]:S},B)[I];if(I===bs){se(ve,R,F);return}let Ot=xe(I,ve,F);if(td.has(I)){_(I,Ot,R,F);return}G(I,Ot)},X=(I,S,R)=>{Object.entries(I).forEach(([F,B])=>{V(F,B,S,R)})},z=(I,S,R={})=>{t.beginRollbackActionBatch({source:R.rollbackSource});try{X(I,S,R)}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:K,handleInternalAction:oe,handleActions:z,selectRenderState:A,prepareRenderState:x,commitRenderState:C,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:N,selectSaveSlotMap:k,selectSaveSlot:w,selectSaveSlotPage:j,selectSaveSlots:k,selectRuntime:P,selectIsChoiceVisible:W,selectIsFormVisible:H,selectActiveInteraction:te,handleLineActions:()=>{let I=t.selectCurrentLine();return I?.actions?(z(I.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var Nn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},rd=80,As=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},nd=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&As({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},od=({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 c=n.delay??1e3;r.getElapsed()>=c&&(t.remove(i),r.setCallback(null),r.setElapsed(0),gr(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},id=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},sd=({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 c=n?.delay??rd;r.getElapsed()>=c&&(r.setElapsed(0),gr(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},ad=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},cd=({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 c=n.delay??1e3;r.getElapsed()>=c&&(r.setElapsed(0),gr(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},ld=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},ud=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},fd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},dd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},pd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},hd=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},Is={render:As,saveSlots:ud,saveGlobalDeviceVariables:fd,saveGlobalAccountVariables:dd,saveGlobalRuntime:pd,applyScopedDataUpdates:hd,handleLineActions:nd,startAutoNextTimer:od,clearAutoNextTimer:id,startSkipNextTimer:sd,clearSkipNextTimer:ad,nextLineConfigTimer:cd,clearNextLineConfigTimer:ld},md=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),gr=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},gd=(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(!md.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},yd=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:c})=>{let a=Nn(),l=Nn(),u=Nn(),f=s??null,d=Promise.resolve(),p=null,h=null,g=!1,y=0,b=v=>{if(o){o(v);return}console.error("RouteEngine persistence write failed.",v)},A=()=>{if(f)return f;let v=e();return f=kn({indexedDB:i,namespace:c??v?.getNamespace?.()}),f},x=v=>{d=d.catch(()=>{}).then(()=>{let _=A();return v(_)}).catch(_=>{b(_)})},C=v=>{let _=typeof v?.id=="string"&&v.id.length>0?v.id:null;y+=1,p=_,g=!1},N=()=>y,k=(v={})=>{if(v?.aborted===!0)return!1;let _=typeof v?.id=="string"&&v.id.length>0?v.id:null;return _?_!==p||_===h?!1:(h=_,!0):p!==null||g?!1:(g=!0,!0)},w=(v,_={})=>{if(v!=="renderComplete"||!k(_))return!1;let V=e();return gr(V,"markLineCompleted",{}),!0},j=new Set(["updateFormField","submitForm","cancelForm"]),M=new Set(["updateVariable"]),ee=v=>typeof v?.selectActiveInteraction=="function"?v.selectActiveInteraction():typeof v?.selectIsChoiceVisible=="function"&&v.selectIsChoiceVisible()?{source:"choice"}:null,P=v=>v?._formKey??v?.formKey,W=(v,_)=>P(v)===_?.formKey,H=(v,_)=>!v||typeof v!="object"||Array.isArray(v)?!1:v._interactionSource===_?.source,te=(v,_)=>H(v,_)?_.source==="form"?W(v,_):!0:!1,xe=(v,_)=>!v||typeof v!="object"||Array.isArray(v)||_?.source!=="form"?!1:W(v,_),G=(v={})=>Object.keys(v).some(_=>j.has(_)),K=(v={},_)=>Object.entries(v).some(([V,X])=>j.has(V)&&xe(X,_)),oe=(v={})=>Object.keys(v).length>0&&Object.keys(v).every(_=>M.has(_)),re=(v={},_)=>{let V=v?.actions;return _?.source==="form"?!V||typeof V!="object"||Array.isArray(V)?!1:K(V,_)?!0:G(V)?!1:oe(V):te(v,_)?!0:!V||typeof V!="object"||Array.isArray(V)?!1:Object.values(V).some(X=>te(X,_))},J=(v,_={})=>{if(!_?.actions)return!1;let V=ee(v);return!V||V.source==="choice"?!1:!re(_,V)},ie=({preprocessPayload:v,onEvent:_}={})=>async(V,X={})=>{let z=e();if(J(z,X))return _?.(V,X);let Q=await v?.(V,X)??X;if(J(z,Q))return _?.(V,Q);if(w(V,Q),Q?.actions){let I=Q?._event?{_event:Q._event}:Q?.event?{_event:Q.event}:void 0,S;Q?.bypassChoice===!0?S={bypassChoice:!0}:Q?._interactionSource&&(S={interactionSource:Q._interactionSource}),S?z.handleActions(Q.actions,I,S):z.handleActions(Q.actions,I)}return _?.(V,Q)},se=v=>{let _=e(),V=gd(v);V.forEach(z=>{if(!Is[z.name]&&!n)throw new Error(`Unhandled pending effect "${z.name}".`)});let X={engine:_,routeGraphics:t,ticker:r,autoTimer:a,skipTimer:l,nextLineConfigTimerState:u,trackRenderDispatch:C,getRenderDispatchCount:N,enqueuePersistenceWrite:x};for(let z of V){let Q=Is[z.name];if(Q){Q(X,z.payload);continue}n(z,X)}};return se.handleRouteGraphicsEvent=w,se.createRouteGraphicsEventHandler=ie,se},bd=yd;var Id=(e,t={})=>{let{resources:r={}}=t;return pn(e,r)};var Jp=Tn;export{Hr as DEFAULT_VISUAL_LAYER,ot as RENDER_LAYER,_e as VISUAL_LAYER,bd as createEffectsHandler,Qf as createIndexedDbPersistence,Jp as default,Ra as resolveComputedVariables,Id as resolveLayoutReferences};
|
package/package.json
CHANGED