@kosdev-code/kos-ui-sdk 0.1.0-dev.5264 → 0.1.0-dev.5344

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/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var jh=Object.defineProperty;var Bh=(t,e,s)=>e in t?jh(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var l=(t,e,s)=>(Bh(t,typeof e!="symbol"?e+"":e,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("loglevel"),M=require("mobx"),b=require("robot3"),Ke=require("date-fns"),T=require("@emotion/react/jsx-runtime"),tn=require("@emotion/styled"),Oa=require("react-dom"),tt=require("@emotion/react"),g=require("react"),sn=require("mobx-react-lite"),Hh=require("@use-gesture/react"),qr="method",Ia="topic",Bt="url",Ns="request-id",zr="response-id",rn="status",je="dst-addr",$a="src-addr",Ce="type",on="ordered",nn="tracker",Ca="Content-Type",Da="Cache-Control",xa="requestId",Aa=process.env.KOS_LOGIN_URL||"http://localhost",Ra=process.env.KOS_APP_PORT||"8080",Kh=`${Aa}:${Ra}`,gr="{MODEL_ID}";var Us=(t=>(t.SEND="/ws/log/msg/send",t.RECEIVED="/ws/log/msg/receive",t))(Us||{}),Pa=(t=>(t.MSG_RECEIVE="/mock/msg/receive",t))(Pa||{});const an="/kos/model/ready/";D.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const K=globalThis.kos.subscriptions,qh=()=>Symbol("eventKey");function cn(t){return K[t]&&Object.getOwnPropertySymbols(K[t]).length>0}function C(t,e){const s=qh();return K[t]||(D.debug(`Initializing subscription for ${t}`),K[t]={}),D.debug(`Subscribing to ${t} with id ${s.toString()}`),K[t][s]=e,{count:K[t]?Object.getOwnPropertySymbols(K[t]).length:0,unsubscribe:()=>(D.debug(`Unsubscribing from ${t} with id ${s.toString()}`),K[t]&&K[t][s]&&delete K[t][s],K[t]&&Object.getOwnPropertySymbols(K[t]).length===0&&delete K[t],{count:K[t]?Object.getOwnPropertySymbols(K[t]).length:0})}}function q(t,e,s={}){if(!K[t]||Object.getOwnPropertySymbols(K[t]).length===0)return D.debug(`No subscriptions for ${t}. Not publishing.`),{eventType:t,subscribers:0};const r=Object.getOwnPropertySymbols(K[t]).length;return Object.getOwnPropertySymbols(K[t]).forEach(o=>{if(s.sync){const n=s.sync;D.debug(`Performing sync publish for ${t} with sync id ${n}`),K[t][o]({body:e,headers:s}).then(i=>{D.debug(`Response recieved for ${n}, publishing back to source.`),q(n,i)})}else D.debug(`Performing async publish for ${t}`),K[t][o]({body:e,headers:s})}),{eventType:t,subscribers:r}}function zh(){D.warn("Resetting event bus"),Object.keys(K).forEach(t=>delete K[t])}function ka(t,e){const s=C(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function ln(t,e){return new Promise((s,r)=>{let o=null;const n=ka(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}const Vh=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:cn,once:ka,publish:q,reset:zh,subscribe:C,waitFor:ln},Symbol.toStringTag,{value:"Module"}));function Vr(t,e){const s=C(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function Gr(t,e){return new Promise((s,r)=>{let o=null;const n=Vr(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}function La(t,e){const s=t.map(r=>Gr(r,e));return Promise.all(s)}function Fa(t,e){return new Promise((s,r)=>{const o=[];let n=null,i=!1;const a=()=>{o.forEach(c=>c()),n&&clearTimeout(n)};t.forEach(c=>{const u=Vr(c,d=>{i||(i=!0,a(),s({eventType:c,data:d}))});o.push(u)}),e&&(n=setTimeout(()=>{i||(i=!0,a(),r(new Error(`Timeout waiting for any event: ${t.join(", ")}`)))},e))})}function Na(t,e,s){return C(t,o=>{o&&e(o)&&s(o)}).unsubscribe}function Ua(t,e,s){return C(t,o=>{if(o){const n=e(o);s(n)}}).unsubscribe}function ja(t,e,s){let r=null;const o=C(t,n=>{r&&clearTimeout(r),r=setTimeout(()=>{s(n)},e)});return()=>{r&&clearTimeout(r),o.unsubscribe()}}function Ba(t,e,s){let r=0,o=null;const n=C(t,i=>{const a=Date.now(),c=a-r;c>=e?(r=a,s(i)):o||(o=setTimeout(()=>{r=Date.now(),s(i),o=null},e-c))});return()=>{o&&clearTimeout(o),n.unsubscribe()}}function Ha(t,e,s){let r=[],o=null;const n=()=>{r.length>0&&(s([...r]),r=[])},i=C(t,a=>{a&&(r.push(a),o||(o=setTimeout(()=>{n(),o=null},e)))});return()=>{o&&(clearTimeout(o),n()),i.unsubscribe()}}function un(t,e=1){const s=[];return C(t,r=>{r&&(s.push(r),s.length>e&&s.shift())}),{subscribe:r=>(s.forEach(o=>r(o)),C(t,r))}}function Ka(t,e){const s=t.map(r=>C(r,o=>{o&&e(r,o)}));return()=>{s.forEach(r=>r.unsubscribe())}}function qa(t,e){let s=t;const r=[],o=new Set;return Object.values(e).forEach(n=>{Object.keys(n).forEach(i=>{o.add(i)})}),o.forEach(n=>{const{unsubscribe:i}=C(n,a=>{const c=e[s];c&&c[n]&&(s=c[n](a))});r.push(i)}),{get state(){return s},unsubscribe:()=>{r.forEach(n=>n())}}}function za(t,e,s,r){const o=Gr(e,r);return q(t,s),o}async function*Va(t){const e=[],s=[],r=C(t,o=>{o&&(s.length>0?s.shift()(o):e.push(o))});try{for(;;)e.length>0?yield e.shift():yield await new Promise(o=>{s.push(o)})}finally{r.unsubscribe()}}const Gh={once:Vr,waitFor:Gr,waitForAll:La,race:Fa,filter:Na,map:Ua,debounce:ja,throttle:Ba,buffer:Ha,replay:un,merge:Ka,stateMachine:qa,request:za,eventIterator:Va},Yh=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:Gh,buffer:Ha,debounce:ja,eventIterator:Va,filter:Na,map:Ua,merge:Ka,once:Vr,race:Fa,replay:un,request:za,stateMachine:qa,throttle:Ba,waitFor:Gr,waitForAll:La},Symbol.toStringTag,{value:"Module"}));async function Yr(t,e){const{getCurrentState:s,transformState:r,shouldUseFetchedState:o,timeout:n}=e,i=ln(t,n),a=await s(),c=r?r(a):a;return o&&o(c)?(i.catch(()=>{}),c):await Promise.race([i,new Promise(d=>{setTimeout(()=>d(c),100)})])}function Ga(t,e,s){const{getCurrentState:r,transformState:o}=s;let n=!1;const i=C(t,a=>{a&&(n=!0,e(a))});return Promise.resolve(r()).then(a=>{const c=o?o(a):a;n||e(c)}).catch(a=>{console.error("Failed to fetch initial state:",a)}),i.unsubscribe}function Ya(t,e){let s;const r=new Set,o=async()=>{try{typeof e=="string"?s=await(await fetch(e)).json():s=await e(),r.forEach(a=>a(s))}catch(a){throw console.error("Failed to fetch initial state:",a),a}};C(t,a=>{a!=null&&a.body&&(s=a.body,r.forEach(c=>c(s)))});let n=!1;const i=()=>{n||(n=!0,o())};return{get state(){return s},async getState(){return i(),s===void 0&&await new Promise(a=>{const c=()=>{s!==void 0?a():setTimeout(c,10)};c()}),s},subscribe(a){return i(),r.add(a),s!==void 0&&a(s),()=>{r.delete(a)}},async refresh(){return await o(),s}}}async function dn(t,e){if(typeof t=="string")return Yr(t,e);const s=t,{getCurrentState:r,shouldUseFetchedState:o,timeout:n}=e,i=await r(),a=e.transformState?e.transformState(i):i;if(o&&o(a))return a;const c=s.map(d=>ln(d,n)),u=await Promise.all(c);return u[u.length-1]}function Wa(t,e,s){const{fetchMissedEvents:r,checkInterval:o=3e4,deduplicateById:n}=s,i=new Set,a=C(t,async u=>{if(u){if(n){const d=n(u);if(i.has(d))return;i.add(d),i.size>1e3&&Array.from(i).slice(0,500).forEach(f=>i.delete(f))}await e(u)}}),c=setInterval(async()=>{try{const u=await r(),d=Array.isArray(u)?u:[u];for(const h of d)if(n){const f=n(h);i.has(f)||(i.add(f),await e(h))}else await e(h)}catch(u){console.error("Failed to fetch missed events:",u)}},o);return()=>{a.unsubscribe(),clearInterval(c)}}function Qa(t){const{connectEvent:e,disconnectEvent:s,errorEvent:r,dataEvent:o,fetchInitialState:n,reconnectDelay:i=5e3}=t,a={state:"disconnected",data:void 0,async waitForConnection(d){if(a.state==="connected"&&a.data)return a.data;const h=await Yr(e,{getCurrentState:n,shouldUseFetchedState:f=>!!f,timeout:d});return a.state="connected",a.data=h,u(),h},subscribe(d){return c.add(d),d(a),()=>{c.delete(d)}},async reconnect(){a.state="connecting",u();try{const d=await n();a.state="connected",a.data=d,u()}catch{a.state="error",u(),setTimeout(()=>{a.state==="error"&&a.reconnect()},i)}}},c=new Set,u=()=>{c.forEach(d=>d(a))};return C(e,d=>{a.state="connected",d!=null&&d.body&&(a.data=d.body),u()}),C(s,()=>{a.state="disconnected",u(),setTimeout(()=>{a.state==="disconnected"&&a.reconnect()},i)}),r&&C(r,()=>{a.state="error",u()}),o&&C(o,d=>{d!=null&&d.body&&a.state==="connected"&&(a.data=d.body,u())}),a.reconnect(),a}const Wh={waitForOrGetState:Yr,subscribeWithInitialState:Ga,createStatefulEventStream:Ya,waitForAllWithState:dn,createResilientEventHandler:Wa,createConnectionStateManager:Qa},Qh=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:Wh,createConnectionStateManager:Qa,createResilientEventHandler:Wa,createStatefulEventStream:Ya,subscribeWithInitialState:Ga,waitForAllWithState:dn,waitForOrGetState:Yr},Symbol.toStringTag,{value:"Module"})),Zh=(t,e=0)=>{if(!+t)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,r=e<0?0:e,o=["bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(t)/Math.log(s)),i=parseFloat((t/Math.pow(s,n)).toFixed(r)),a=o[n];return{value:i,scale:a,toString:()=>`${i} ${a}`}};function hn(t){let e="pending",s;const r=t.then(n=>{e="success",s=n},n=>{e="error",s=n});return{read:()=>{switch(e){case"pending":throw r;case"error":throw s;default:return s}}}}function lt(){return"xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}function Xh(t,e){e.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(r=>{const o=Object.getOwnPropertyDescriptor(s.prototype,r);Object.defineProperty(t.prototype,r,o)})})}function Jh(t,e){const s=t??[],r=e??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const fn=(t,e)=>{const s=t.map(n=>n.id);return e.map(n=>n.id).filter(n=>!s.includes(n))},Za=t=>t,pn=t=>t,ef=({container:t,onAddItem:e,onUpdateItem:s,onRemoveItem:r=Za,idMapper:o=pn})=>n=>{const i=n.map(o),c=fn(i,t.data).map(r).filter(Boolean);t.removeAll(c);const u=i.map(d=>{const h=t.getModel(d.id);return h&&s?s(d,h):e(d)}).filter(Boolean);t.addAll(u)},tf=({container:t,onAddItem:e,onRemoveItem:s=Za,idMapper:r=pn})=>o=>{const n=o.map(r);fn(n,t.models).forEach(s),n.forEach(e)},sf=({items:t,onAddItem:e,onRemoveItem:s,idMapper:r=pn})=>o=>{const n=o.map(r);fn(n,t).forEach(s),n.forEach(e)},rf=(t,e="parent-")=>{let s=t;return s.startsWith(e)&&(s=s.replace(e,"")),s},Di=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),xi=[{amount:60,name:"seconds"},{amount:60,name:"minutes"},{amount:24,name:"hours"},{amount:7,name:"days"},{amount:4.34524,name:"weeks"},{amount:12,name:"months"},{amount:Number.POSITIVE_INFINITY,name:"years"}];function Xa(t){let e=(t.getTime()-Date.now())/1e3;for(let s=0;s<=xi.length;s++){const r=xi[s];if(Math.abs(e)<r.amount)return Di.format(Math.round(e),r.name);e/=r.amount}return Di.format(Math.round(e),"years")}const gn=t=>t%4===0&&t%100!==0||t%400===0,mn=(t,e)=>[31,gn(t)?29:28,31,30,31,30,31,31,30,31,30,31][e],Ja=(t,e)=>{const s=new Date(t),r=t.getDate();return s.setDate(1),s.setMonth(s.getMonth()+e),s.setDate(Math.min(r,mn(s.getFullYear(),s.getMonth()))),s},ec=(t,e)=>{const s=new Date(t);return s.setDate(s.getDate()+e),s},$t="en-US",tc={short:{year:"numeric",month:"2-digit",day:"2-digit"},medium:{year:"numeric",month:"short",day:"2-digit"},long:{year:"numeric",month:"long",day:"numeric"},full:{year:"numeric",month:"long",day:"numeric",weekday:"long"}},sc={short:{hour:"2-digit",minute:"2-digit",hour12:!0},medium:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0},long:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZoneName:"short"},full:{hour:"2-digit",minute:"2-digit",hour12:!0,timeZoneName:"long"}},rc=(t,{dateStyle:e="short",locales:s=$t}={dateStyle:"short",locales:$t})=>{const r=e==="short"?tc.short:{dateStyle:e};return new Intl.DateTimeFormat(s,r).format(t)},oc=(t,{locales:e=$t,timeStyle:s="short"}={locales:$t,timeStyle:"short"})=>{const r=sc[s];return new Intl.DateTimeFormat(e,r).format(t)},nc=(t,{dateStyle:e="short",locales:s=$t,timeStyle:r="short"}={dateStyle:"short",locales:$t,timeStyle:"short"})=>{const o={...e&&tc[e],...r&&sc[r]};return new Intl.DateTimeFormat(s,o).format(t)},of=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:ec,addMonthsToDate:Ja,formatDate:rc,formatDateSince:Xa,formatDateTime:nc,formatTime:oc,getDaysInMonth:mn,isLeapYear:gn},Symbol.toStringTag,{value:"Module"}));function ic(t,e,s=300){let r;return(...o)=>{clearTimeout(r),r=setTimeout(()=>{e.apply(t,o)},s)}}const ee="canvas-renderer",mo=new Map,Ai=new Map,yo=new Map,bo=new Map,js=(t,e)=>{ac[t]=e},ac={indexExtension:{registerIndexExtension:(t,e)=>{const s=bo.get(t)||{};Object.assign(s,e),bo.set(t,e)},loadIndexExtensions:t=>bo.get(t)||{}},loader:{registerLoader:(t,e)=>{Ai.set(t,e)},executeLoader:async(t,e)=>{const s=Ai.get(t);if(s)return await s(e)}},propertyMapper:{registerPropertyMapper:(t,e)=>{yo.set(t,e)},hasMapper:t=>yo.has(t),executeMapper:(t,e,s)=>{const r=yo.get(t);return r?r(e,s):""}},dataMapper:{registerDataMapper:(t,e)=>{const s=mo.get(t)||[];s.push(e),mo.set(t,s)},executeMapper:async(t,e,s)=>{const r=mo.get(t);if(!r)return{};const o={};for(const n of r){const i=await n(e,s);Object.assign(o,i)}return o}},canvas:{registerRenderer:(t,e)=>{if(!$[ee]){console.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${t}".`);return}$[ee].register(t,e)}}},$=ac,nf=async({context:t,extension:e})=>{const s=await $.loader.executeLoader(e,{});return t==null||t.set(e,s),s},af=async({extension:t,contextData:e,data:s})=>await $.dataMapper.executeMapper(t,s,e),cf=async({extension:t,contextData:e,data:s})=>await $.propertyMapper.executeMapper(t,s,e),lf=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:af,executeLoaderExtension:nf,executePropertyMapperExtension:cf},Symbol.toStringTag,{value:"Module"})),uf="Extensions";class df{constructor(){l(this,"extensions");this.extensions={}}register(e,s,r){this.extensions[e]={},this.extensions[e][s]={component:r}}get(e,s){if(!this.extensions[e])throw new Error(`Extension point ${e} not found`);return this.extensions[e][s]}get allExtensions(){return this.extensions}}const be=(t=null)=>(t||window.location.search.replace("?","")).split("&").map(e=>{const[s,r]=e.split("=");return[s,decodeURIComponent(r||"")]}).reduce((e,[s,r])=>(e[s]=r,e),{}),hf="studio.enable.releases",cc="studio.tools.preview",ff="studio.relax.store.validation",lc="studio.log.debug",uc="studio.log.info",pf={profiles:[cc]};var Sa;const gf=((Sa=globalThis.getKosConfig)==null?void 0:Sa.call(globalThis))||JSON.stringify(pf),dc=JSON.parse(gf);globalThis.kosConfig=dc;const yn=dc,hc=()=>yn.profiles||[],Po=t=>hc().includes(t),mf=()=>yn.logging||!1,yf=()=>{const t=Po(lc),e=Po(uc);return t?"DEBUG":e?"INFO":void 0},fc=()=>{const t=be(),e=yf(),r=t.kosLogLevel??e??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},pc=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",gc=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",mc="ws-log",bf=D.methodFactory,yc=pc(),vf=gc();D.methodFactory=function(t,e,s){const r=bf(t,e,s);return function(...o){var c;const n=s?String(s):"",i=n?`[${String(n).substring(n.lastIndexOf(":")+1)}] | `:"[root] | ",a=o.map(u=>typeof u=="object"?JSON.stringify(u):String(u)).join(" ");r(`${i}${a}`),(c=globalThis==null?void 0:globalThis.kosConfig)!=null&&c.logging&&globalThis.kosLog&&(s!==mc||yc&&vf)&&globalThis.kosLog(`UI: ${i}${a}`)}};let bc=fc();D.setLevel(bc);window.setKosLogLevel=t=>{bc=t,D.setLevel(t)};const mr=D.getLogger(mc);window.enableKosMessageLog=()=>{mr.setLevel(D.levels.INFO)};window.disableKosMessageLog=()=>{mr.setLevel(D.levels.ERROR)};yc?window.enableKosMessageLog():window.disableKosMessageLog();const wf=["color: black","display: block","background-color: lightgreen","padding: 4px","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),Ef=["color: black","display: block","padding: 4px","background-color: yellow","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),Ws=t=>e=>{D.getLevel()<=t&&e()},m={...D,ifDebug:Ws(D.levels.DEBUG),ifInfo:Ws(D.levels.INFO),ifWarn:Ws(D.levels.WARN),ifError:Ws(D.levels.ERROR),getLogger:t=>D.getLogger(`kos::${t}`),getLoggers:()=>D.getLoggers(),createLogger:({name:t,group:e})=>{var n,i,a,c;const s=`${e?`${e}:`:"kos"}::${t}`,r=D.getLogger(s);let o=(i=(n=globalThis.kos.logOverrides)==null?void 0:n.find(u=>u.name===s))==null?void 0:i.level;return o?r.setLevel(o):(o=(c=(a=globalThis.kos.logOverrides)==null?void 0:a.find(u=>s.startsWith(u.name)))==null?void 0:c.level,o&&r.setLevel(o)),r},wsSend:(...t)=>{const e=String(t).replace(/\n/g,"\\n");mr.info(`%c⬆ ${e}`,wf)},wsReceive:(...t)=>{const e=String(t).replace(/\n/g,"\\n");mr.info(`%c⬇ ${e}`,Ef)}},vc="featureFlagResolver",Qs=new Map;js(vc,{register:(t,e)=>{var s;Qs.has(t)||Qs.set(t,[]),(s=Qs.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Qs.get(t);if(!s)return[];const r=s.map(a=>a(e)),n=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(m.info(`Feature flag resolver ${t} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(n)).reduce((a,c)=>(a[c]=!0,a),{});return Ec.updateFlags(i),Object.keys(i)}});const Mf="kos.loader.featureFlag";class wc{constructor(e={}){l(this,"flags",{});this.flags=e}isFeatureEnabled(e){return!!this.flags[e]}enableFeature(e){this.flags[e]=!0}disableFeature(e){this.flags[e]=!1}toggleFeature(e){this.flags[e]=!this.flags[e]}updateFlags(e){this.flags={...this.flags,...e}}}window.KosFeatureFlags=window.KosFeatureFlags??new wc;const Ec=window.KosFeatureFlags,Mc=(t,e,s)=>{s/=100;const r=e*Math.min(s,1-s)/100,o=n=>{const i=(n+t/30)%12,a=s-r*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*a).toString(16).padStart(2,"0")};return`#${o(0)}${o(8)}${o(4)}`},Tc=t=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(t);if(!s)throw Error("Invalid HSL string");return Mc(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},_c=(t,e)=>getComputedStyle(t).getPropertyValue(e),Tf=(t,e)=>Tc(_c(t,e)),_f=(t,e)=>{const s={...t};return s.id&&delete s.id,s},ko=(t,e,s=_f)=>{const r=s(t,e);M.runInAction(()=>{Object.assign(e,r)})},J=Symbol("SubscriptionHandlers"),F=Symbol("DependencyModels"),gs=Symbol("FutureService"),ze=Symbol("ChildModels"),ms=Symbol("ParentModel"),ys=Symbol("LogConfig"),cr=Symbol("ReferenceConfig"),bn=Symbol("KosModelSymbol"),nt=Symbol("ModelEffects"),Ve=Symbol("CompanionParentModel"),vn=Symbol("FutureContainerSetup"),wn=Symbol("MultipleFutureContainerSetup"),bs=Symbol("FutureAliases"),En=Symbol("TroubleAwareSetup"),Mn=Symbol("LoggerSetup"),Tn=Symbol("ContainerAwareSetup"),Bs=Symbol("StateMachineSetup"),St=Symbol("StateEntryHandlers"),vs=Symbol("StateExitHandlers"),Sf=Symbol("StateActionHandlers"),Hs=Symbol("OptionsRequired"),Of=m.createLogger({group:"decorators",name:"fsm-injection"});function Sc(t){const e=t[Bs];if(!e)return;const{config:s,options:r}=e;Df(t,s,r),xf(t,r);const o=Cf(t);If(t,s,r,o),$f(t,s,r)}function If(t,e,s,r){t.transition=Pf(t,e,s,r.entry,r.exit),t.canTransition=Hf(t,e,s),t.isInState=Kf(t,s)}function $f(t,e,s){Af(t),Rf(t,e,s)}function Cf(t){const e=t.constructor.prototype[St]||new Map,s=t.constructor.prototype[vs]||new Map;return{entry:e,exit:s}}function Df(t,e,s){t._fsmConfig=e,t._fsmOptions=s}function xf(t,e){const{stateProperty:s,trackHistory:r}=e,o=t._fsmConfig;t[s]=o.initial,t._fsmInitialized=!0,t.isTransitioning=!1,r&&(t.stateHistory=[{state:o.initial,timestamp:new Date}])}function Af(t){Object.defineProperty(t,"isFsmInitialized",{get(){return this._fsmInitialized},enumerable:!0,configurable:!0})}function Rf(t,e,s){const{stateProperty:r}=s;Object.defineProperty(t,"allowedTransitions",{get(){if(!this._fsmInitialized)return[];const o=this[r],n=this._fsmConfig.states[o];return n!=null&&n.on?Object.keys(n.on):[]},enumerable:!0,configurable:!0})}function Pf(t,e,s,r,o){const{stateProperty:n,throwOnInvalid:i}=s;return function(a){if(!this._fsmInitialized){kf(e.initializeAt,i);return}const c=this[n],u=Lf(c,a,this._fsmConfig,i);u&&Nf(this,c,u,a,n,r,o,s)}}function kf(t,e){const s=`Cannot transition: FSM not initialized. Waiting for ${t} lifecycle phase.`;if(e)throw new Error(s);console.warn(s)}function Lf(t,e,s,r){var i;const o=s.states[t],n=(i=o==null?void 0:o.on)==null?void 0:i[e];if(!n){Ff(t,e,r);return}return n}function Ff(t,e,s){const r=`Invalid transition: Event "${e}" not allowed from state "${t}"`;if(s)throw new Error(r);console.warn(r)}function Nf(t,e,s,r,o,n,i,a){t.isTransitioning=!0;try{Uf(t,e,i),t[o]=s,Bf(t,s,r,a),jf(t,s,n)}finally{t.isTransitioning=!1}}function Uf(t,e,s){const r=s.get(e);r&&typeof t[r]=="function"&&t[r]()}function jf(t,e,s){const r=s.get(e);r&&typeof t[r]=="function"&&t[r]()}function Bf(t,e,s,r){r.trackHistory&&t.stateHistory&&t.stateHistory.push({state:e,timestamp:new Date,event:s})}function Hf(t,e,s){const{stateProperty:r}=s;return function(o){var a;if(!this._fsmInitialized)return!1;const n=this[r],i=this._fsmConfig.states[n];return((a=i==null?void 0:i.on)==null?void 0:a[o])!==void 0}}function Kf(t,e){const{stateProperty:s}=e;return function(r){return this._fsmInitialized?this[s]===r:!1}}function Oc(t,e){const s=t[Bs];if(!s)return;const{config:r,options:o}=s,{stateProperty:n}=o;r.initializeAt===e&&(t._fsmInitialized||(qf(t,n,r.initial),t._fsmInitialized=!0,zf(t,r.initial,o),Vf(t,r.initial),Of.debug(`FSM initialized for model ${t.id} at lifecycle ${e} with initial state "${r.initial}"`)))}function qf(t,e,s){t[e]=s}function zf(t,e,s){s.trackHistory&&t.stateHistory&&t.stateHistory.push({state:e,timestamp:new Date})}function Vf(t,e){const r=(t.constructor.prototype[St]||new Map).get(e);r&&typeof t[r]=="function"&&t[r]()}const De=(t,e)=>{t[ze]=t[ze]||{},t[ze][e]=!0},ut=t=>`{PROP_${String(t)}}`,Gf=t=>`{PROP_${String(t)}}`,Yf=ut("kosParentId"),Wr=t=>e=>{e[ms]=e[ms]||{};const s=(t==null?void 0:t.parentId)||Yf;e[ms]={parentId:s},e.prototype[Hs]=!0};function Wf(t){return e=>{const s=(t==null?void 0:t.mode)||"decorator",r=(t==null?void 0:t.parentProperty)||"companionParent",o=(t==null?void 0:t.excludeProperties)||[],n=t==null?void 0:t.lifecycle;return Wr()(e),e.prototype[Ve]={mode:s,parentProperty:r,excludeProperties:o,lifecycle:n},e}}function Ic(t){return e=>{const s=t!=null&&t.legacy?"_models":(t==null?void 0:t.containerProperty)||"container",r=(t==null?void 0:t.includeMethods)!==!1,o=(t==null?void 0:t.includeGetters)!==!1,n=(t==null?void 0:t.modelsProperty)||"models",i=(t==null?void 0:t.containerOptions)||{};return e.prototype[Tn]={containerProperty:s,includeMethods:r,includeGetters:o,modelsProperty:n,containerOptions:i,legacy:(t==null?void 0:t.legacy)||!1},e}}function Qf(t,e,s){const r=s.value;s.value=function(...o){const n=V.getContext(this.id);return o.push(n),r.apply(this,o)}}const Qr=Symbol("KosExecutionContext");function _n(t){return t&&typeof t=="object"&&Qr in t}function Zf(t){return e=>{const s=(t==null?void 0:t.mode)||"full",r=(t==null?void 0:t.handlerProperty)||"futureHandler";return e.prototype[vn]={mode:s,handlerProperty:r},e}}function Xf(t){return e=>{const s=(t==null?void 0:t.mode)||"full",r=(t==null?void 0:t.handlerProperty)||"futureHandler";return e.prototype[wn]={mode:s,handlerProperty:r},e}}var x=(t=>(t.INIT="init",t.LOAD="load",t.READY="ready",t.ACTIVATE="activate",t.ONLINE="online",t))(x||{}),qe=(t=>(t.CREATE="create",t.CONTINUE="continue",t.FAIL="fail",t))(qe||{});const Jf=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:x,DependencyResolutionPolicy:qe},Symbol.toStringTag,{value:"Module"})),ke=Symbol("HttpRouteHandlers"),Ri="__httpBrowserRouter";function Zr(t){return function(s){return function(r,o,n){r[ke]=r[ke]||[];const i={method:t,path:s,handler:o};return r[ke].push(i),r[F]=r[F]||{},r[F][Ri]||(r[F][Ri]={modelType:"browser-router-model",lifecycle:x.INIT}),n}}}const $c=Zr("GET"),Ks=Zr("POST"),ep=Zr("PUT"),Cc=Zr("DELETE"),tp=Cc;function yr(t){return!!(t!=null&&t[ke])&&t[ke].length>0}function Dc(t){return(t==null?void 0:t[ke])||[]}const sp=({group:t}={group:""})=>e=>{e[ys]=e[ys]||{},e[ys]={group:t}};class xc{static create({modelId:e,modelTypeName:s,component:r}){const o=[r??"kos",s,e].filter(Boolean).join(".");return m.createLogger({name:o})}}function Ac(t){return e=>{const s=(t==null?void 0:t.loggerProperty)||"logger",r=t==null?void 0:t.loggerContext;e.prototype[Mn]={loggerProperty:s,loggerContext:r};const o=()=>{var i;return(i=e.prototype[bn])==null?void 0:i.type};let n;return Object.defineProperty(e.prototype,s,{get(){if(!n){const i=o();n=xc.create({modelTypeName:r||i,component:"kos-model"})}return n},enumerable:!1,configurable:!1}),e}}function Rc(t){return(e,s,r)=>{e[nt]=e[nt]||{},e[nt][s]={dependencies:t==null?void 0:t.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const rp=t=>(e,s)=>{e[cr]=e[cr]||{},e[cr][s]=t},vo=m.createLogger({name:"resolve-parameters"}),he=({value:t,modelId:e,modelData:s})=>{let r=t;if(Array.isArray(r))return[...t];if(typeof r!="string"&&typeof r!="object")return r;if(typeof r=="object")r=Object.keys(r).reduce((o,n)=>(o[n]=he({value:r[n],modelId:e,modelData:s}),o),{});else if(typeof r=="string"){const o=new RegExp("{PROP_(.+?)}","g");let n=r!=null&&r.includes(gr)?r.replace(gr,e):r;if(s){let i=!1;const a=/^{PROP_.+?}$/.test(n);if(n=n.replace(o,(c,u)=>{if(Object.getOwnPropertyNames(s).includes(u)||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(u)){const h=s[u];return h?(vo.debug(`Resolved ${c} to ${h}`),h):(vo[a?"debug":"warn"](`Property ${u} is falsy${a?"":" in composite string"}, marking for undefined return`),i=!0,c)}return vo[a?"debug":"warn"](`Property ${u} not found in modelData${a?"":" for composite string"}`),c}),i)return}return n}else return r;return r};function op(t,e,s,r){const o=he({value:t.path,modelId:e.id,modelData:e}),n=he({modelId:e.id,modelData:e,value:{...typeof t.pathParams=="function"?t.pathParams(e):t.pathParams||{},...(r==null?void 0:r.pathParams)||{}}}),i=he({modelId:e.id,modelData:e,value:{...typeof t.queryParams=="function"?t.queryParams(e):t.queryParams||{},...(r==null?void 0:r.queryParams)||{}}}),a=(r==null?void 0:r.body)||(typeof t.body=="function"?t.body(e):t.body),u={...(typeof t.requestOptions=="function"?t.requestOptions(e,...s):t.requestOptions)||{},...(r==null?void 0:r.requestOptions)||{}},d={};return n&&Object.keys(n).length>0&&(d.path=n),i&&Object.keys(i).length>0&&(d.query=i),{resolvedPath:o,apiParams:d,finalBody:a,finalRequestOptions:u}}async function np(t,e,s,r,o,n){const i=(e||"get").toLowerCase(),a=t;switch(i){case"get":return await a.get(s,r,n);case"post":return await a.post(s,r,o,n);case"put":return await a.put(s,r,o,n);case"delete":return await a.delete(s,r,o,n);default:return await a.get(s,r,n)}}function ip(t,e,s,r){if(!s)return[t,null];switch(s.strategy){case"log":return console.error(`Service request status ${e==null?void 0:e.status} error: ${t}`),s.onError&&s.onError(new Error(t),r),[null,s.defaultValue];case"ignore":return[null,s.defaultValue];case"default":return[null,s.defaultValue];case"throw":default:return[t,null]}}const it=Symbol("ServiceRequestHandlers"),Pi=new WeakMap;function dt(t){return(e,s,r)=>{var a;e[it]=e[it]||{};const o=r.value,n={...t,handlerMethod:s,originalHandler:o},i=`${((a=t.method)==null?void 0:a.toUpperCase())||"GET"}:${String(t.path)}`;if(e[it][i]=n,!t.lifecycle){const c=function(...u){const d=u[u.length-1],h=async f=>{const p=Pi.get(c);if(!p)throw new Error("Service request metadata not found for method");try{const{default:y}=await Promise.resolve().then(()=>al),{resolvedPath:w,apiParams:E,finalBody:_,finalRequestOptions:L}=op(p,this,u,f),[U,I]=await np(y,p.method,w,E,_,L);if(U)return ip(U,I,p.errorHandler,this);let S=I;return p.transform&&(S=p.transform(I)),[null,S]}catch(y){return[y.message||"Unknown error",null]}};if(_n(d))return d.$request=h,o.apply(this,u);{const f={[Qr]:!0,$request:h};return o.apply(this,[...u,f])}};Pi.set(c,n),r.value=c}return r}}var Pc=(t=>(t.GET="GET",t.PUT="PUT",t.POST="POST",t.DELETE="DELETE",t))(Pc||{}),se=(t=>(t.IMMEDIATE="immediate",t.SINGLE="single",t.TTL="ttl",t.PERMANENT="permanent",t.MANUAL="manual",t))(se||{}),ot=(t=>(t.ALL="all",t.AFTER_REQUEST="after-request",t.AFTER_RESPONSE="after-response",t.NONE="none",t))(ot||{});const ap=m.createLogger({name:"kos-state-machine"});function cp(t,e){return s=>(s.prototype[Bs]={config:{...t,initializeAt:t.initializeAt||x.READY},options:{stateProperty:(e==null?void 0:e.stateProperty)||"currentState",trackHistory:(e==null?void 0:e.trackHistory)||!1,throwOnInvalid:(e==null?void 0:e.throwOnInvalid)!==!1}},s)}function lp(t){return(e,s)=>{e[St]||(e[St]=new Map),e[St].set(t,s)}}function up(t){return(e,s)=>{e[vs]||(e[vs]=new Map),e[vs].set(t,s)}}function dp(t){return(e,s,r)=>{const o=r.value;return r.value=function(...n){var u,d;if(!this.isFsmInitialized)return o.apply(this,n);const a=this.currentState;if(!t.allowedStates.includes(a)){const h=`Method ${String(s)} cannot be called from state "${a}". Allowed states: ${t.allowedStates.join(", ")}`;if(t.throwOnInvalid!==void 0?t.throwOnInvalid:((d=(u=this[Bs])==null?void 0:u.options)==null?void 0:d.throwOnInvalid)!==!1)throw new Error(h);ap.warn(h);return}return o.apply(this,n)},r}}function hp(t){return e=>{const s=(t==null?void 0:t.pathProperty)||"path";return e.prototype[En]={pathProperty:s},e.prototype[F]=e.prototype[F]||{},e.prototype[F].troubleContainer={modelType:"trouble-container-model",id:"trouble-container-model",options:{},lazy:!1},e}}const Ht=({modelType:t,id:e,options:s,lifecycle:r,resolutionPolicy:o})=>(n,i)=>{n[F]=n[F]||{},n[F][i]={modelType:t,id:e,options:s,lifecycle:r||x.INIT,resolutionPolicy:o}};class kc{constructor(e,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=Pn.map(new Map),this.context="",this.defaultContext=s||"",this.container=e,M.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(e,s){this.futures.set(s||e.id,e),this.context=s||e.id;const r=s,o=G(()=>{var n,i;(e.endState||e.progress)&&((i=(n=this.container)==null?void 0:n.onFutureUpdate)==null||i.call(n,e,r))});this.disposers.set(s||e.id,o)}removeFuture(e){var s;this.futures.delete(e||this.context),(s=this.disposers.get(e||this.context))==null||s(),this.disposers.delete(e||this.context)}getFuture(e){return this.futures.get(e||this.context)}get futureMap(){return this.futures}}class Xr{constructor(e){l(this,"disposer");l(this,"_future");l(this,"container");l(this,"onFutureUpdate");this._future=void 0,this.container=e,M.makeAutoObservable(this)}removeFuture(){var e;this._future=void 0,(e=this.disposer)==null||e.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(e){this._future=e;const s=G(()=>{var r,o;(e.endState||e.progress)&&((o=(r=this.container)==null?void 0:r.onFutureUpdate)==null||o.call(r,e))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var e;return((e=this._future)==null?void 0:e.timeRemaining)||""}get status(){var e;return((e=this._future)==null?void 0:e.status)||"NOT_RESOLVED"}get progress(){var e;return((e=this._future)==null?void 0:e.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(e){throw m.error(e),e}}}const Lc=(t,e)=>{const s=e.type;return t[s]||(t[s]=[]),t[s].push(e),t},Fc=Symbol("KosObservableData"),Jt=Symbol("revision");var BT;class Nc{constructor(){l(this,"map");l(this,BT,1);l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(e,s)=>{var r;return s===Jt||e[s]!==void 0?e[s]:this.atomMap.has(s)&&(r=this.atomMap.get(s))!=null&&r.reportObserved()?this.getValue(s):this.getValue(s)},set:(e,s,r)=>{var o;return this.map.has(s),this.setValue(s,r),this.atomMap.has(s)||this.atomMap.set(s,M.createAtom(s.toString())),(o=this.atomMap.get(s))==null||o.reportChanged(),!0},ownKeys:()=>Array.from(this.map.keys())});this.map=M.observable.map(new Map),M.makeObservable(this,{[Jt]:M.observable})}setValue(e,s){const r=this.map.has(e);this.map.set(e,s),r||M.action(()=>{this[Jt]++})()}getValue(e){return this.map.get(e)}has(e){return this.map.has(e)}get entries(){return Array.from(this.map.entries())}get keys(){return this[Jt],Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(e){e&&Object.keys(e).forEach(s=>{this.setValue(s,e[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}BT=Jt;Nc.prototype[Fc]=!0;function fp(t,e){return new Proxy(t,{construct:(s,r)=>{const o=new t(...r);return o.setValues(e),o.proxy}})}const Ie=t=>{const e=fp(Nc,t);return new e(t)};function pp(t,e){return t.length!==e.length?!1:t.every(s=>e.includes(s))}class Sn{constructor({container:e,key:s}){l(this,"_container");l(this,"_map");l(this,"_key");l(this,"data");this._container=e,this._map=M.observable.map(new Map),this._key=s,this.data=Ie(),this.generateIndex(),M.autorun(()=>{this._container.revision&&this.generateIndex()}),M.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(e,s,r=this._map,o=this.data){const n=r.get(e)||new Set;n.add(s),r.set(e,n),o[e]=Array.from(n)}resolveIndex(e,s){this.data.keys.filter(o=>!Object.keys(s).includes(o)).forEach(o=>{delete this.data[o],this._map.delete(o)}),Object.keys(s).forEach(o=>{const n=s[o],i=this.data[o]||[];if(pp(n,i))m.debug(`KosContainerIndex - Index ${o} is the same`);else{this.data[o]=n;const a=e.get(o)||new Set;this._map.set(o,a)}})}generateIndex(){M.runInAction(async()=>{const e=new Map,s={};for(const r of this._container.data){const o=typeof this._key=="function"?await this._key(r):r[this._key];Array.isArray(o)?o.forEach(n=>{this.addItemToIndex(n,r,e,s)}):typeof o=="string"||typeof o=="number"?this.addItemToIndex(String(o),r,e,s):typeof o=="boolean"&&this.addItemToIndex(String(o),r,e,s)}this.resolveIndex(e,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(e){const s=this._map.get(e);return s?Array.from(s):[]}}function gp(t,e,s=[]){const r=Object.getOwnPropertyDescriptors(t);return Object.keys(r).filter(i=>M.isComputedProp(t,i)).filter(i=>s.includes(i)).map(i=>M.reaction(()=>t[i],(a,c)=>{e({name:i,newValue:a,oldValue:c})}))}const ne=m.createLogger({name:"kos-container-model"});class xe{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"_parentId");l(this,"idx");l(this,"_maxCapacity");l(this,"_evictionStrategy");l(this,"_evictionBatchSize");l(this,"_insertionOrder",[]);l(this,"_accessTimes");l(this,"_customEvictionFilter");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1;const s=e!=null&&e.extensionId?$.indexExtension.loadIndexExtensions(e.extensionId):{},r=(e==null?void 0:e.indexMap)||{};this._optionsMap={...r,...s};const o=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=M.observable.map(o),this.idx=Ie(),this._parentId=e==null?void 0:e.parentId,this._maxCapacity=e==null?void 0:e.maxCapacity,this._evictionStrategy=(e==null?void 0:e.evictionStrategy)||"fifo",this._evictionBatchSize=(e==null?void 0:e.evictionBatchSize)??Math.max(10,Math.ceil(((e==null?void 0:e.maxCapacity)??100)*.1)),this._customEvictionFilter=e==null?void 0:e.customEvictionFilter,this._evictionStrategy==="lru"&&this._maxCapacity&&(this._accessTimes=M.observable.map(new Map)),M.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new Sn({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get revision(){return this._revision}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s,!0)),this.increment()})}async removeAndDestroy(e){const s=this.getModel(e);if(!s){ne.debug(`Model ${e} not found in container, skipping destroy`);return}this.removeModel(e);try{await Oe(s)}catch(r){throw ne.error(`Failed to destroy model ${e}:`,r),r}}async removeAndDestroyAll(e){const s=e.map(n=>this.getModel(n)).filter(n=>n!==void 0);if(s.length===0){ne.debug("No models found to destroy");return}this.removeAll(e);const r=await Promise.allSettled(s.map(n=>Oe(n)));r.forEach((n,i)=>{n.status==="rejected"&&ne.error(`Failed to destroy model ${s[i].id}:`,n.reason)});const o=r.filter(n=>n.status==="rejected");if(o.length>0)throw new Error(`Failed to destroy ${o.length} of ${s.length} models`)}addModel(e,s){this._persistModel(e),this._trackModelMetadata(e),this._establishModelRelationships(e),this._enforceCapacityLimits(),this._configureModelMonitoring(e),s||this.increment()}_persistModel(e){this._data.set(e.id||"",e)}_trackModelMetadata(e){this._maxCapacity&&(this._insertionOrder.push(e.id||""),this._accessTimes&&this._accessTimes.set(e.id||"",Date.now()))}_establishModelRelationships(e){e.id&&this._parentId&&V.setParentContext(e.id,this._parentId)}_enforceCapacityLimits(){this._maxCapacity&&this._data.size>this._maxCapacity&&this._evictModels()}_configureModelMonitoring(e){const s=this._disposerMap.get(e.id);s&&(s(),this._disposerMap.delete(e.id));const r=Object.entries(this._optionsMap||{}),o=Object.values(this._optionsMap||{}),n=new Map(r.map(([u,d])=>[d,u])),i=u=>{var h,f;o.includes(u.name)&&((h=this.index.get(n.get(u.name)))==null||h.refresh());const d=r.filter(([,p])=>typeof p=="function");for(const[p]of d)(f=this.index.get(p))==null||f.refresh()},a=gp(e,i,o.filter(u=>typeof u=="string")),c=M.observe(e,i);this._disposerMap.set(e.id||"",()=>[c,...a].forEach(u=>u()))}removeModel(e,s){this._data.delete(e);const r=this._insertionOrder.indexOf(e);r!==-1&&this._insertionOrder.splice(r,1),this._accessTimes&&this._accessTimes.delete(e),s||this.increment();const o=this._disposerMap.get(e);o&&(o(),this._disposerMap.delete(e))}updateModel(e){this._data.set(e.id||"",e),this.increment()}getModel(e){const s=this._data.get(e);return s&&this._accessTimes&&this._accessTimes.set(e,Date.now()),s}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(ne.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(e,s){if(this.index.has(e)){const r=this.index.get(e);return r.index.has(s)?r.getByKey(s):(ne.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return ne.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async _evictModels(){if(!this._maxCapacity)return;const e=this._data.size-this._maxCapacity;if(e<=0)return;const s=Math.min(this._evictionBatchSize,e);this._logCapacityWarning(s);const r=this._selectModelsForEviction(s);await this._removeEvictedModels(r),this._logEvictionComplete(r.length),this.increment()}_logCapacityWarning(e){ne.info(`Container capacity exceeded (${this._data.size}/${this._maxCapacity}). Evicting ${e} models using ${this._evictionStrategy} strategy.`,{parentId:this._parentId})}_selectModelsForEviction(e){switch(this._evictionStrategy){case"fifo":return this._selectFifoModels(e);case"lru":return this._selectLruModels(e);case"custom":return this._selectCustomModels(e);default:return this._selectFifoModels(e)}}_selectFifoModels(e){const s=[];for(let r=0;r<e&&this._insertionOrder.length>0;r++){const o=this._insertionOrder.shift();if(!o)continue;const n=this._data.get(o);n&&s.push(n)}return s}_selectLruModels(e){const s=[];return this._accessTimes&&Array.from(this._accessTimes.entries()).sort((o,n)=>o[1]-n[1]).slice(0,e).forEach(([o])=>{const n=this._data.get(o);n&&s.push(n)}),s}_selectCustomModels(e){return this._customEvictionFilter?this._customEvictionFilter(this.data).slice(0,e):(ne.error("Custom eviction strategy specified but no customEvictionFilter provided. Falling back to FIFO.",{parentId:this._parentId}),this._selectFifoModels(e))}async _removeEvictedModels(e){for(const s of e)ne.info(`Evicting model: ${s.id} (type: ${s.constructor.name})`,{modelId:s.id,parentId:this._parentId,strategy:this._evictionStrategy}),this.removeModel(s.id,!0),Oe(s).catch(r=>ne.error(`Failed to destroy evicted model ${s.id}:`,r))}_logEvictionComplete(e){ne.info(`Evicted ${e} models. Current size: ${this._data.size}/${this._maxCapacity}`,{parentId:this._parentId})}async clear(){this._data.forEach(e=>{const s=e.id;Oe(e).then(()=>{ne.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>ne.error(r))}),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}var v=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.READY_FAILED="ready_failed",t.RESETTING="resetting",t.RESET="reset",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.FAILED="failed",t.INACTIVE="inactive",t.ACTIVE="active",t.ACTIVATING="activating",t.DEACTIVATING="deactivating",t))(v||{}),k=(t=>(t.CREATE="create",t.INITIALIZE="init",t.LOAD="load",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.RESET="go_offline",t.UNLOAD="unload",t.FAILED="failed",t.GO_ACTIVE="go_active",t.GO_INACTIVE="go_inactive",t.TIMEOUT="timeout",t))(k||{});const fe=async t=>{if(t.id){const e=O.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error(`Model with ID ${t.id} not found`);await(e==null?void 0:e.whenReady())}else throw new Error("Data model must have a valid ID");return t},Oe=async t=>{await O.getInstance().whenReady(),await O.getInstance().modelManager.initiateDestroyModel(t)},mp=async t=>{if(await O.getInstance().whenReady(),!t.id)throw new Error("Model ID is required");const e=O.getInstance().modelManager.getModelById(t.id);e&&await e.fsm.transitionTo(k.UNLOAD,v.UNLOADED)},yp=async t=>{await O.getInstance().whenReady(),await O.getInstance().modelManager.reloadModel(t),m.debug(`reload model initiated for model ${t.id}, model ready: ${br(t)} - ${Date.now()} `),await fe(t),m.debug(`reload model complete for model ${t.id}, model ready: ${br(t)} - ${Date.now()} `)},bp=async t=>{if(await O.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=O.getInstance().modelManager.getModelById(t);return e==null?void 0:e.modelTypeName},Uc=async t=>{if(await O.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=O.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},$e=t=>{if(!t)throw new Error("Model ID is required");const e=O.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},jc=(t,e)=>{if(!t)throw new Error("Model type is required");return O.getInstance().modelManager.getModelsByType(t).filter(o=>Object.keys(e).every(n=>o[n]===e[n]))},vp=(t,e)=>jc(t,e)[0],wp=(t,e)=>{if(!t.id)throw new Error("Model ID is required");const s=O.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error("Model not found");const r=s.companionModels.get(e);return r==null?void 0:r.modelData},Bc=t=>{if(!t.id)throw new Error("Model ID is required");const e=O.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return Array.from(e.companionModels.all()).map(r=>r.modelData)},Ep=t=>{if(!t)throw new Error("Model ID is required");const e=O.getInstance().modelManager.getModelById(t);if(!e)throw new Error("Model not found");return e.companionModels.data},Lo=(t,e)=>{const s=O.getInstance().modelManager.getModelById(t);if(!s){m.info(`Model not found for id ${t}`);return}return Array.from(s.companionModels.all()).find(o=>e(o.modelData))},_e=t=>e=>Object.getPrototypeOf(e).modelTypeId===t,br=t=>{const e=O.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return e.isReady()},Mp=m.createLogger({name:"kos-model-factory"}),ws={byModelType:t=>O.getInstance().modelManager.getModelFactory(t),getModelInstance:(t,e,s)=>{const r=ws.byModelType(e);if(!r)throw Mp.error(`No registered factory found for model type ${e}. Please register a factory for this model type. `),Error(`No factory found for model type ${e}`);return r.build(t,s)}},ae={Factory:{create:t=>e=>(s,r)=>(r&&V.setParentContext(e,r),ws.getModelInstance(e,t,s))},Singleton:{create:t=>(e,s)=>(s&&V.setParentContext(t,s),ws.getModelInstance(t,t,e))},Model:{instance:t=>e=>ws.getModelInstance(e,t)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const ki=window.KosRegistry.coreModels,wo=window.KosRegistry.preloadModels,Eo=window.KosRegistry.companionModels,Zs=window.KosRegistry.models,A={model:{registerLegacyModel:t=>(e,s)=>(ki.set(e,s),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}),preloadModel:t=>e=>(wo.includes(e)||wo.push(e),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}),register:t=>(e,s)=>{const r=Mo(e)?e.registration():e;return Zs.set(r.type,r),Mo(e)&&e.relatedModels.forEach(o=>Zs.set(o.type,o.registration())),O.getInstance().isReady&&(O.getInstance().modelManager.registry.models[r.type]||(console.info(`Model with type ${r.type} doesn't exist. Adding new registration`),O.getInstance().modelManager.registry.models[r.type]=r.registration[r.type],Mo(e)&&e.relatedModels.forEach(o=>O.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&A.model.preloadModel(t)(r.type),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}},get:t=>Zs.get(t),getAll:()=>Array.from(Zs.entries()),getPreloadModels:()=>wo,getLegacyModels:()=>Array.from(ki.entries()).reduce((t,[e,s])=>(t[e]=s,t),{})},companion:{register:t=>(e,s)=>{const r=Eo.get(e)||[];return r.push(s),Eo.set(e,r),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}},getAll:()=>Array.from(Eo.entries())}},Hc=A.model.registerLegacyModel,Kc=A.model.register,Tp=A.companion.register,_p=A.model.preloadModel,On=t=>typeof t.updateModel=="function",Mo=t=>t.registration!==void 0&&typeof t.registration=="function";class qc{constructor(e){l(this,"singleton");l(this,"type");l(this,"loader");l(this,"class");l(this,"guard");l(this,"factory");l(this,"relatedModels",[]);this.singleton=e.singleton,this.guard=_e(e.type),this.type=e.type,this.loader=`kos.extension.model.loader.${e.type}`,this.factory=e.factory,this.class=e.class}addRelatedModel(e){this.relatedModels.push(e)}registerRelatedModels(){this.relatedModels.forEach(e=>e.register())}register(){A.model.register({})(this.registration()),this.registerRelatedModels()}}class ve extends qc{constructor(e){super({...e,singleton:!1,factory:ae.Factory.create(e.type)})}instance(e){const s=this.factory(e);return{get:()=>{const r=$e(e);if(!r)throw new Error("Model not found with id "+e);if(this.guard(r.model))return r.model;throw new Error("Model is not of type "+this.type)},forceUpdate:{options:r=>({build:()=>{const o=s(r);if(this.guard(o)){if(On(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error("Model is not of type "+this.type)}})},options:r=>({build:()=>{const o=s(r);if(this.guard(o))return o;throw new Error("Model is not of type "+this.type)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!1}},factory:this.factory}}}class Se extends qc{constructor(e){super({...e,singleton:!0,factory:ae.Singleton.create(e.type)})}instance(){const e=this.factory;return{get:()=>{const r=$e(this.type);if(!r)throw new Error("Model not found with id "+this.type);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)},forceUpdate:{options:r=>({build:()=>{const o=e(r);if(this.guard(o)){if(On(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})},options:r=>({build:()=>{const o=e(r);if(this.guard(o))return o;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const Fo=m.createLogger({group:"decorators",name:"kos-model"});function Sp(t,e,s){var n;const r=(n=t[ms])==null?void 0:n.parentId;if(!r)return;const o=he({value:r,modelData:s,modelId:e});o&&typeof o=="string"&&V.setParentContext(e,o)}function Op(t){const e=t[gs];e&&Object.entries(e).forEach(([s,{handler:r}])=>{t[s]=r})}function Ip(t,e){const s=t[F]||{};Object.entries(s).forEach(([r,o])=>{const n=he({value:o.id||o.modelType,modelData:t,modelId:e}),i=Object.entries((o==null?void 0:o.options)||{}).reduce((a,[c,u])=>(a[c]=he({value:u,modelData:t,modelId:e}),a),{});if(typeof n=="string"){if(!o.lazy){const a=O.getInstance().modelManager.createModelInstance(o.modelType,n,i);t[r]=a.data}O.getInstance().modelManager.addDependency(e,n)}})}function $p(t){const e=t[vn];if(!e)return;const{mode:s,handlerProperty:r}=e,o=new Xr(t);t[r]=o,s==="full"&&(Object.defineProperty(t,"future",{get(){return o.future},enumerable:!0,configurable:!0}),Object.defineProperty(t,"progress",{get(){var n;return((n=o.future)==null?void 0:n.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){var n;return((n=o.future)==null?void 0:n.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){var n;return((n=o.future)==null?void 0:n.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function Cp(t){const e=t[wn];if(!e)return;const{mode:s,handlerProperty:r}=e,o=new kc(t);t[r]=o,Object.defineProperty(t,"future",{get(){return o.future},enumerable:!0,configurable:!0});const n=t[bs];n instanceof Map&&n.forEach(i=>{const a=`${i}Future`;Object.defineProperty(t,a,{get(){return o.futureMap.get(i)},enumerable:!0,configurable:!0}),s==="full"&&(Object.defineProperty(t,`${i}Progress`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}Status`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}IsRunning`,{get(){const c=o.futureMap.get(i);return c?!c.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}IsCancelled`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t[`cancel${i.charAt(0).toUpperCase()}${i.slice(1)}`]=async()=>{const c=o.futureMap.get(i);c&&await c.cancelFuture()})}),s==="full"&&(Object.defineProperty(t,"progress",{get(){var i;return((i=o.future)==null?void 0:i.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){var i;return((i=o.future)==null?void 0:i.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){var i;return((i=o.future)==null?void 0:i.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function Dp(t){const e=t[En];if(!e)return;const{pathProperty:s}=e;Object.defineProperty(t,"troubles",{get(){const r=this[s];if(r==null){const o=`@kosTroubleAware: Path property '${s}' is undefined on model ${this.id||"unknown"}. Returning empty troubles array.`;return this.logger&&typeof this.logger.warn=="function"?this.logger.warn(o):console.warn(o),[]}return this.troubleContainer.troubles.getIndexByKey("byIface",r).sort((o,n)=>n.rank-o.rank)},enumerable:!0,configurable:!0}),Object.defineProperty(t,"troubleStatus",{get(){return""},enumerable:!0,configurable:!0}),Object.defineProperty(t,"troublesByType",{get(){return this.troubles.reduce(Lc,{})},enumerable:!0,configurable:!0})}function xp(t,e){const s=t[Tn];if(!s)return;const{containerProperty:r,includeMethods:o,includeGetters:n,modelsProperty:i,containerOptions:a,legacy:c}=s,u={...a,parentId:a.parentId||e},d=new xe(u);t[r]=d,t[ze]||(t[ze]={}),t[ze][r]=d,o&&(t.getModel=h=>d.getModel(h),t.addModel=h=>{d.addModel(h)},t.removeModel=h=>{d.removeModel(h)},t.addAll=h=>{d.addAll(h)},t.removeAll=h=>{d.removeAll(h)},t.removeAndDestroy=async h=>d.removeAndDestroy(h),t.removeAndDestroyAll=async h=>d.removeAndDestroyAll(h)),n&&(Object.defineProperty(t,i,{get(){return d},enumerable:!0,configurable:!0}),Object.defineProperty(t,"data",{get(){return d.data},enumerable:!0,configurable:!0}))}function Ap(t,e){const s=t.constructor.prototype[Ve];if(!s)return;const{mode:r,parentProperty:o,excludeProperties:n}=s,i=e.companionParent;if(!i){Fo.warn("Companion decorator configured but no parent model found in initialData.companionParent");return}if(t.getCompanionParent=()=>i,Object.defineProperty(t,o,{get:()=>i,enumerable:!0,configurable:!0}),r==="composition")return;const a=["init","load","unload","ready","dispose","destroy","activate"],c=["getDependencies","getChildren","update","toJSON","forceUpdate","makeAutoObservable","runInAction","transaction","observe","unobserve","intercept","spy","trace","getCompanionParent"],u=p=>{const y=i.constructor.prototype[J]||{};return Object.values(y).some(w=>{const E=w==null?void 0:w.handler;return E===i[p]||E===i.constructor.prototype[p]})},d=p=>p==="constructor"||p.startsWith("_")||p.startsWith("__")||a.includes(p)||c.includes(p)||n.includes(p)||u(p)||p in t,h=new Set;Object.getOwnPropertyNames(i).filter(p=>!d(p)).forEach(p=>h.add(p));let f=Object.getPrototypeOf(i);for(;f&&f!==Object.prototype;)Object.getOwnPropertyNames(f).filter(p=>!d(p)).forEach(p=>h.add(p)),f=Object.getPrototypeOf(f);for(const p of h)try{const y=i[p];typeof y=="function"?t[p]=(...w)=>y.apply(i,w):Object.defineProperty(t,p,{get:()=>i[p],set:w=>{i[p]=w},enumerable:!0,configurable:!0})}catch(y){Fo.debug(`Skipping companion proxy for property ${p}:`,y)}}function Rp(t){try{return M.makeAutoObservable(t)}catch(e){return Fo.error("Failed to make observable:",e),t}}const Pp={construct(t,e){var c;const[s,r={}]=e,o=V.createContext(s);Sp(t,s,r);const i=!!t.prototype[Mn]?null:m.createLogger({name:t.prototype.modelTypeId,group:((c=t[ys])==null?void 0:c.group)??"kos-model"}),a=new t(s,r,{logger:i,kosContext:o});return Ap(a,r),Op(a),$p(a),Cp(a),Dp(a),xp(a,s),Sc(a),Ip(a,s),Rp(a)}};function R(t){return e=>{var n,i;const s=e,r=typeof t=="string"?{modelTypeId:t,autoRegister:!1}:{autoRegister:!1,...t};s.prototype.modelTypeId=r.modelTypeId,s.prototype[bn]=!0,(n=s.prototype)[J]??(n[J]={}),(i=s.prototype)[F]??(i[F]={}),r.optionsRequired&&(s.prototype[Hs]=!0),m.ifDebug(()=>{m.debug(`Registering model with id ${r.modelTypeId}`)});const o=new Proxy(s,Pp);if(r.singleton!==void 0){let a;r.singleton?a=new Se({class:o,type:r.modelTypeId}):a=new ve({class:o,type:r.modelTypeId}),Object.defineProperty(o,"Registration",{value:a,writable:!1,enumerable:!0,configurable:!1}),r.autoRegister&&a.register()}return o}}const kp=({topic:t,handler:e,websocket:s=!1,condition:r=()=>!0})=>o=>{o[J]=o[J]||{},Array.isArray(t)?t.forEach(n=>{o[J][n]={websocket:s,handler:e,condition:r}}):o[J][t]={websocket:s,handler:ic(o,M.action(e),200),condition:r}};function zc(t,e,s){const r={};if(!t.endsWith("/*"))return r;const o=t.slice(0,-2);if(e.startsWith(o)){const n=e.slice(o.length+1),i=s||"path";r[i]=n}return r}function Vc(t){return t.endsWith("/*")}function B(t){return(e,s,r)=>{const o=Lp(t,r);Up(e,t.topic,o),t.replay&&jp(t.topic,t.replay.bufferSize)}}function Lp(t,e){const{condition:s=(S,Z)=>!0,transform:r=S=>S,websocket:o=!1,fos:n=!1,bridge:i=!1,skipParse:a=!1,lifecycle:c,destinationAddress:u,debounce:d,throttle:h,buffer:f,filter:p,once:y,wildcardName:w,flow:E,requiresBaseline:_}=t,L=e.value,U=Fp(L,{debounce:d,throttle:h,buffer:f,once:y}),I=Np(p,s);return{websocket:o,fos:n,bridge:i,handler:U,condition:I,transform:r,lifecycle:c,skipParse:a,destinationAddress:u,wildcardName:w,flow:E,requiresBaseline:_}}function Fp(t,e){var n,i;let s=t;const r=typeof e.debounce=="number"?e.debounce:(n=e.debounce)==null?void 0:n.delay,o=typeof e.throttle=="number"?e.throttle:(i=e.throttle)==null?void 0:i.interval;return r&&r>0?s=Bp(s,e.debounce):o&&o>0?s=zp(s,e.throttle):e.buffer?s=Vp(async function(c){for(const u of c)await s.call(this,u)},e.buffer):e.once&&(s=Gp(s)),s}function Np(t,e){return t?(s,r,o)=>t(o)?e(s,r,o):!1:e}function Up(t,e,s){t[J]=t[J]||{},Array.isArray(e)?e.forEach(r=>{t[J][r]=s}):t[J][e]=s}function jp(t,e){Yp(t,e)}function Bp(t,e){const s=typeof e=="number"?e:e.delay;return Hp(e)==="discard"?Kp(t,s):qp(t,s)}function Hp(t){return(typeof t=="object"?t.discardIntermediate:!1)?"discard":"accumulate"}function Kp(t,e){let s=null;return function(r){s&&clearTimeout(s),s=setTimeout(()=>{t.call(this,r),s=null},e)}}function qp(t,e){let s=null,r=[];return function(o){r.push(o),s&&clearTimeout(s),s=setTimeout(()=>{const n=[...r];r=[],t.call(this,n),s=null},e)}}function zp(t,e){const s=typeof e=="number"?e:e.interval,r=typeof e=="object"?e.discardIntermediate:!1;let o=0,n=null,i=[],a=!1;const c=function(){if(i.length>0){const u=[...i];i=[],t.call(this,u)}};return function(u){const d=Date.now(),h=d-o;r?h>=s?(o=d,t.call(this,u)):n||(n=setTimeout(()=>{o=Date.now(),t.call(this,u),n=null},s-h)):(i.push(u),h>=s?(o=d,c.call(this)):a||(a=!0,n=setTimeout(()=>{o=Date.now(),c.call(this),n=null,a=!1},s-h)))}}function Vp(t,e){const s=[];let r=null;const o=e.maxSize||1e3,n=i=>{s.length>0&&(t.call(i,[...s]),s.length=0)};return function(i){if(s.push(i),s.length>=o){r&&(clearTimeout(r),r=null),n(this);return}r||(r=setTimeout(()=>{n(this),r=null},e.time))}}function Gp(t){let e=!1;return function(s){e||(e=!0,t.call(this,s))}}function Yp(t,e){(Array.isArray(t)?t:[t]).forEach(r=>{un(r,e)})}const To=new Map,Gc={addToDeletionQueue:(t,e)=>{const s=To.get(t)||[];s.push(e),To.set(t,s)},cancelDeletion:t=>{const e=To.get(t);e&&e.forEach(s=>{clearTimeout(s)})}},Wp=m.createLogger({name:"kos-dependency-manager"});class Qp{constructor(){l(this,"_usedByCache",new Map);l(this,"_usesCache",new Map)}add(e,s){Gc.cancelDeletion(s);const r=this._usedByCache.get(s)||[];r.includes(e)||r.push(e),this._usedByCache.set(s,r);const o=this._usesCache.get(e)||[];o.includes(s)||o.push(s),this._usesCache.set(e,o)}remove(e,s){const r=this._usedByCache.get(s)||[];this._usedByCache.set(s,r.filter(n=>n!==e));const o=this._usesCache.get(e)||[];this._usesCache.set(e,o.filter(n=>n!==s))}canDestroy(e){const s=this._usedByCache.get(e);return s!=null&&s.length?(Wp.info(`Model ${e} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}const Li=m.createLogger({name:"kos-model-cache"});class Zp{constructor(e=[]){l(this,"_modelsById",M.observable.map(new Map));l(this,"_toDelete",new Map);l(this,"_preloaded",[]);l(this,"_isPreloaded",!1);this.preloadKeys=e}get models(){return Array.from(this._modelsById.values()).map(e=>e).filter(e=>!this._toDelete.has(e.modelId))}getModelById(e){if(e&&!this._toDelete.has(e))return this._modelsById.get(e)}addModel(e){const s=this.getModelById(e.modelId)||e;return this._modelsById.set(s.modelId,s),s}removeModel(e){this._modelsById.delete(e),this._toDelete.delete(e)}hasModel(e){return!!e&&this._modelsById.has(e)&&!this._toDelete.has(e)}restoreFromDeleteCache(e){if(e&&this._toDelete.has(e)){const s=this._toDelete.get(e);this._toDelete.delete(e),this._modelsById.set(e,s)}}markForDeletion(e){this._modelsById.delete(e.modelId),this._toDelete.set(e.modelId,e)}preload(e){return this._isPreloaded?(Li.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(Li.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),e(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}class lr extends Error{constructor(s,r,o){super(s,{cause:o});l(this,"context");l(this,"originalCause");this.name="KosModelError",this.context=r,this.originalCause=o,o!=null&&o.stack&&(this.stack=`${this.stack}
1
+ "use strict";var jh=Object.defineProperty;var Bh=(t,e,s)=>e in t?jh(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var l=(t,e,s)=>(Bh(t,typeof e!="symbol"?e+"":e,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("loglevel"),M=require("mobx"),b=require("robot3"),Ke=require("date-fns"),T=require("@emotion/react/jsx-runtime"),tn=require("@emotion/styled"),Oa=require("react-dom"),st=require("@emotion/react"),g=require("react"),sn=require("mobx-react-lite"),Hh=require("@use-gesture/react"),qr="method",Ia="topic",Bt="url",Ns="request-id",zr="response-id",rn="status",je="dst-addr",$a="src-addr",Ce="type",on="ordered",nn="tracker",Ca="Content-Type",Da="Cache-Control",xa="requestId",Aa=process.env.KOS_LOGIN_URL||"http://localhost",Ra=process.env.KOS_APP_PORT||"8080",Kh=`${Aa}:${Ra}`,gr="{MODEL_ID}";var Us=(t=>(t.SEND="/ws/log/msg/send",t.RECEIVED="/ws/log/msg/receive",t))(Us||{}),Pa=(t=>(t.MSG_RECEIVE="/mock/msg/receive",t))(Pa||{});const an="/kos/model/ready/";D.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const K=globalThis.kos.subscriptions,qh=()=>Symbol("eventKey");function cn(t){return K[t]&&Object.getOwnPropertySymbols(K[t]).length>0}function C(t,e){const s=qh();return K[t]||(D.debug(`Initializing subscription for ${t}`),K[t]={}),D.debug(`Subscribing to ${t} with id ${s.toString()}`),K[t][s]=e,{count:K[t]?Object.getOwnPropertySymbols(K[t]).length:0,unsubscribe:()=>(D.debug(`Unsubscribing from ${t} with id ${s.toString()}`),K[t]&&K[t][s]&&delete K[t][s],K[t]&&Object.getOwnPropertySymbols(K[t]).length===0&&delete K[t],{count:K[t]?Object.getOwnPropertySymbols(K[t]).length:0})}}function q(t,e,s={}){if(!K[t]||Object.getOwnPropertySymbols(K[t]).length===0)return D.debug(`No subscriptions for ${t}. Not publishing.`),{eventType:t,subscribers:0};const r=Object.getOwnPropertySymbols(K[t]).length;return Object.getOwnPropertySymbols(K[t]).forEach(o=>{if(s.sync){const n=s.sync;D.debug(`Performing sync publish for ${t} with sync id ${n}`),K[t][o]({body:e,headers:s}).then(i=>{D.debug(`Response recieved for ${n}, publishing back to source.`),q(n,i)})}else D.debug(`Performing async publish for ${t}`),K[t][o]({body:e,headers:s})}),{eventType:t,subscribers:r}}function zh(){D.warn("Resetting event bus"),Object.keys(K).forEach(t=>delete K[t])}function ka(t,e){const s=C(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function ln(t,e){return new Promise((s,r)=>{let o=null;const n=ka(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}const Vh=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:cn,once:ka,publish:q,reset:zh,subscribe:C,waitFor:ln},Symbol.toStringTag,{value:"Module"}));function Vr(t,e){const s=C(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function Gr(t,e){return new Promise((s,r)=>{let o=null;const n=Vr(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}function La(t,e){const s=t.map(r=>Gr(r,e));return Promise.all(s)}function Fa(t,e){return new Promise((s,r)=>{const o=[];let n=null,i=!1;const a=()=>{o.forEach(c=>c()),n&&clearTimeout(n)};t.forEach(c=>{const u=Vr(c,d=>{i||(i=!0,a(),s({eventType:c,data:d}))});o.push(u)}),e&&(n=setTimeout(()=>{i||(i=!0,a(),r(new Error(`Timeout waiting for any event: ${t.join(", ")}`)))},e))})}function Na(t,e,s){return C(t,o=>{o&&e(o)&&s(o)}).unsubscribe}function Ua(t,e,s){return C(t,o=>{if(o){const n=e(o);s(n)}}).unsubscribe}function ja(t,e,s){let r=null;const o=C(t,n=>{r&&clearTimeout(r),r=setTimeout(()=>{s(n)},e)});return()=>{r&&clearTimeout(r),o.unsubscribe()}}function Ba(t,e,s){let r=0,o=null;const n=C(t,i=>{const a=Date.now(),c=a-r;c>=e?(r=a,s(i)):o||(o=setTimeout(()=>{r=Date.now(),s(i),o=null},e-c))});return()=>{o&&clearTimeout(o),n.unsubscribe()}}function Ha(t,e,s){let r=[],o=null;const n=()=>{r.length>0&&(s([...r]),r=[])},i=C(t,a=>{a&&(r.push(a),o||(o=setTimeout(()=>{n(),o=null},e)))});return()=>{o&&(clearTimeout(o),n()),i.unsubscribe()}}function un(t,e=1){const s=[];return C(t,r=>{r&&(s.push(r),s.length>e&&s.shift())}),{subscribe:r=>(s.forEach(o=>r(o)),C(t,r))}}function Ka(t,e){const s=t.map(r=>C(r,o=>{o&&e(r,o)}));return()=>{s.forEach(r=>r.unsubscribe())}}function qa(t,e){let s=t;const r=[],o=new Set;return Object.values(e).forEach(n=>{Object.keys(n).forEach(i=>{o.add(i)})}),o.forEach(n=>{const{unsubscribe:i}=C(n,a=>{const c=e[s];c&&c[n]&&(s=c[n](a))});r.push(i)}),{get state(){return s},unsubscribe:()=>{r.forEach(n=>n())}}}function za(t,e,s,r){const o=Gr(e,r);return q(t,s),o}async function*Va(t){const e=[],s=[],r=C(t,o=>{o&&(s.length>0?s.shift()(o):e.push(o))});try{for(;;)e.length>0?yield e.shift():yield await new Promise(o=>{s.push(o)})}finally{r.unsubscribe()}}const Gh={once:Vr,waitFor:Gr,waitForAll:La,race:Fa,filter:Na,map:Ua,debounce:ja,throttle:Ba,buffer:Ha,replay:un,merge:Ka,stateMachine:qa,request:za,eventIterator:Va},Yh=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:Gh,buffer:Ha,debounce:ja,eventIterator:Va,filter:Na,map:Ua,merge:Ka,once:Vr,race:Fa,replay:un,request:za,stateMachine:qa,throttle:Ba,waitFor:Gr,waitForAll:La},Symbol.toStringTag,{value:"Module"}));async function Yr(t,e){const{getCurrentState:s,transformState:r,shouldUseFetchedState:o,timeout:n}=e,i=ln(t,n),a=await s(),c=r?r(a):a;return o&&o(c)?(i.catch(()=>{}),c):await Promise.race([i,new Promise(d=>{setTimeout(()=>d(c),100)})])}function Ga(t,e,s){const{getCurrentState:r,transformState:o}=s;let n=!1;const i=C(t,a=>{a&&(n=!0,e(a))});return Promise.resolve(r()).then(a=>{const c=o?o(a):a;n||e(c)}).catch(a=>{console.error("Failed to fetch initial state:",a)}),i.unsubscribe}function Ya(t,e){let s;const r=new Set,o=async()=>{try{typeof e=="string"?s=await(await fetch(e)).json():s=await e(),r.forEach(a=>a(s))}catch(a){throw console.error("Failed to fetch initial state:",a),a}};C(t,a=>{a!=null&&a.body&&(s=a.body,r.forEach(c=>c(s)))});let n=!1;const i=()=>{n||(n=!0,o())};return{get state(){return s},async getState(){return i(),s===void 0&&await new Promise(a=>{const c=()=>{s!==void 0?a():setTimeout(c,10)};c()}),s},subscribe(a){return i(),r.add(a),s!==void 0&&a(s),()=>{r.delete(a)}},async refresh(){return await o(),s}}}async function dn(t,e){if(typeof t=="string")return Yr(t,e);const s=t,{getCurrentState:r,shouldUseFetchedState:o,timeout:n}=e,i=await r(),a=e.transformState?e.transformState(i):i;if(o&&o(a))return a;const c=s.map(d=>ln(d,n)),u=await Promise.all(c);return u[u.length-1]}function Wa(t,e,s){const{fetchMissedEvents:r,checkInterval:o=3e4,deduplicateById:n}=s,i=new Set,a=C(t,async u=>{if(u){if(n){const d=n(u);if(i.has(d))return;i.add(d),i.size>1e3&&Array.from(i).slice(0,500).forEach(f=>i.delete(f))}await e(u)}}),c=setInterval(async()=>{try{const u=await r(),d=Array.isArray(u)?u:[u];for(const h of d)if(n){const f=n(h);i.has(f)||(i.add(f),await e(h))}else await e(h)}catch(u){console.error("Failed to fetch missed events:",u)}},o);return()=>{a.unsubscribe(),clearInterval(c)}}function Qa(t){const{connectEvent:e,disconnectEvent:s,errorEvent:r,dataEvent:o,fetchInitialState:n,reconnectDelay:i=5e3}=t,a={state:"disconnected",data:void 0,async waitForConnection(d){if(a.state==="connected"&&a.data)return a.data;const h=await Yr(e,{getCurrentState:n,shouldUseFetchedState:f=>!!f,timeout:d});return a.state="connected",a.data=h,u(),h},subscribe(d){return c.add(d),d(a),()=>{c.delete(d)}},async reconnect(){a.state="connecting",u();try{const d=await n();a.state="connected",a.data=d,u()}catch{a.state="error",u(),setTimeout(()=>{a.state==="error"&&a.reconnect()},i)}}},c=new Set,u=()=>{c.forEach(d=>d(a))};return C(e,d=>{a.state="connected",d!=null&&d.body&&(a.data=d.body),u()}),C(s,()=>{a.state="disconnected",u(),setTimeout(()=>{a.state==="disconnected"&&a.reconnect()},i)}),r&&C(r,()=>{a.state="error",u()}),o&&C(o,d=>{d!=null&&d.body&&a.state==="connected"&&(a.data=d.body,u())}),a.reconnect(),a}const Wh={waitForOrGetState:Yr,subscribeWithInitialState:Ga,createStatefulEventStream:Ya,waitForAllWithState:dn,createResilientEventHandler:Wa,createConnectionStateManager:Qa},Qh=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:Wh,createConnectionStateManager:Qa,createResilientEventHandler:Wa,createStatefulEventStream:Ya,subscribeWithInitialState:Ga,waitForAllWithState:dn,waitForOrGetState:Yr},Symbol.toStringTag,{value:"Module"})),Zh=(t,e=0)=>{if(!+t)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,r=e<0?0:e,o=["bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(t)/Math.log(s)),i=parseFloat((t/Math.pow(s,n)).toFixed(r)),a=o[n];return{value:i,scale:a,toString:()=>`${i} ${a}`}};function hn(t){let e="pending",s;const r=t.then(n=>{e="success",s=n},n=>{e="error",s=n});return{read:()=>{switch(e){case"pending":throw r;case"error":throw s;default:return s}}}}function ut(){return"xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}function Xh(t,e){e.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(r=>{const o=Object.getOwnPropertyDescriptor(s.prototype,r);Object.defineProperty(t.prototype,r,o)})})}function Jh(t,e){const s=t??[],r=e??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const fn=(t,e)=>{const s=t.map(n=>n.id);return e.map(n=>n.id).filter(n=>!s.includes(n))},Za=t=>t,pn=t=>t,ef=({container:t,onAddItem:e,onUpdateItem:s,onRemoveItem:r=Za,idMapper:o=pn})=>n=>{const i=n.map(o),c=fn(i,t.data).map(r).filter(Boolean);t.removeAll(c);const u=i.map(d=>{const h=t.getModel(d.id);return h&&s?s(d,h):e(d)}).filter(Boolean);t.addAll(u)},tf=({container:t,onAddItem:e,onRemoveItem:s=Za,idMapper:r=pn})=>o=>{const n=o.map(r);fn(n,t.models).forEach(s),n.forEach(e)},sf=({items:t,onAddItem:e,onRemoveItem:s,idMapper:r=pn})=>o=>{const n=o.map(r);fn(n,t).forEach(s),n.forEach(e)},rf=(t,e="parent-")=>{let s=t;return s.startsWith(e)&&(s=s.replace(e,"")),s},Di=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),xi=[{amount:60,name:"seconds"},{amount:60,name:"minutes"},{amount:24,name:"hours"},{amount:7,name:"days"},{amount:4.34524,name:"weeks"},{amount:12,name:"months"},{amount:Number.POSITIVE_INFINITY,name:"years"}];function Xa(t){let e=(t.getTime()-Date.now())/1e3;for(let s=0;s<=xi.length;s++){const r=xi[s];if(Math.abs(e)<r.amount)return Di.format(Math.round(e),r.name);e/=r.amount}return Di.format(Math.round(e),"years")}const gn=t=>t%4===0&&t%100!==0||t%400===0,mn=(t,e)=>[31,gn(t)?29:28,31,30,31,30,31,31,30,31,30,31][e],Ja=(t,e)=>{const s=new Date(t),r=t.getDate();return s.setDate(1),s.setMonth(s.getMonth()+e),s.setDate(Math.min(r,mn(s.getFullYear(),s.getMonth()))),s},ec=(t,e)=>{const s=new Date(t);return s.setDate(s.getDate()+e),s},$t="en-US",tc={short:{year:"numeric",month:"2-digit",day:"2-digit"},medium:{year:"numeric",month:"short",day:"2-digit"},long:{year:"numeric",month:"long",day:"numeric"},full:{year:"numeric",month:"long",day:"numeric",weekday:"long"}},sc={short:{hour:"2-digit",minute:"2-digit",hour12:!0},medium:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0},long:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZoneName:"short"},full:{hour:"2-digit",minute:"2-digit",hour12:!0,timeZoneName:"long"}},rc=(t,{dateStyle:e="short",locales:s=$t}={dateStyle:"short",locales:$t})=>{const r=e==="short"?tc.short:{dateStyle:e};return new Intl.DateTimeFormat(s,r).format(t)},oc=(t,{locales:e=$t,timeStyle:s="short"}={locales:$t,timeStyle:"short"})=>{const r=sc[s];return new Intl.DateTimeFormat(e,r).format(t)},nc=(t,{dateStyle:e="short",locales:s=$t,timeStyle:r="short"}={dateStyle:"short",locales:$t,timeStyle:"short"})=>{const o={...e&&tc[e],...r&&sc[r]};return new Intl.DateTimeFormat(s,o).format(t)},of=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:ec,addMonthsToDate:Ja,formatDate:rc,formatDateSince:Xa,formatDateTime:nc,formatTime:oc,getDaysInMonth:mn,isLeapYear:gn},Symbol.toStringTag,{value:"Module"}));function ic(t,e,s=300){let r;return(...o)=>{clearTimeout(r),r=setTimeout(()=>{e.apply(t,o)},s)}}const ee="canvas-renderer",mo=new Map,Ai=new Map,yo=new Map,bo=new Map,js=(t,e)=>{ac[t]=e},ac={indexExtension:{registerIndexExtension:(t,e)=>{const s=bo.get(t)||{};Object.assign(s,e),bo.set(t,e)},loadIndexExtensions:t=>bo.get(t)||{}},loader:{registerLoader:(t,e)=>{Ai.set(t,e)},executeLoader:async(t,e)=>{const s=Ai.get(t);if(s)return await s(e)}},propertyMapper:{registerPropertyMapper:(t,e)=>{yo.set(t,e)},hasMapper:t=>yo.has(t),executeMapper:(t,e,s)=>{const r=yo.get(t);return r?r(e,s):""}},dataMapper:{registerDataMapper:(t,e)=>{const s=mo.get(t)||[];s.push(e),mo.set(t,s)},executeMapper:async(t,e,s)=>{const r=mo.get(t);if(!r)return{};const o={};for(const n of r){const i=await n(e,s);Object.assign(o,i)}return o}},canvas:{registerRenderer:(t,e)=>{if(!$[ee]){console.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${t}".`);return}$[ee].register(t,e)}}},$=ac,nf=async({context:t,extension:e})=>{const s=await $.loader.executeLoader(e,{});return t==null||t.set(e,s),s},af=async({extension:t,contextData:e,data:s})=>await $.dataMapper.executeMapper(t,s,e),cf=async({extension:t,contextData:e,data:s})=>await $.propertyMapper.executeMapper(t,s,e),lf=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:af,executeLoaderExtension:nf,executePropertyMapperExtension:cf},Symbol.toStringTag,{value:"Module"})),uf="Extensions";class df{constructor(){l(this,"extensions");this.extensions={}}register(e,s,r){this.extensions[e]={},this.extensions[e][s]={component:r}}get(e,s){if(!this.extensions[e])throw new Error(`Extension point ${e} not found`);return this.extensions[e][s]}get allExtensions(){return this.extensions}}const be=(t=null)=>(t||window.location.search.replace("?","")).split("&").map(e=>{const[s,r]=e.split("=");return[s,decodeURIComponent(r||"")]}).reduce((e,[s,r])=>(e[s]=r,e),{}),hf="studio.enable.releases",cc="studio.tools.preview",ff="studio.relax.store.validation",lc="studio.log.debug",uc="studio.log.info",pf={profiles:[cc]};var Sa;const gf=((Sa=globalThis.getKosConfig)==null?void 0:Sa.call(globalThis))||JSON.stringify(pf),dc=JSON.parse(gf);globalThis.kosConfig=dc;const yn=dc,hc=()=>yn.profiles||[],Po=t=>hc().includes(t),mf=()=>yn.logging||!1,yf=()=>{const t=Po(lc),e=Po(uc);return t?"DEBUG":e?"INFO":void 0},fc=()=>{const t=be(),e=yf(),r=t.kosLogLevel??e??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},pc=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",gc=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",mc="ws-log",bf=D.methodFactory,yc=pc(),vf=gc();D.methodFactory=function(t,e,s){const r=bf(t,e,s);return function(...o){var c;const n=s?String(s):"",i=n?`[${String(n).substring(n.lastIndexOf(":")+1)}] | `:"[root] | ",a=o.map(u=>typeof u=="object"?JSON.stringify(u):String(u)).join(" ");r(`${i}${a}`),(c=globalThis==null?void 0:globalThis.kosConfig)!=null&&c.logging&&globalThis.kosLog&&(s!==mc||yc&&vf)&&globalThis.kosLog(`UI: ${i}${a}`)}};let bc=fc();D.setLevel(bc);window.setKosLogLevel=t=>{bc=t,D.setLevel(t)};const mr=D.getLogger(mc);window.enableKosMessageLog=()=>{mr.setLevel(D.levels.INFO)};window.disableKosMessageLog=()=>{mr.setLevel(D.levels.ERROR)};yc?window.enableKosMessageLog():window.disableKosMessageLog();const wf=["color: black","display: block","background-color: lightgreen","padding: 4px","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),Ef=["color: black","display: block","padding: 4px","background-color: yellow","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),Ws=t=>e=>{D.getLevel()<=t&&e()},m={...D,ifDebug:Ws(D.levels.DEBUG),ifInfo:Ws(D.levels.INFO),ifWarn:Ws(D.levels.WARN),ifError:Ws(D.levels.ERROR),getLogger:t=>D.getLogger(`kos::${t}`),getLoggers:()=>D.getLoggers(),createLogger:({name:t,group:e})=>{var n,i,a,c;const s=`${e?`${e}:`:"kos"}::${t}`,r=D.getLogger(s);let o=(i=(n=globalThis.kos.logOverrides)==null?void 0:n.find(u=>u.name===s))==null?void 0:i.level;return o?r.setLevel(o):(o=(c=(a=globalThis.kos.logOverrides)==null?void 0:a.find(u=>s.startsWith(u.name)))==null?void 0:c.level,o&&r.setLevel(o)),r},wsSend:(...t)=>{const e=String(t).replace(/\n/g,"\\n");mr.info(`%c⬆ ${e}`,wf)},wsReceive:(...t)=>{const e=String(t).replace(/\n/g,"\\n");mr.info(`%c⬇ ${e}`,Ef)}},vc="featureFlagResolver",Qs=new Map;js(vc,{register:(t,e)=>{var s;Qs.has(t)||Qs.set(t,[]),(s=Qs.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Qs.get(t);if(!s)return[];const r=s.map(a=>a(e)),n=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(m.info(`Feature flag resolver ${t} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(n)).reduce((a,c)=>(a[c]=!0,a),{});return Ec.updateFlags(i),Object.keys(i)}});const Mf="kos.loader.featureFlag";class wc{constructor(e={}){l(this,"flags",{});this.flags=e}isFeatureEnabled(e){return!!this.flags[e]}enableFeature(e){this.flags[e]=!0}disableFeature(e){this.flags[e]=!1}toggleFeature(e){this.flags[e]=!this.flags[e]}updateFlags(e){this.flags={...this.flags,...e}}}window.KosFeatureFlags=window.KosFeatureFlags??new wc;const Ec=window.KosFeatureFlags,Mc=(t,e,s)=>{s/=100;const r=e*Math.min(s,1-s)/100,o=n=>{const i=(n+t/30)%12,a=s-r*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*a).toString(16).padStart(2,"0")};return`#${o(0)}${o(8)}${o(4)}`},Tc=t=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(t);if(!s)throw Error("Invalid HSL string");return Mc(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},_c=(t,e)=>getComputedStyle(t).getPropertyValue(e),Tf=(t,e)=>Tc(_c(t,e)),_f=(t,e)=>{const s={...t};return s.id&&delete s.id,s},ko=(t,e,s=_f)=>{const r=s(t,e);M.runInAction(()=>{Object.assign(e,r)})},J=Symbol("SubscriptionHandlers"),F=Symbol("DependencyModels"),gs=Symbol("FutureService"),ze=Symbol("ChildModels"),ms=Symbol("ParentModel"),ys=Symbol("LogConfig"),cr=Symbol("ReferenceConfig"),bn=Symbol("KosModelSymbol"),it=Symbol("ModelEffects"),Ve=Symbol("CompanionParentModel"),vn=Symbol("FutureContainerSetup"),wn=Symbol("MultipleFutureContainerSetup"),bs=Symbol("FutureAliases"),En=Symbol("TroubleAwareSetup"),Mn=Symbol("LoggerSetup"),Tn=Symbol("ContainerAwareSetup"),Bs=Symbol("StateMachineSetup"),St=Symbol("StateEntryHandlers"),vs=Symbol("StateExitHandlers"),Sf=Symbol("StateActionHandlers"),Hs=Symbol("OptionsRequired"),Of=m.createLogger({group:"decorators",name:"fsm-injection"});function Sc(t){const e=t[Bs];if(!e)return;const{config:s,options:r}=e;Df(t,s,r),xf(t,r);const o=Cf(t);If(t,s,r,o),$f(t,s,r)}function If(t,e,s,r){t.transition=Pf(t,e,s,r.entry,r.exit),t.canTransition=Hf(t,e,s),t.isInState=Kf(t,s)}function $f(t,e,s){Af(t),Rf(t,e,s)}function Cf(t){const e=t.constructor.prototype[St]||new Map,s=t.constructor.prototype[vs]||new Map;return{entry:e,exit:s}}function Df(t,e,s){t._fsmConfig=e,t._fsmOptions=s}function xf(t,e){const{stateProperty:s,trackHistory:r}=e,o=t._fsmConfig;t[s]=o.initial,t._fsmInitialized=!0,t.isTransitioning=!1,r&&(t.stateHistory=[{state:o.initial,timestamp:new Date}])}function Af(t){Object.defineProperty(t,"isFsmInitialized",{get(){return this._fsmInitialized},enumerable:!0,configurable:!0})}function Rf(t,e,s){const{stateProperty:r}=s;Object.defineProperty(t,"allowedTransitions",{get(){if(!this._fsmInitialized)return[];const o=this[r],n=this._fsmConfig.states[o];return n!=null&&n.on?Object.keys(n.on):[]},enumerable:!0,configurable:!0})}function Pf(t,e,s,r,o){const{stateProperty:n,throwOnInvalid:i}=s;return function(a){if(!this._fsmInitialized){kf(e.initializeAt,i);return}const c=this[n],u=Lf(c,a,this._fsmConfig,i);u&&Nf(this,c,u,a,n,r,o,s)}}function kf(t,e){const s=`Cannot transition: FSM not initialized. Waiting for ${t} lifecycle phase.`;if(e)throw new Error(s);console.warn(s)}function Lf(t,e,s,r){var i;const o=s.states[t],n=(i=o==null?void 0:o.on)==null?void 0:i[e];if(!n){Ff(t,e,r);return}return n}function Ff(t,e,s){const r=`Invalid transition: Event "${e}" not allowed from state "${t}"`;if(s)throw new Error(r);console.warn(r)}function Nf(t,e,s,r,o,n,i,a){t.isTransitioning=!0;try{Uf(t,e,i),t[o]=s,Bf(t,s,r,a),jf(t,s,n)}finally{t.isTransitioning=!1}}function Uf(t,e,s){const r=s.get(e);r&&typeof t[r]=="function"&&t[r]()}function jf(t,e,s){const r=s.get(e);r&&typeof t[r]=="function"&&t[r]()}function Bf(t,e,s,r){r.trackHistory&&t.stateHistory&&t.stateHistory.push({state:e,timestamp:new Date,event:s})}function Hf(t,e,s){const{stateProperty:r}=s;return function(o){var a;if(!this._fsmInitialized)return!1;const n=this[r],i=this._fsmConfig.states[n];return((a=i==null?void 0:i.on)==null?void 0:a[o])!==void 0}}function Kf(t,e){const{stateProperty:s}=e;return function(r){return this._fsmInitialized?this[s]===r:!1}}function Oc(t,e){const s=t[Bs];if(!s)return;const{config:r,options:o}=s,{stateProperty:n}=o;r.initializeAt===e&&(t._fsmInitialized||(qf(t,n,r.initial),t._fsmInitialized=!0,zf(t,r.initial,o),Vf(t,r.initial),Of.debug(`FSM initialized for model ${t.id} at lifecycle ${e} with initial state "${r.initial}"`)))}function qf(t,e,s){t[e]=s}function zf(t,e,s){s.trackHistory&&t.stateHistory&&t.stateHistory.push({state:e,timestamp:new Date})}function Vf(t,e){const r=(t.constructor.prototype[St]||new Map).get(e);r&&typeof t[r]=="function"&&t[r]()}const De=(t,e)=>{t[ze]=t[ze]||{},t[ze][e]=!0},dt=t=>`{PROP_${String(t)}}`,Gf=t=>`{PROP_${String(t)}}`,Yf=dt("kosParentId"),Wr=t=>e=>{e[ms]=e[ms]||{};const s=(t==null?void 0:t.parentId)||Yf;e[ms]={parentId:s},e.prototype[Hs]=!0};function Wf(t){return e=>{const s=(t==null?void 0:t.mode)||"decorator",r=(t==null?void 0:t.parentProperty)||"companionParent",o=(t==null?void 0:t.excludeProperties)||[],n=t==null?void 0:t.lifecycle;return Wr()(e),e.prototype[Ve]={mode:s,parentProperty:r,excludeProperties:o,lifecycle:n},e}}function Ic(t){return e=>{const s=t!=null&&t.legacy?"_models":(t==null?void 0:t.containerProperty)||"container",r=(t==null?void 0:t.includeMethods)!==!1,o=(t==null?void 0:t.includeGetters)!==!1,n=(t==null?void 0:t.modelsProperty)||"models",i=(t==null?void 0:t.containerOptions)||{};return e.prototype[Tn]={containerProperty:s,includeMethods:r,includeGetters:o,modelsProperty:n,containerOptions:i,legacy:(t==null?void 0:t.legacy)||!1},e}}function Qf(t,e,s){const r=s.value;s.value=function(...o){const n=G.getContext(this.id);return o.push(n),r.apply(this,o)}}const Qr=Symbol("KosExecutionContext");function _n(t){return t&&typeof t=="object"&&Qr in t}function Zf(t){return e=>{const s=(t==null?void 0:t.mode)||"full",r=(t==null?void 0:t.handlerProperty)||"futureHandler";return e.prototype[vn]={mode:s,handlerProperty:r},e}}function Xf(t){return e=>{const s=(t==null?void 0:t.mode)||"full",r=(t==null?void 0:t.handlerProperty)||"futureHandler";return e.prototype[wn]={mode:s,handlerProperty:r},e}}var x=(t=>(t.INIT="init",t.LOAD="load",t.READY="ready",t.ACTIVATE="activate",t.ONLINE="online",t))(x||{}),qe=(t=>(t.CREATE="create",t.CONTINUE="continue",t.FAIL="fail",t))(qe||{});const Jf=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:x,DependencyResolutionPolicy:qe},Symbol.toStringTag,{value:"Module"})),ke=Symbol("HttpRouteHandlers"),Ri="__httpBrowserRouter";function Zr(t){return function(s){return function(r,o,n){r[ke]=r[ke]||[];const i={method:t,path:s,handler:o};return r[ke].push(i),r[F]=r[F]||{},r[F][Ri]||(r[F][Ri]={modelType:"browser-router-model",lifecycle:x.INIT}),n}}}const $c=Zr("GET"),Ks=Zr("POST"),ep=Zr("PUT"),Cc=Zr("DELETE"),tp=Cc;function yr(t){return!!(t!=null&&t[ke])&&t[ke].length>0}function Dc(t){return(t==null?void 0:t[ke])||[]}const sp=({group:t}={group:""})=>e=>{e[ys]=e[ys]||{},e[ys]={group:t}};class xc{static create({modelId:e,modelTypeName:s,component:r}){const o=[r??"kos",s,e].filter(Boolean).join(".");return m.createLogger({name:o})}}function Ac(t){return e=>{const s=(t==null?void 0:t.loggerProperty)||"logger",r=t==null?void 0:t.loggerContext;e.prototype[Mn]={loggerProperty:s,loggerContext:r};const o=()=>{var i;return(i=e.prototype[bn])==null?void 0:i.type};let n;return Object.defineProperty(e.prototype,s,{get(){if(!n){const i=o();n=xc.create({modelTypeName:r||i,component:"kos-model"})}return n},enumerable:!1,configurable:!1}),e}}function Rc(t){return(e,s,r)=>{e[it]=e[it]||{},e[it][s]={dependencies:t==null?void 0:t.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const rp=t=>(e,s)=>{e[cr]=e[cr]||{},e[cr][s]=t},vo=m.createLogger({name:"resolve-parameters"}),he=({value:t,modelId:e,modelData:s})=>{let r=t;if(Array.isArray(r))return[...t];if(typeof r!="string"&&typeof r!="object")return r;if(typeof r=="object")r=Object.keys(r).reduce((o,n)=>(o[n]=he({value:r[n],modelId:e,modelData:s}),o),{});else if(typeof r=="string"){const o=new RegExp("{PROP_(.+?)}","g");let n=r!=null&&r.includes(gr)?r.replace(gr,e):r;if(s){let i=!1;const a=/^{PROP_.+?}$/.test(n);if(n=n.replace(o,(c,u)=>{if(Object.getOwnPropertyNames(s).includes(u)||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(u)){const h=s[u];return h!=null?(vo.debug(`Resolved ${c} to ${h}`),h):(vo[a?"debug":"warn"](`Property ${u} is null or undefined${a?"":" in composite string"}, marking for undefined return`),i=!0,c)}return vo[a?"debug":"warn"](`Property ${u} not found in modelData${a?"":" for composite string"}`),c}),i)return}return n}else return r;return r};function op(t,e,s,r){const o=he({value:t.path,modelId:e.id,modelData:e}),n=he({modelId:e.id,modelData:e,value:{...typeof t.pathParams=="function"?t.pathParams(e):t.pathParams||{},...(r==null?void 0:r.pathParams)||{}}}),i=he({modelId:e.id,modelData:e,value:{...typeof t.queryParams=="function"?t.queryParams(e):t.queryParams||{},...(r==null?void 0:r.queryParams)||{}}}),a=(r==null?void 0:r.body)||(typeof t.body=="function"?t.body(e):t.body),u={...(typeof t.requestOptions=="function"?t.requestOptions(e,...s):t.requestOptions)||{},...(r==null?void 0:r.requestOptions)||{}},d={};return n&&Object.keys(n).length>0&&(d.path=n),i&&Object.keys(i).length>0&&(d.query=i),{resolvedPath:o,apiParams:d,finalBody:a,finalRequestOptions:u}}async function np(t,e,s,r,o,n){const i=(e||"get").toLowerCase(),a=t;switch(i){case"get":return await a.get(s,r,n);case"post":return await a.post(s,r,o,n);case"put":return await a.put(s,r,o,n);case"delete":return await a.delete(s,r,o,n);default:return await a.get(s,r,n)}}function ip(t,e,s,r){if(!s)return[t,null];switch(s.strategy){case"log":return console.error(`Service request status ${e==null?void 0:e.status} error: ${t}`),s.onError&&s.onError(new Error(t),r),[null,s.defaultValue];case"ignore":return[null,s.defaultValue];case"default":return[null,s.defaultValue];case"throw":default:return[t,null]}}const at=Symbol("ServiceRequestHandlers"),Pi=new WeakMap;function ht(t){return(e,s,r)=>{var a;e[at]=e[at]||{};const o=r.value,n={...t,handlerMethod:s,originalHandler:o},i=`${((a=t.method)==null?void 0:a.toUpperCase())||"GET"}:${String(t.path)}`;if(e[at][i]=n,!t.lifecycle){const c=function(...u){const d=u[u.length-1],h=async f=>{const p=Pi.get(c);if(!p)throw new Error("Service request metadata not found for method");try{const{default:y}=await Promise.resolve().then(()=>al),{resolvedPath:w,apiParams:E,finalBody:_,finalRequestOptions:L}=op(p,this,u,f),[U,I]=await np(y,p.method,w,E,_,L);if(U)return ip(U,I,p.errorHandler,this);let S=I;return p.transform&&(S=p.transform(I)),[null,S]}catch(y){return[y.message||"Unknown error",null]}};if(_n(d))return d.$request=h,o.apply(this,u);{const f={[Qr]:!0,$request:h};return o.apply(this,[...u,f])}};Pi.set(c,n),r.value=c}return r}}var Pc=(t=>(t.GET="GET",t.PUT="PUT",t.POST="POST",t.DELETE="DELETE",t))(Pc||{}),se=(t=>(t.IMMEDIATE="immediate",t.SINGLE="single",t.TTL="ttl",t.PERMANENT="permanent",t.MANUAL="manual",t))(se||{}),nt=(t=>(t.ALL="all",t.AFTER_REQUEST="after-request",t.AFTER_RESPONSE="after-response",t.NONE="none",t))(nt||{});const ap=m.createLogger({name:"kos-state-machine"});function cp(t,e){return s=>(s.prototype[Bs]={config:{...t,initializeAt:t.initializeAt||x.READY},options:{stateProperty:(e==null?void 0:e.stateProperty)||"currentState",trackHistory:(e==null?void 0:e.trackHistory)||!1,throwOnInvalid:(e==null?void 0:e.throwOnInvalid)!==!1}},s)}function lp(t){return(e,s)=>{e[St]||(e[St]=new Map),e[St].set(t,s)}}function up(t){return(e,s)=>{e[vs]||(e[vs]=new Map),e[vs].set(t,s)}}function dp(t){return(e,s,r)=>{const o=r.value;return r.value=function(...n){var u,d;if(!this.isFsmInitialized)return o.apply(this,n);const a=this.currentState;if(!t.allowedStates.includes(a)){const h=`Method ${String(s)} cannot be called from state "${a}". Allowed states: ${t.allowedStates.join(", ")}`;if(t.throwOnInvalid!==void 0?t.throwOnInvalid:((d=(u=this[Bs])==null?void 0:u.options)==null?void 0:d.throwOnInvalid)!==!1)throw new Error(h);ap.warn(h);return}return o.apply(this,n)},r}}function hp(t){return e=>{const s=(t==null?void 0:t.pathProperty)||"path";return e.prototype[En]={pathProperty:s},e.prototype[F]=e.prototype[F]||{},e.prototype[F].troubleContainer={modelType:"trouble-container-model",id:"trouble-container-model",options:{},lazy:!1},e}}const Ht=({modelType:t,id:e,options:s,lifecycle:r,resolutionPolicy:o})=>(n,i)=>{n[F]=n[F]||{},n[F][i]={modelType:t,id:e,options:s,lifecycle:r||x.INIT,resolutionPolicy:o}};class kc{constructor(e,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=Pn.map(new Map),this.context="",this.defaultContext=s||"",this.container=e,M.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(e,s){this.futures.set(s||e.id,e),this.context=s||e.id;const r=s,o=Y(()=>{var n,i;(e.endState||e.progress)&&((i=(n=this.container)==null?void 0:n.onFutureUpdate)==null||i.call(n,e,r))});this.disposers.set(s||e.id,o)}removeFuture(e){var s;this.futures.delete(e||this.context),(s=this.disposers.get(e||this.context))==null||s(),this.disposers.delete(e||this.context)}getFuture(e){return this.futures.get(e||this.context)}get futureMap(){return this.futures}}class Xr{constructor(e){l(this,"disposer");l(this,"_future");l(this,"container");l(this,"onFutureUpdate");this._future=void 0,this.container=e,M.makeAutoObservable(this)}removeFuture(){var e;this._future=void 0,(e=this.disposer)==null||e.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(e){this._future=e;const s=Y(()=>{var r,o;(e.endState||e.progress)&&((o=(r=this.container)==null?void 0:r.onFutureUpdate)==null||o.call(r,e))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var e;return((e=this._future)==null?void 0:e.timeRemaining)||""}get status(){var e;return((e=this._future)==null?void 0:e.status)||"NOT_RESOLVED"}get progress(){var e;return((e=this._future)==null?void 0:e.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(e){throw m.error(e),e}}}const Lc=(t,e)=>{const s=e.type;return t[s]||(t[s]=[]),t[s].push(e),t},Fc=Symbol("KosObservableData"),Jt=Symbol("revision");var BT;class Nc{constructor(){l(this,"map");l(this,BT,1);l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(e,s)=>{var r;return s===Jt||e[s]!==void 0?e[s]:this.atomMap.has(s)&&(r=this.atomMap.get(s))!=null&&r.reportObserved()?this.getValue(s):this.getValue(s)},set:(e,s,r)=>{var o;return this.map.has(s),this.setValue(s,r),this.atomMap.has(s)||this.atomMap.set(s,M.createAtom(s.toString())),(o=this.atomMap.get(s))==null||o.reportChanged(),!0},ownKeys:()=>Array.from(this.map.keys())});this.map=M.observable.map(new Map),M.makeObservable(this,{[Jt]:M.observable})}setValue(e,s){const r=this.map.has(e);this.map.set(e,s),r||M.action(()=>{this[Jt]++})()}getValue(e){return this.map.get(e)}has(e){return this.map.has(e)}get entries(){return Array.from(this.map.entries())}get keys(){return this[Jt],Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(e){e&&Object.keys(e).forEach(s=>{this.setValue(s,e[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}BT=Jt;Nc.prototype[Fc]=!0;function fp(t,e){return new Proxy(t,{construct:(s,r)=>{const o=new t(...r);return o.setValues(e),o.proxy}})}const Ie=t=>{const e=fp(Nc,t);return new e(t)};function pp(t,e){return t.length!==e.length?!1:t.every(s=>e.includes(s))}class Sn{constructor({container:e,key:s}){l(this,"_container");l(this,"_map");l(this,"_key");l(this,"data");this._container=e,this._map=M.observable.map(new Map),this._key=s,this.data=Ie(),this.generateIndex(),M.autorun(()=>{this._container.revision&&this.generateIndex()}),M.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(e,s,r=this._map,o=this.data){const n=r.get(e)||new Set;n.add(s),r.set(e,n),o[e]=Array.from(n)}resolveIndex(e,s){this.data.keys.filter(o=>!Object.keys(s).includes(o)).forEach(o=>{delete this.data[o],this._map.delete(o)}),Object.keys(s).forEach(o=>{const n=s[o],i=this.data[o]||[];if(pp(n,i))m.debug(`KosContainerIndex - Index ${o} is the same`);else{this.data[o]=n;const a=e.get(o)||new Set;this._map.set(o,a)}})}generateIndex(){M.runInAction(async()=>{const e=new Map,s={};for(const r of this._container.data){const o=typeof this._key=="function"?await this._key(r):r[this._key];Array.isArray(o)?o.forEach(n=>{this.addItemToIndex(n,r,e,s)}):typeof o=="string"||typeof o=="number"?this.addItemToIndex(String(o),r,e,s):typeof o=="boolean"&&this.addItemToIndex(String(o),r,e,s)}this.resolveIndex(e,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(e){const s=this._map.get(e);return s?Array.from(s):[]}}function gp(t,e,s=[]){const r=Object.getOwnPropertyDescriptors(t);return Object.keys(r).filter(i=>M.isComputedProp(t,i)).filter(i=>s.includes(i)).map(i=>M.reaction(()=>t[i],(a,c)=>{e({name:i,newValue:a,oldValue:c})}))}const ne=m.createLogger({name:"kos-container-model"});class xe{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"_parentId");l(this,"idx");l(this,"_maxCapacity");l(this,"_evictionStrategy");l(this,"_evictionBatchSize");l(this,"_insertionOrder",[]);l(this,"_accessTimes");l(this,"_customEvictionFilter");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1;const s=e!=null&&e.extensionId?$.indexExtension.loadIndexExtensions(e.extensionId):{},r=(e==null?void 0:e.indexMap)||{};this._optionsMap={...r,...s};const o=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=M.observable.map(o),this.idx=Ie(),this._parentId=e==null?void 0:e.parentId,this._maxCapacity=e==null?void 0:e.maxCapacity,this._evictionStrategy=(e==null?void 0:e.evictionStrategy)||"fifo",this._evictionBatchSize=(e==null?void 0:e.evictionBatchSize)??Math.max(10,Math.ceil(((e==null?void 0:e.maxCapacity)??100)*.1)),this._customEvictionFilter=e==null?void 0:e.customEvictionFilter,this._evictionStrategy==="lru"&&this._maxCapacity&&(this._accessTimes=M.observable.map(new Map)),M.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new Sn({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get revision(){return this._revision}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s,!0)),this.increment()})}async removeAndDestroy(e){const s=this.getModel(e);if(!s){ne.debug(`Model ${e} not found in container, skipping destroy`);return}this.removeModel(e);try{await Oe(s)}catch(r){throw ne.error(`Failed to destroy model ${e}:`,r),r}}async removeAndDestroyAll(e){const s=e.map(n=>this.getModel(n)).filter(n=>n!==void 0);if(s.length===0){ne.debug("No models found to destroy");return}this.removeAll(e);const r=await Promise.allSettled(s.map(n=>Oe(n)));r.forEach((n,i)=>{n.status==="rejected"&&ne.error(`Failed to destroy model ${s[i].id}:`,n.reason)});const o=r.filter(n=>n.status==="rejected");if(o.length>0)throw new Error(`Failed to destroy ${o.length} of ${s.length} models`)}addModel(e,s){this._persistModel(e),this._trackModelMetadata(e),this._establishModelRelationships(e),this._enforceCapacityLimits(),this._configureModelMonitoring(e),s||this.increment()}_persistModel(e){this._data.set(e.id||"",e)}_trackModelMetadata(e){this._maxCapacity&&(this._insertionOrder.push(e.id||""),this._accessTimes&&this._accessTimes.set(e.id||"",Date.now()))}_establishModelRelationships(e){e.id&&this._parentId&&G.setParentContext(e.id,this._parentId)}_enforceCapacityLimits(){this._maxCapacity&&this._data.size>this._maxCapacity&&this._evictModels()}_configureModelMonitoring(e){const s=this._disposerMap.get(e.id);s&&(s(),this._disposerMap.delete(e.id));const r=Object.entries(this._optionsMap||{}),o=Object.values(this._optionsMap||{}),n=new Map(r.map(([u,d])=>[d,u])),i=u=>{var h,f;o.includes(u.name)&&((h=this.index.get(n.get(u.name)))==null||h.refresh());const d=r.filter(([,p])=>typeof p=="function");for(const[p]of d)(f=this.index.get(p))==null||f.refresh()},a=gp(e,i,o.filter(u=>typeof u=="string")),c=M.observe(e,i);this._disposerMap.set(e.id||"",()=>[c,...a].forEach(u=>u()))}removeModel(e,s){this._data.delete(e);const r=this._insertionOrder.indexOf(e);r!==-1&&this._insertionOrder.splice(r,1),this._accessTimes&&this._accessTimes.delete(e),s||this.increment();const o=this._disposerMap.get(e);o&&(o(),this._disposerMap.delete(e))}updateModel(e){this._data.set(e.id||"",e),this.increment()}getModel(e){const s=this._data.get(e);return s&&this._accessTimes&&this._accessTimes.set(e,Date.now()),s}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(ne.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(e,s){if(this.index.has(e)){const r=this.index.get(e);return r.index.has(s)?r.getByKey(s):(ne.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return ne.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async _evictModels(){if(!this._maxCapacity)return;const e=this._data.size-this._maxCapacity;if(e<=0)return;const s=Math.min(this._evictionBatchSize,e);this._logCapacityWarning(s);const r=this._selectModelsForEviction(s);await this._removeEvictedModels(r),this._logEvictionComplete(r.length),this.increment()}_logCapacityWarning(e){ne.info(`Container capacity exceeded (${this._data.size}/${this._maxCapacity}). Evicting ${e} models using ${this._evictionStrategy} strategy.`,{parentId:this._parentId})}_selectModelsForEviction(e){switch(this._evictionStrategy){case"fifo":return this._selectFifoModels(e);case"lru":return this._selectLruModels(e);case"custom":return this._selectCustomModels(e);default:return this._selectFifoModels(e)}}_selectFifoModels(e){const s=[];for(let r=0;r<e&&this._insertionOrder.length>0;r++){const o=this._insertionOrder.shift();if(!o)continue;const n=this._data.get(o);n&&s.push(n)}return s}_selectLruModels(e){const s=[];return this._accessTimes&&Array.from(this._accessTimes.entries()).sort((o,n)=>o[1]-n[1]).slice(0,e).forEach(([o])=>{const n=this._data.get(o);n&&s.push(n)}),s}_selectCustomModels(e){return this._customEvictionFilter?this._customEvictionFilter(this.data).slice(0,e):(ne.error("Custom eviction strategy specified but no customEvictionFilter provided. Falling back to FIFO.",{parentId:this._parentId}),this._selectFifoModels(e))}async _removeEvictedModels(e){for(const s of e)ne.info(`Evicting model: ${s.id} (type: ${s.constructor.name})`,{modelId:s.id,parentId:this._parentId,strategy:this._evictionStrategy}),this.removeModel(s.id,!0),Oe(s).catch(r=>ne.error(`Failed to destroy evicted model ${s.id}:`,r))}_logEvictionComplete(e){ne.info(`Evicted ${e} models. Current size: ${this._data.size}/${this._maxCapacity}`,{parentId:this._parentId})}async clear(){this._data.forEach(e=>{const s=e.id;Oe(e).then(()=>{ne.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>ne.error(r))}),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}var v=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.READY_FAILED="ready_failed",t.RESETTING="resetting",t.RESET="reset",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.FAILED="failed",t.INACTIVE="inactive",t.ACTIVE="active",t.ACTIVATING="activating",t.DEACTIVATING="deactivating",t))(v||{}),k=(t=>(t.CREATE="create",t.INITIALIZE="init",t.LOAD="load",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.RESET="go_offline",t.UNLOAD="unload",t.FAILED="failed",t.GO_ACTIVE="go_active",t.GO_INACTIVE="go_inactive",t.TIMEOUT="timeout",t))(k||{});const fe=async t=>{if(t.id){const e=O.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error(`Model with ID ${t.id} not found`);await(e==null?void 0:e.whenReady())}else throw new Error("Data model must have a valid ID");return t},Oe=async t=>{await O.getInstance().whenReady(),await O.getInstance().modelManager.initiateDestroyModel(t)},mp=async t=>{if(await O.getInstance().whenReady(),!t.id)throw new Error("Model ID is required");const e=O.getInstance().modelManager.getModelById(t.id);e&&await e.fsm.transitionTo(k.UNLOAD,v.UNLOADED)},yp=async t=>{await O.getInstance().whenReady(),await O.getInstance().modelManager.reloadModel(t),m.debug(`reload model initiated for model ${t.id}, model ready: ${br(t)} - ${Date.now()} `),await fe(t),m.debug(`reload model complete for model ${t.id}, model ready: ${br(t)} - ${Date.now()} `)},bp=async t=>{if(await O.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=O.getInstance().modelManager.getModelById(t);return e==null?void 0:e.modelTypeName},Uc=async t=>{if(await O.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=O.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},$e=t=>{if(!t)throw new Error("Model ID is required");const e=O.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},jc=(t,e)=>{if(!t)throw new Error("Model type is required");return O.getInstance().modelManager.getModelsByType(t).filter(o=>Object.keys(e).every(n=>o[n]===e[n]))},vp=(t,e)=>jc(t,e)[0],wp=(t,e)=>{if(!t.id)throw new Error("Model ID is required");const s=O.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error("Model not found");const r=s.companionModels.get(e);return r==null?void 0:r.modelData},Bc=t=>{if(!t.id)throw new Error("Model ID is required");const e=O.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return Array.from(e.companionModels.all()).map(r=>r.modelData)},Ep=t=>{if(!t)throw new Error("Model ID is required");const e=O.getInstance().modelManager.getModelById(t);if(!e)throw new Error("Model not found");return e.companionModels.data},Lo=(t,e)=>{const s=O.getInstance().modelManager.getModelById(t);if(!s){m.info(`Model not found for id ${t}`);return}return Array.from(s.companionModels.all()).find(o=>e(o.modelData))},_e=t=>e=>Object.getPrototypeOf(e).modelTypeId===t,br=t=>{const e=O.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return e.isReady()},Mp=m.createLogger({name:"kos-model-factory"}),ws={byModelType:t=>O.getInstance().modelManager.getModelFactory(t),getModelInstance:(t,e,s)=>{const r=ws.byModelType(e);if(!r)throw Mp.error(`No registered factory found for model type ${e}. Please register a factory for this model type. `),Error(`No factory found for model type ${e}`);return r.build(t,s)}},ae={Factory:{create:t=>e=>(s,r)=>(r&&G.setParentContext(e,r),ws.getModelInstance(e,t,s))},Singleton:{create:t=>(e,s)=>(s&&G.setParentContext(t,s),ws.getModelInstance(t,t,e))},Model:{instance:t=>e=>ws.getModelInstance(e,t)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const ki=window.KosRegistry.coreModels,wo=window.KosRegistry.preloadModels,Eo=window.KosRegistry.companionModels,Zs=window.KosRegistry.models,A={model:{registerLegacyModel:t=>(e,s)=>(ki.set(e,s),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}),preloadModel:t=>e=>(wo.includes(e)||wo.push(e),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}),register:t=>(e,s)=>{const r=Mo(e)?e.registration():e;return Zs.set(r.type,r),Mo(e)&&e.relatedModels.forEach(o=>Zs.set(o.type,o.registration())),O.getInstance().isReady&&(O.getInstance().modelManager.registry.models[r.type]||(console.info(`Model with type ${r.type} doesn't exist. Adding new registration`),O.getInstance().modelManager.registry.models[r.type]=r.registration[r.type],Mo(e)&&e.relatedModels.forEach(o=>O.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&A.model.preloadModel(t)(r.type),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}},get:t=>Zs.get(t),getAll:()=>Array.from(Zs.entries()),getPreloadModels:()=>wo,getLegacyModels:()=>Array.from(ki.entries()).reduce((t,[e,s])=>(t[e]=s,t),{})},companion:{register:t=>(e,s)=>{const r=Eo.get(e)||[];return r.push(s),Eo.set(e,r),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}},getAll:()=>Array.from(Eo.entries())}},Hc=A.model.registerLegacyModel,Kc=A.model.register,Tp=A.companion.register,_p=A.model.preloadModel,On=t=>typeof t.updateModel=="function",Mo=t=>t.registration!==void 0&&typeof t.registration=="function";class qc{constructor(e){l(this,"singleton");l(this,"type");l(this,"loader");l(this,"class");l(this,"guard");l(this,"factory");l(this,"relatedModels",[]);this.singleton=e.singleton,this.guard=_e(e.type),this.type=e.type,this.loader=`kos.extension.model.loader.${e.type}`,this.factory=e.factory,this.class=e.class}addRelatedModel(e){this.relatedModels.push(e)}registerRelatedModels(){this.relatedModels.forEach(e=>e.register())}register(){A.model.register({})(this.registration()),this.registerRelatedModels()}}class ve extends qc{constructor(e){super({...e,singleton:!1,factory:ae.Factory.create(e.type)})}instance(e){const s=this.factory(e);return{get:()=>{const r=$e(e);if(!r)throw new Error("Model not found with id "+e);if(this.guard(r.model))return r.model;throw new Error("Model is not of type "+this.type)},forceUpdate:{options:r=>({build:()=>{const o=s(r);if(this.guard(o)){if(On(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error("Model is not of type "+this.type)}})},options:r=>({build:()=>{const o=s(r);if(this.guard(o))return o;throw new Error("Model is not of type "+this.type)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!1}},factory:this.factory}}}class Se extends qc{constructor(e){super({...e,singleton:!0,factory:ae.Singleton.create(e.type)})}instance(){const e=this.factory;return{get:()=>{const r=$e(this.type);if(!r)throw new Error("Model not found with id "+this.type);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)},forceUpdate:{options:r=>({build:()=>{const o=e(r);if(this.guard(o)){if(On(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})},options:r=>({build:()=>{const o=e(r);if(this.guard(o))return o;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const Fo=m.createLogger({group:"decorators",name:"kos-model"});function Sp(t,e,s){var n;const r=(n=t[ms])==null?void 0:n.parentId;if(!r)return;const o=he({value:r,modelData:s,modelId:e});o&&typeof o=="string"&&G.setParentContext(e,o)}function Op(t){const e=t[gs];e&&Object.entries(e).forEach(([s,{handler:r}])=>{t[s]=r})}function Ip(t,e){const s=t[F]||{};Object.entries(s).forEach(([r,o])=>{const n=he({value:o.id||o.modelType,modelData:t,modelId:e}),i=Object.entries((o==null?void 0:o.options)||{}).reduce((a,[c,u])=>(a[c]=he({value:u,modelData:t,modelId:e}),a),{});if(typeof n=="string"){if(!o.lazy){const a=O.getInstance().modelManager.createModelInstance(o.modelType,n,i);t[r]=a.data}O.getInstance().modelManager.addDependency(e,n)}})}function $p(t){const e=t[vn];if(!e)return;const{mode:s,handlerProperty:r}=e,o=new Xr(t);t[r]=o,s==="full"&&(Object.defineProperty(t,"future",{get(){return o.future},enumerable:!0,configurable:!0}),Object.defineProperty(t,"progress",{get(){var n;return((n=o.future)==null?void 0:n.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){var n;return((n=o.future)==null?void 0:n.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){var n;return((n=o.future)==null?void 0:n.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function Cp(t){const e=t[wn];if(!e)return;const{mode:s,handlerProperty:r}=e,o=new kc(t);t[r]=o,Object.defineProperty(t,"future",{get(){return o.future},enumerable:!0,configurable:!0});const n=t[bs];n instanceof Map&&n.forEach(i=>{const a=`${i}Future`;Object.defineProperty(t,a,{get(){return o.futureMap.get(i)},enumerable:!0,configurable:!0}),s==="full"&&(Object.defineProperty(t,`${i}Progress`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}Status`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}IsRunning`,{get(){const c=o.futureMap.get(i);return c?!c.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}IsCancelled`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t[`cancel${i.charAt(0).toUpperCase()}${i.slice(1)}`]=async()=>{const c=o.futureMap.get(i);c&&await c.cancelFuture()})}),s==="full"&&(Object.defineProperty(t,"progress",{get(){var i;return((i=o.future)==null?void 0:i.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){var i;return((i=o.future)==null?void 0:i.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){var i;return((i=o.future)==null?void 0:i.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function Dp(t){const e=t[En];if(!e)return;const{pathProperty:s}=e;Object.defineProperty(t,"troubles",{get(){const r=this[s];if(r==null){const o=`@kosTroubleAware: Path property '${s}' is undefined on model ${this.id||"unknown"}. Returning empty troubles array.`;return this.logger&&typeof this.logger.warn=="function"?this.logger.warn(o):console.warn(o),[]}return this.troubleContainer.troubles.getIndexByKey("byIface",r).sort((o,n)=>n.rank-o.rank)},enumerable:!0,configurable:!0}),Object.defineProperty(t,"troubleStatus",{get(){return""},enumerable:!0,configurable:!0}),Object.defineProperty(t,"troublesByType",{get(){return this.troubles.reduce(Lc,{})},enumerable:!0,configurable:!0})}function xp(t,e){const s=t[Tn];if(!s)return;const{containerProperty:r,includeMethods:o,includeGetters:n,modelsProperty:i,containerOptions:a,legacy:c}=s,u={...a,parentId:a.parentId||e},d=new xe(u);t[r]=d,t[ze]||(t[ze]={}),t[ze][r]=d,o&&(t.getModel=h=>d.getModel(h),t.addModel=h=>{d.addModel(h)},t.removeModel=h=>{d.removeModel(h)},t.addAll=h=>{d.addAll(h)},t.removeAll=h=>{d.removeAll(h)},t.removeAndDestroy=async h=>d.removeAndDestroy(h),t.removeAndDestroyAll=async h=>d.removeAndDestroyAll(h)),n&&(Object.defineProperty(t,i,{get(){return d},enumerable:!0,configurable:!0}),Object.defineProperty(t,"data",{get(){return d.data},enumerable:!0,configurable:!0}))}function Ap(t,e){const s=t.constructor.prototype[Ve];if(!s)return;const{mode:r,parentProperty:o,excludeProperties:n}=s,i=e.companionParent;if(!i){Fo.warn("Companion decorator configured but no parent model found in initialData.companionParent");return}if(t.getCompanionParent=()=>i,Object.defineProperty(t,o,{get:()=>i,enumerable:!0,configurable:!0}),r==="composition")return;const a=["init","load","unload","ready","dispose","destroy","activate"],c=["getDependencies","getChildren","update","toJSON","forceUpdate","makeAutoObservable","runInAction","transaction","observe","unobserve","intercept","spy","trace","getCompanionParent"],u=p=>{const y=i.constructor.prototype[J]||{};return Object.values(y).some(w=>{const E=w==null?void 0:w.handler;return E===i[p]||E===i.constructor.prototype[p]})},d=p=>p==="constructor"||p.startsWith("_")||p.startsWith("__")||a.includes(p)||c.includes(p)||n.includes(p)||u(p)||p in t,h=new Set;Object.getOwnPropertyNames(i).filter(p=>!d(p)).forEach(p=>h.add(p));let f=Object.getPrototypeOf(i);for(;f&&f!==Object.prototype;)Object.getOwnPropertyNames(f).filter(p=>!d(p)).forEach(p=>h.add(p)),f=Object.getPrototypeOf(f);for(const p of h)try{const y=i[p];typeof y=="function"?t[p]=(...w)=>y.apply(i,w):Object.defineProperty(t,p,{get:()=>i[p],set:w=>{i[p]=w},enumerable:!0,configurable:!0})}catch(y){Fo.debug(`Skipping companion proxy for property ${p}:`,y)}}function Rp(t){try{return M.makeAutoObservable(t)}catch(e){return Fo.error("Failed to make observable:",e),t}}const Pp={construct(t,e){var c;const[s,r={}]=e,o=G.createContext(s);Sp(t,s,r);const i=!!t.prototype[Mn]?null:m.createLogger({name:t.prototype.modelTypeId,group:((c=t[ys])==null?void 0:c.group)??"kos-model"}),a=new t(s,r,{logger:i,kosContext:o});return Ap(a,r),Op(a),$p(a),Cp(a),Dp(a),xp(a,s),Sc(a),Ip(a,s),Rp(a)}};function R(t){return e=>{var n,i;const s=e,r=typeof t=="string"?{modelTypeId:t,autoRegister:!1}:{autoRegister:!1,...t};s.prototype.modelTypeId=r.modelTypeId,s.prototype[bn]=!0,(n=s.prototype)[J]??(n[J]={}),(i=s.prototype)[F]??(i[F]={}),r.optionsRequired&&(s.prototype[Hs]=!0),m.ifDebug(()=>{m.debug(`Registering model with id ${r.modelTypeId}`)});const o=new Proxy(s,Pp);if(r.singleton!==void 0){let a;r.singleton?a=new Se({class:o,type:r.modelTypeId}):a=new ve({class:o,type:r.modelTypeId}),Object.defineProperty(o,"Registration",{value:a,writable:!1,enumerable:!0,configurable:!1}),r.autoRegister&&a.register()}return o}}const kp=({topic:t,handler:e,websocket:s=!1,condition:r=()=>!0})=>o=>{o[J]=o[J]||{},Array.isArray(t)?t.forEach(n=>{o[J][n]={websocket:s,handler:e,condition:r}}):o[J][t]={websocket:s,handler:ic(o,M.action(e),200),condition:r}};function zc(t,e,s){const r={};if(!t.endsWith("/*"))return r;const o=t.slice(0,-2);if(e.startsWith(o)){const n=e.slice(o.length+1),i=s||"path";r[i]=n}return r}function Vc(t){return t.endsWith("/*")}function B(t){return(e,s,r)=>{const o=Lp(t,r);Up(e,t.topic,o),t.replay&&jp(t.topic,t.replay.bufferSize)}}function Lp(t,e){const{condition:s=(S,Z)=>!0,transform:r=S=>S,websocket:o=!1,fos:n=!1,bridge:i=!1,skipParse:a=!1,lifecycle:c,destinationAddress:u,debounce:d,throttle:h,buffer:f,filter:p,once:y,wildcardName:w,flow:E,requiresBaseline:_}=t,L=e.value,U=Fp(L,{debounce:d,throttle:h,buffer:f,once:y}),I=Np(p,s);return{websocket:o,fos:n,bridge:i,handler:U,condition:I,transform:r,lifecycle:c,skipParse:a,destinationAddress:u,wildcardName:w,flow:E,requiresBaseline:_}}function Fp(t,e){var n,i;let s=t;const r=typeof e.debounce=="number"?e.debounce:(n=e.debounce)==null?void 0:n.delay,o=typeof e.throttle=="number"?e.throttle:(i=e.throttle)==null?void 0:i.interval;return r&&r>0?s=Bp(s,e.debounce):o&&o>0?s=zp(s,e.throttle):e.buffer?s=Vp(async function(c){for(const u of c)await s.call(this,u)},e.buffer):e.once&&(s=Gp(s)),s}function Np(t,e){return t?(s,r,o)=>t(o)?e(s,r,o):!1:e}function Up(t,e,s){t[J]=t[J]||{},Array.isArray(e)?e.forEach(r=>{t[J][r]=s}):t[J][e]=s}function jp(t,e){Yp(t,e)}function Bp(t,e){const s=typeof e=="number"?e:e.delay;return Hp(e)==="discard"?Kp(t,s):qp(t,s)}function Hp(t){return(typeof t=="object"?t.discardIntermediate:!1)?"discard":"accumulate"}function Kp(t,e){let s=null;return function(r){s&&clearTimeout(s),s=setTimeout(()=>{t.call(this,r),s=null},e)}}function qp(t,e){let s=null,r=[];return function(o){r.push(o),s&&clearTimeout(s),s=setTimeout(()=>{const n=[...r];r=[],t.call(this,n),s=null},e)}}function zp(t,e){const s=typeof e=="number"?e:e.interval,r=typeof e=="object"?e.discardIntermediate:!1;let o=0,n=null,i=[],a=!1;const c=function(){if(i.length>0){const u=[...i];i=[],t.call(this,u)}};return function(u){const d=Date.now(),h=d-o;r?h>=s?(o=d,t.call(this,u)):n||(n=setTimeout(()=>{o=Date.now(),t.call(this,u),n=null},s-h)):(i.push(u),h>=s?(o=d,c.call(this)):a||(a=!0,n=setTimeout(()=>{o=Date.now(),c.call(this),n=null,a=!1},s-h)))}}function Vp(t,e){const s=[];let r=null;const o=e.maxSize||1e3,n=i=>{s.length>0&&(t.call(i,[...s]),s.length=0)};return function(i){if(s.push(i),s.length>=o){r&&(clearTimeout(r),r=null),n(this);return}r||(r=setTimeout(()=>{n(this),r=null},e.time))}}function Gp(t){let e=!1;return function(s){e||(e=!0,t.call(this,s))}}function Yp(t,e){(Array.isArray(t)?t:[t]).forEach(r=>{un(r,e)})}const To=new Map,Gc={addToDeletionQueue:(t,e)=>{const s=To.get(t)||[];s.push(e),To.set(t,s)},cancelDeletion:t=>{const e=To.get(t);e&&e.forEach(s=>{clearTimeout(s)})}},Wp=m.createLogger({name:"kos-dependency-manager"});class Qp{constructor(){l(this,"_usedByCache",new Map);l(this,"_usesCache",new Map)}add(e,s){Gc.cancelDeletion(s);const r=this._usedByCache.get(s)||[];r.includes(e)||r.push(e),this._usedByCache.set(s,r);const o=this._usesCache.get(e)||[];o.includes(s)||o.push(s),this._usesCache.set(e,o)}remove(e,s){const r=this._usedByCache.get(s)||[];this._usedByCache.set(s,r.filter(n=>n!==e));const o=this._usesCache.get(e)||[];this._usesCache.set(e,o.filter(n=>n!==s))}canDestroy(e){const s=this._usedByCache.get(e);return s!=null&&s.length?(Wp.info(`Model ${e} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}const Li=m.createLogger({name:"kos-model-cache"});class Zp{constructor(e=[]){l(this,"_modelsById",M.observable.map(new Map));l(this,"_toDelete",new Map);l(this,"_preloaded",[]);l(this,"_isPreloaded",!1);this.preloadKeys=e}get models(){return Array.from(this._modelsById.values()).map(e=>e).filter(e=>!this._toDelete.has(e.modelId))}getModelById(e){if(e&&!this._toDelete.has(e))return this._modelsById.get(e)}addModel(e){const s=this.getModelById(e.modelId)||e;return this._modelsById.set(s.modelId,s),s}removeModel(e){this._modelsById.delete(e),this._toDelete.delete(e)}hasModel(e){return!!e&&this._modelsById.has(e)&&!this._toDelete.has(e)}restoreFromDeleteCache(e){if(e&&this._toDelete.has(e)){const s=this._toDelete.get(e);this._toDelete.delete(e),this._modelsById.set(e,s)}}markForDeletion(e){this._modelsById.delete(e.modelId),this._toDelete.set(e.modelId,e)}preload(e){return this._isPreloaded?(Li.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(Li.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),e(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}class lr extends Error{constructor(s,r,o){super(s,{cause:o});l(this,"context");l(this,"originalCause");this.name="KosModelError",this.context=r,this.originalCause=o,o!=null&&o.stack&&(this.stack=`${this.stack}
2
2
  Caused by: ${o.stack}`)}toDetailedString(){const s=[`KosModelError: ${this.message}`,"","Context:",` Model Type: ${this.context.modelType}`,` Model ID: ${this.context.modelId}`];return this.context.parentModel&&s.push(` Parent Model: ${this.context.parentModel.type} [${this.context.parentModel.id}]`),this.context.lifecycle&&s.push(` Lifecycle: ${this.context.lifecycle}`),this.context.operation&&s.push(` Operation: ${this.context.operation}`),this.context.options&&Object.keys(this.context.options).length>0&&s.push(` Options: ${JSON.stringify(this.context.options,null,2)}`),this.originalCause&&s.push("",`Original Error: ${this.originalCause.message}`),s.join(`
3
3
  `)}}function Ot(t,e){const s=t instanceof Error?t:new Error(String(t));return t instanceof lr?new lr(`${t.message} (enriched with additional context)`,{...t.context,...e},t.originalCause||s):new lr(`Error in ${e.operation||"model operation"}: ${s.message}`,e,s)}function Xp(t,e){t.length!==0&&(m.error(`${e} - ${t.length} error(s) occurred:`),t.forEach(({error:s,context:r},o)=>{const n=s instanceof lr?s:Ot(s,r);m.error(` [${o+1}/${t.length}] ${n.toDetailedString()}`)}))}function Fi(t,e){console.error("Model instantiation failed",{modelType:e.modelType,options:e.options,registryId:e.registryId,error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,timestamp:new Date().toISOString()})}const Yc=t=>typeof t=="function",Xs=m.createLogger({name:"kos-companion-instantiator"});class Jp{constructor(e,s,r){this.registry=e,this.cache=s,this.createModel=r}createCompanionModels(e,s,r){const o=this.getCompanionDefinitions(e.modelTypeName);r!==void 0&&Xs.debug(`Creating ${r} lifecycle companions for ${e.modelTypeName} [${e.modelId}]`);for(const n of o){const i=this.resolveCompanionType(n,e,s,r);i&&this.shouldCreateCompanion(i.lifecycle,r)&&this.instantiateCompanion(i.type,e,s,r)}}getCompanionDefinitions(e){var s;return((s=this.registry.companionModels)==null?void 0:s[e])||[]}resolveCompanionType(e,s,r,o){return Yc(e.type)?this.resolveFactoryCompanion(e,s,r,o):this.resolveStringCompanion(e)}resolveFactoryCompanion(e,s,r,o){const n=e.type(s.modelData,r);if(!n)return Xs.debug(`Companion factory returned undefined for ${s.modelTypeName} at ${o||"INIT"} phase`),null;const i=this.extractLifecycleFromType(n);return{type:n,lifecycle:i}}resolveStringCompanion(e){return{type:e.type,lifecycle:e.lifecycle}}extractLifecycleFromType(e){const s=this.registry.models[e];if(!(s!=null&&s.class))return;const r=s.class.prototype[Ve];return r==null?void 0:r.lifecycle}shouldCreateCompanion(e,s){return s!==void 0?e===s:e===void 0}instantiateCompanion(e,s,r,o){const n=this.generateCompanionId(e,s.modelId);if(this.companionAlreadyExists(n,e,s.modelTypeName))return;const i=this.createCompanionInstance(e,n,s,r);i&&(this.attachCompanionToParent(i,s),Xs.debug(`Created ${o||"INIT"} companion ${e} for ${s.modelTypeName} [${s.modelId}]`))}generateCompanionId(e,s){return`${e}-${s}`}companionAlreadyExists(e,s,r){return this.cache.hasModel(e)?(Xs.debug(`Companion ${s} already exists for ${r}`),!0):!1}createCompanionInstance(e,s,r,o){const n=this.createModel(e,s,{data:o,companionParent:r.modelData,kosParentId:r.modelId});return(n==null?void 0:n.model)||null}attachCompanionToParent(e,s){e[Ve]=s,s.addCompanionModel(e)}}function Wc(t,e){return`${an}${t}${e?`/${e}`:`/${t}`}`}function Qc(t){return`${an}${t}`}function _o(t){const e=[];return new Promise((s,r)=>{for(const{condition:o,onMatch:n}of t){const i=M.when(o,()=>{e.forEach(a=>a());try{n==null||n(),s()}catch(a){r(a)}});e.push(i)}})}const Zc=5e3,eg=t=>t.fsm.transitionTo(k.GO_ACTIVE,v.ACTIVE),tg=t=>t.whenReady(),sg=t=>t.fsm.transitionTo(k.LOAD,v.LOADED),rg=t=>t.fsm.transitionTo(k.UNLOAD,v.UNLOADED),og=t=>t.fsm.transitionTo(k.INITIALIZE,v.INITIALIZED);var In=(t=>(t.ACTIVE="active",t.READY="ready",t.LOAD="load",t.UNLOAD="unload",t.INIT="init",t))(In||{});const ur={active:eg,ready:tg,load:sg,unload:rg,init:og};class Xc extends Error{constructor(s,r){super(s);l(this,"model");this.model=r}}const Jc=(t,e,s)=>{let r;return{promise:new Promise((i,a)=>{r=setTimeout(()=>{m.error(`Model ${e.modelId} - ${e.modelTypeName} - ${s} timed out after ${t}ms`),a(new Xc(`${e.modelId} - ${e.modelTypeName} - ${s}`,e))},t)}),cancel:()=>{r&&clearTimeout(r)}}},ng=t=>typeof t.toJSON=="function",Es=t=>t[F]!==void 0,$n=t=>t.revision!==void 0&&t.index!==void 0,el=t=>{if(t){if(Es(t))return t;if($n(t))return t.data;if(t instanceof Map||t instanceof M.ObservableMap||t instanceof Set)return Array.from(t.values()).filter(Es);if(Array.isArray(t))return t.filter(Es)}},tl=(t,e)=>{var f;const s=e.id||e.modelType,r=he({value:s,modelData:t.modelData,modelId:t.modelId}),o=e.resolutionPolicy||qe.CREATE;m.debug(`Resolving dependent model ${e.modelType} with id ${r} (policy: ${o})`);const n=Object.keys((e==null?void 0:e.options)||{}).reduce((p,y)=>{const w=e.options[y];return p[y]=he({value:w,modelData:t.modelData,modelId:t.modelId}),p},{}),i=O.getInstance().modelManager,a=i.registry.models[e.modelType];if(!a){const p=`No model registered for type ${e.modelType}`;if(m.error(`Failed to resolve dependency for model ${t.modelId}:
4
4
  - Dependency Type: ${e.modelType}
@@ -28,7 +28,7 @@ Caused by: ${o.stack}`)}toDetailedString(){const s=[`KosModelError: ${this.messa
28
28
  - Parent Model: ${t.modelTypeName}
29
29
  - Parent Model ID: ${t.modelId}
30
30
  - Provided Options: ${JSON.stringify(n,null,2)}
31
- - Error: ${y}`),o===qe.FAIL?new Error(`Dependency resolution failed (policy: FAIL) - Model ${t.modelId} cannot resolve dependency ${e.modelType} [${r}]: ${y}`):p}},sl=(t,e=x.READY)=>{var o;const s=((o=t.modelData)==null?void 0:o[F])||{};return Object.keys(s).length===0?(m.debug(`${t.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===e).map(n=>{const i=s[n],a=tl(t,i);if(!a.success||!a.dependentModel)return m.debug(`Skipping dependency ${i.modelType} with id ${a.dataModelId} - resolution failed with CONTINUE policy`),t.modelData[n]=void 0,null;const{dependentModel:c,dataModelId:u}=a;t.modelData[n]=c.data,m.debug(`waiting for dependent model ${i.modelType} with id ${u} - waiting for WHENREADY`);const d=async(p,y,w)=>{var E;await((E=p.whenReady)==null?void 0:E.call(p)),m.debug(`dependent model ${y} with id ${w} - READY`)},{promise:h,cancel:f}=Jc(Zc,t,t.status);return Promise.race([d(c.model,i.modelType,u).then(()=>{f()}).catch(p=>{const y=Ot(p,{modelType:i.modelType,modelId:u,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:e,operation:"dependency whenReady()"});throw m.error(y.toDetailedString()),f(),y}),h])}).filter(n=>!!n)},rl=async(t,e,s,r)=>{if(m.debug(`Execute lifecycle with ${e.length} models`),e.length===0){m.debug(`${t.modelId} has no children. Returning`);return}if(!s){m.error(`${t.modelId} is not transitioning with a valid target ${s}`);return}const o=e.map(a=>{let c;return ur[s]&&a?c=ur[s](a):(a||m.error("model is undefined. This shouldn't happen"),ur[s]||m.error(`There is no promise in the Transition Map for ${s}`)),{promise:c,modelId:a==null?void 0:a.modelId,model:a,type:a==null?void 0:a.modelTypeName,status:a==null?void 0:a.status}}).filter(a=>a.promise?a.model?!0:(m.error(`No model found ${a.modelId}`),!1):(m.error(`No promise found ${a.modelId}`),!1)),n=await Promise.allSettled(o.map(a=>{var d;if(!a.model||!a.status)return Promise.resolve();const{promise:c,cancel:u}=Jc(Zc,a.model,a.status);return Promise.race([(d=a.promise)==null?void 0:d.then(()=>{u()}).catch(h=>{const f=Ot(h,{modelType:a.type||"unknown",modelId:a.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`});throw m.error(f.toDetailedString()),u(),f}),c])})),i=n.filter(a=>a.status==="rejected");if(i.length>0){const a=i.map(c=>{const u=o[n.indexOf(c)];return{error:c.status==="rejected"?c.reason:new Error("Unknown error"),context:{modelType:u.type||"unknown",modelId:u.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`}}});Xp(a,`Model ${t.modelId} had ${i.length} failed child model(s) on ${r}`)}},ol=async(t,e,s)=>{await rl(t,t.getChildren().filter(r=>!!r),e,s)},ts=async(t,e)=>{const r=(await Promise.allSettled(sl(t,e))).filter(o=>o.status==="rejected");r.length&&(m.error(`There were ${r.length} failed dependent models on ${e}`),m.error(r))};function ig(t){const e=`KosModel(${t.modelTypeName}:${t.modelId})`;try{Object.defineProperty(t,Symbol.toStringTag,{value:e,configurable:!0})}catch{t.toString=()=>e}try{Object.defineProperty(t.constructor,"name",{value:`KosModel_${t.modelTypeName}`,configurable:!0})}catch{t.constructor.name=`KosModel_${t.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in t&&Object.defineProperty(t,r,{enumerable:!1});Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var r,o,n;return{id:t.modelId,type:t.modelTypeName,initialized:t.initialized,loaded:t.loaded,status:t.status,onlineStatus:t.onlineStatus,activeStatus:t.activeStatus,companions:(o=(r=t.companionManager)==null?void 0:r.all())==null?void 0:o.map(i=>i.modelTypeName),children:(n=t.getChildren)==null?void 0:n.call(t).map(i=>i.modelId),effects:!!t.effectManager,subs:!!t.subscriptionManager}}}),ag(t.modelData,t.modelTypeName,t.modelId,t)}function ag(t,e,s,r){Object.defineProperty(t,Symbol.toStringTag,{value:`KosModelData(${e}:${s})`,configurable:!0});try{Object.defineProperty(t.constructor,"name",{value:`${e}ModelData`,configurable:!0})}catch{t.constructor.name=`${e}ModelData`}Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,u;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[F]||{};return{id:s,type:e,companions:{count:n.length,data:n.map(d=>({type:d.modelTypeName,id:d.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(d=>({id:d.id||d.modelType,type:d.modelType,options:d.options,lifecycle:d.lifecycle}))},children:{count:o.length,data:o.map(d=>({id:d.modelId,type:d.modelTypeName}))},data:((u=t.toJSON)==null?void 0:u.call(t))||{},subs:!!r.subscriptionManager}}}),Object.defineProperty(t,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const o={};for(const n of Object.keys(t))if(!(n.startsWith("_")||typeof t[n]=="function"))try{const i=t[n];Es(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:$n(i)?o[`[KOS Container] ${n}`]=typeof i.toJSON=="function"?i.toJSON():["Container"]:Array.isArray(i)?o[n]=`[Array(${i.length})]`:typeof i=="object"&&i!==null?o[n]=JSON.parse(JSON.stringify(i)):o[n]=i}catch{o[n]="[unreadable]"}return o}})}class cg{constructor(e){this.model=e}resolve(){const e=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(e).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==v.FAILED).filter(r=>!!r);return s.forEach(r=>{try{V.setParentContext(r.modelId,this.model.modelId)}catch(o){console.error(`Failed to set parent context for ${r.modelId} under ${this.model.modelId}`,o)}}),s}getResolvedDecoratedChildren(){var s;const e=((s=this.model.modelData)==null?void 0:s[ze])||{};return Object.keys(e).map(r=>el(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var e,s;return((s=(e=this.model.modelData)==null?void 0:e.getChildren)==null?void 0:s.call(e))||[]}}class lg{constructor(e){l(this,"companions",new M.ObservableMap);this.hostModel=e}add(e){this.companions.set(e.modelTypeName,e)}clear(){this.companions.clear()}get(e){return this.companions.get(e)}all(){return[...this.companions.values()]}get data(){return this.companions}}class ug{constructor(e,s,r,o){l(this,"disposers",[]);this.modelTypeName=e,this.modelId=s,this.modelData=r,this.log=o}setup(){var s;const e=((s=this.modelData)==null?void 0:s[nt])||{};for(const r of Object.keys(e)){const{value:o,dependencies:n,options:i}=e[r],a=o.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),M.runInAction(()=>a())},u=n?M.reaction(()=>n(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):M.autorun(c);this.disposers.push(u)}}disposeAll(){for(const e of this.disposers)try{e()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const dg=m.createLogger({name:"model-active-machine"}),hg=t=>{const e=b.createMachine(v.INACTIVE,{[v.FAILED]:b.state(b.transition(k.GO_ACTIVE,v.ACTIVATING)),[v.INACTIVE]:b.state(b.transition(k.GO_ACTIVE,v.ACTIVATING)),[v.ACTIVATING]:b.invoke(()=>(t.activeStatus=v.ACTIVATING,t.activate()),b.transition("done",v.ACTIVE,b.action(()=>{t.activeStatus=v.ACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED}))),[v.ACTIVE]:b.state(b.transition(k.GO_INACTIVE,v.DEACTIVATING)),[v.DEACTIVATING]:b.invoke(()=>(t.activeStatus=v.DEACTIVATING,t.deactivate()),b.transition("done",v.INACTIVE,b.action(()=>{t.activeStatus=v.INACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED})))});return{service:b.interpret(e,r=>dg.debug(r.machine.current)),machine:e}},Ni=m.createLogger({name:"model-online-machine"}),fg=t=>{const e=b.createMachine(v.OFFLINE,{[v.ONLINE]:b.state(b.transition(k.GO_OFFLINE,v.OFFLINE,b.action(async()=>{await t.offline(),t.onlineStatus=v.OFFLINE}))),[v.OFFLINE]:b.state(b.transition(k.GO_ONLINE,v.ONLINE,b.action(async()=>{Ni.debug(`Going online with model ${t.modelId}`),await t.online(),t.onlineStatus=v.ONLINE,await t.fsm.transitionTo(k.INITIALIZE,v.INITIALIZED)})))}),s=b.interpret(e,r=>Ni.debug(r.machine.current));return{machine:e,service:s}},pg=t=>{var r;const e=hg(t).service,s=fg(t).service;return b.createMachine(v.CREATING,{[v.CREATING]:b.state(b.transition(k.CREATE,v.CREATED)),[v.CREATED]:b.state(b.immediate(v.INITIALIZING)),[v.INITIALIZING]:b.invoke(()=>(X(()=>{t.status=v.INITIALIZING}),t.init()),b.transition("done",v.INITIALIZED,b.action(()=>{t.status=v.INITIALIZED})),b.transition("error",v.FAILED,b.action(()=>{m.error(`Model ${t.modelId} - ${t.modelTypeName} failed to initialize. Transitioning to FAILED state.`),t.status=v.FAILED}))),[v.INITIALIZED]:b.state(b.immediate(v.LOADING)),[v.LOADING]:b.invoke(()=>(X(()=>{t.status=v.LOADING}),t.load()),b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.LOADED]:b.state(b.immediate(v.READYING),b.transition(k.UNLOAD,v.UNLOADING)),[v.RESETTING]:b.invoke(()=>{var o;return X(()=>{t.status=v.RESETTING}),(o=t.unload)==null||o.call(t),t.load()},b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED}))),[v.READYING]:b.invoke(()=>(X(()=>{t.status=v.READYING}),t.ready()),b.transition("done",v.READY,b.action(()=>{X(()=>{t.status=v.READY}),s.send(k.GO_ONLINE)})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.READY]:b.state(b.transition(k.UNLOAD,v.UNLOADED,b.action((r=t.unload)==null?void 0:r.bind(t))),b.transition(k.RESET,v.RESETTING),b.transition(k.GO_ONLINE,v.READY,b.action(()=>{s.send(k.GO_ONLINE)})),b.transition(k.GO_OFFLINE,v.READY,b.action(()=>{s.send(k.GO_OFFLINE)})),b.transition(k.GO_ACTIVE,v.READY,b.action(()=>{e.send(k.GO_ACTIVE)})),b.transition(k.GO_INACTIVE,v.READY,b.action(()=>{e.send(k.GO_INACTIVE)}))),[v.UNLOADED]:b.state(),[v.FAILED]:b.state()})},gg=m.createLogger({name:"kos-model-lifecycle"}),mg=t=>({service:b.interpret(pg(t),s=>gg.debug(`state machine for model ${t.modelId}: ${s.machine.current});`))});class yg{constructor(e,s){l(this,"disposer");l(this,"service");this.model=e,this.log=s;const r=mg(e);this.service=r.service,this.service.send(k.CREATE)}get current(){return this.service.machine.current}async transitionTo(e,s,r=v.FAILED){return this.getTransitionStatusFor(s)===s?(this.log.debug(`Model ${this.model.modelId} already in state ${s}, skipping transition`),Promise.resolve()):(this.log.debug(`Transitioning model ${this.model.modelId} with event ${e} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=M.when(()=>{const c=this.getTransitionStatusFor(s);return c===s||c===r},()=>{this.getTransitionStatusFor(s)===r?(this.log.error(`Model ${this.model.modelId} entered error state ${r} during transition`),i(new Error(`FSM transition failed for model ${this.model.modelId} with event ${e}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(e)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(e){return[v.ACTIVE,v.INACTIVE].includes(e)?this.model.activeStatus:this.model.status}}const nl="browser-router-model";class Cn{constructor(e,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=e,this.logger=s}registerAll(){var s;if(!yr(this.model))return;let e=this.model.__httpBrowserRouter;if(!e)for(const r of Object.keys(this.model)){const o=this.model[r];if(o&&typeof o=="object"&&"use"in o&&typeof o.use=="function"){e=o;break}}if(e||(e=(s=$e(nl))==null?void 0:s.model),!e)throw this.logger.error("Cannot register HTTP routes: BrowserRouter not found. The HTTP decorators should have auto-injected it, but something went wrong."),new Error("BrowserRouter is required for HTTP route decorators but was not found. This should not happen as HTTP decorators auto-inject the dependency.");this.setRouter(e)}setRouter(e){this.router=e,this.registered||this.registerRoutes()}hasRoutes(){return yr(this.model)}registerRoutes(){if(!this.router){this.logger.warn("Cannot register routes: router not set");return}if(this.registered){this.logger.debug("Routes already registered");return}const e=Dc(this.model);e.length!==0&&(this.logger.debug(`Registering ${e.length} HTTP routes`),e.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(e){const s=/\{PROP_([^}]+)\}/g;let r=e;if(r.includes("{MODEL_ID}")){const n=this.model.id||this.model._id||"unknown";r=r.replace(/\{MODEL_ID\}/g,n)}let o;for(;(o=s.exec(e))!==null;){const n=o[1];if(n in this.model){const i=this.model[n];r=r.replace(o[0],String(i))}else this.logger.warn(`Property '${n}' not found on model for PropKey resolution in path: ${e}`)}return r}registerRoute(e){if(!this.router)return;const s=this.model[e.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${e.handler}' not found on model`);return}const r=this.resolvePropKey(e.path);this.logger.debug(`Registering ${e.method} ${r} -> ${e.handler}`+(r!==e.path?` (resolved from ${e.path})`:""));const o=async(n,i)=>{var a;try{await s.call(this.model,n,i)}catch(c){this.logger.error(`Error in route handler ${e.method} ${r}:`,c),(a=i.status)==null||a.call(i,500).send({error:"Internal server error",message:c instanceof Error?c.message:String(c)})}};this.checkForDuplicateRoute(e.method,r),this.router.use(e.method,r,o),this.registeredRoutes.push({method:e.method,path:r})}checkForDuplicateRoute(e,s){if(!this.router)return;this.router.getRoutes().find(n=>n.method===e&&n.path===s)&&this.logger.warn(`Duplicate route detected: ${e} ${s}. This route is already registered by another model. The new handler from model '${this.model.id||"unknown"}' will override the existing one. Only the last registered handler will receive requests. Consider using different paths or namespacing to avoid conflicts.`)}dispose(){if(this.router&&this.registeredRoutes.length>0){this.logger.debug(`Removing ${this.registeredRoutes.length} HTTP routes for model ${this.model.id||"unknown"}`);let e=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);e+=r,r>0?this.logger.debug(`Removed route: ${s.method} ${s.path}`):this.logger.warn(`Failed to remove route: ${s.method} ${s.path} (not found)`)}this.logger.debug(`Successfully removed ${e} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function bg(t,e){if(!yr(t))return;const s=$e(nl);if(!(s!=null&&s.model))throw e.error("Cannot register HTTP routes: BrowserRouter not found. Make sure to include BrowserRouter in your model dependencies or create an instance."),new Error("BrowserRouter is required for HTTP route decorators but was not found. Add it as a dependency using @kosDependency or ensure an instance exists.");new Cn(t,e).setRouter(s.model)}class vg{constructor(e){l(this,"queue",[]);this.log=e}enqueue(e,s,r){this.queue.push({handler:e,receivedAt:Date.now(),topic:s,payload:r})}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const e of this.queue)try{e.handler()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}flushWithStrategy(e,s,r){if(this.queue.length===0)return;const o=this.queue.length,n=this.filterEventsByStrategy(e,s,r),i=o-n.length;this.log.warn(`Processing ${n.length}/${o} offline message(s) with strategy: ${e}`);for(const a of n)try{a.handler()}catch(c){this.log.error(`Error while processing offline message for topic ${a.topic}:`,c)}this.queue=[],this.log.info(`Offline queue flushed with strategy ${e}. Replayed: ${n.length}, Discarded: ${i}`)}filterEventsByStrategy(e,s,r){switch(e){case ot.ALL:return[...this.queue];case ot.AFTER_REQUEST:return s===void 0?(this.log.warn("AFTER_REQUEST strategy requires baselineRequestedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=s);case ot.AFTER_RESPONSE:return r===void 0?(this.log.warn("AFTER_RESPONSE strategy requires baselineReceivedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=r);case ot.NONE:return[];default:return this.log.warn(`Unknown replay strategy: ${e}, replaying all`),[...this.queue]}}getStatistics(e,s){if(this.queue.length===0)return{total:0};const r=this.queue.map(n=>n.receivedAt),o={total:this.queue.length,oldestEventAt:Math.min(...r),newestEventAt:Math.max(...r)};return e!==void 0&&(o.afterRequest=this.queue.filter(n=>n.receivedAt>=e).length),s!==void 0&&(o.afterResponse=this.queue.filter(n=>n.receivedAt>=s).length),o}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class wg{constructor(e,s){l(this,"unsubscribers",[]);this.model=e,this.log=s}register(){const e=this.model.modelId,s=C("/kosCore/online",async()=>{this.log.debug(`Online event received for ${e}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${e} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(k.GO_ONLINE,v.ONLINE)}),r=C("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${e} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(k.GO_OFFLINE,v.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}}const il=()=>({isMock:!1,URL:exports.BASE_URL}),Eg=m.createLogger({name:"kos-service-request"}),Mg="errUnknown";async function Js(t,e,s,r,o){const n=r!=null&&r.path?Object.keys(r.path).reduce((h,f)=>String(h).replace(`{${f}}`,r==null?void 0:r.path[f]),String(t)):String(t),i=r!=null&&r.query?Object.keys(r.query).map(h=>`${encodeURIComponent(h)}=${encodeURIComponent(r.query[h])}`).join("&"):"",a=`${il().URL}${n}${i?`?${i}`:""}`;Eg.debug(`fullUrl: ${a}`);const c={method:String(e).toUpperCase(),body:null,...s};o&&(c.body=JSON.stringify(o));const u=await exports.kosFetch(a,c);return u.status<200||u.status>=400?[`${u.statusText||Mg}`,null]:[null,(await u.json()).data]}function Be(){return{get:(t,e,s)=>Js(t,"get",s,e),post:(t,e,s,r)=>Js(t,"post",r,e,s),put:(t,e,s,r)=>Js(t,"put",r,e,s),delete:(t,e,s,r)=>Js(t,"delete",r,e,s)}}const Ae=Be(),al=Object.freeze(Object.defineProperty({__proto__:null,default:Ae},Symbol.toStringTag,{value:"Module"})),et=m.createLogger({name:"kos-service-request-manager",group:"Model"});function Tg(t,e){return!t.condition||t.condition(e)}function _g(t,e){return he({value:t.path,modelId:e.id,modelData:e})}function Sg(t,e){if(t.pathParams)return he({value:typeof t.pathParams=="function"?t.pathParams(e):t.pathParams,modelId:e.id,modelData:e})}function Og(t,e){if(t.queryParams)return he({value:typeof t.queryParams=="function"?t.queryParams(e):t.queryParams,modelId:e.id,modelData:e})}function Ig(t,e){if(t.body)return he({value:typeof t.body=="function"?t.body(e):t.body,modelId:e.id,modelData:e})}function $g(t,e){if(t.requestOptions)return typeof t.requestOptions=="function"?t.requestOptions(e):t.requestOptions}function Cg(t){return(t||"get").toLowerCase()}function er(t,e){return`${e.toUpperCase()}:${t}`}function cl(t){return t==null}function Dg(t,e,s,r){r&&cl(t)&&et.warn(`Required field '${e}' is missing in response for ${s}`)}function xg(t,e){return cl(t)&&e!==void 0?e:t}class Ag{constructor(e,s){l(this,"model");l(this,"responseStore");l(this,"handlers");this.model=e,this.responseStore=s,this.handlers=new Map,this.discoverHandlers()}discoverHandlers(){const s=Object.getPrototypeOf(this.model)[it]||{};Object.values(s).forEach(r=>{const o=r.lifecycle;this.handlers.has(o)||this.handlers.set(o,[]),this.handlers.get(o).push(r)}),Object.keys(s).length>0&&et.debug(`Discovered ${Object.keys(s).length} service request handlers for model ${this.model.id}`)}async executeForLifecycle(e){const s=this.handlers.get(e);!s||s.length===0||(et.debug(`Executing ${s.length} service requests for lifecycle ${e}`),await Promise.all(s.map(r=>this.executeHandler(r))))}async executeHandler(e){try{if(!this.shouldProcessRequest(e))return;const s=await this.prepareAndExecuteRequest(e);await this.processAndStoreResponse(s,e)}catch(s){const r=s instanceof Error?s:new Error(String(s));await this.handleError(r,e)}}shouldProcessRequest(e){return Tg(e,this.model)?!0:(et.debug(`Skipping request ${e.path} - condition returned false`),!1)}async prepareAndExecuteRequest(e){const s=this.prepareRequest(e),r=this.captureRequestTiming(),[o,n]=await this.performRequest(s),i=this.captureResponseTiming();return{requestContext:s,error:o,response:n,requestedAt:r.requestedAt,receivedAt:i.receivedAt}}captureRequestTiming(){return{requestedAt:Date.now()}}captureResponseTiming(){return{receivedAt:Date.now()}}async processAndStoreResponse(e,s){if(e.error){await this.handleError(new Error(e.error),s);return}const r=await this.processResponse(e.response,s);await this.storeAndInvokeHandler(r,s,e.requestContext.resolvedPath,e.requestedAt,e.receivedAt)}prepareRequest(e){const s=_g(e,this.model),r=Sg(e,this.model),o=Og(e,this.model),n=Ig(e,this.model),i=$g(e,this.model),a=Cg(e.method);return{resolvedPath:s,method:a,pathParams:r,queryParams:o,body:n,requestOptions:i}}async performRequest(e){return await this.makeRequest(e.resolvedPath,e.method,{path:e.pathParams,query:e.queryParams},e.body,e.requestOptions)}async processResponse(e,s){let r=e;return s.transform&&(r=s.transform(e)),s.mappings&&s.mappings.length>0&&(r=this.applyMappings(r,s)),s.iterateOver&&(r=await this.handleIteration(r,s)),r}async storeAndInvokeHandler(e,s,r,o,n){const i=s.cache||{retention:se.SINGLE},a=er(r,s.method||"get");this.responseStore.set(a,e,i,o,n),await s.originalHandler.call(this.model,null,e),this.triggerBaselineQueueFlush(r),this.responseStore.shouldCleanupAfterHandler(a)&&this.responseStore.delete(a)}triggerBaselineQueueFlush(e){const s=this.model.subscriptionManager;!s||!s.flushQueueForBaseline||s.flushQueueForBaseline(e)}async makeRequest(e,s,r,o,n){const i=Ae;switch(s){case"get":return await i.get(e,r,n);case"post":return await i.post(e,r,o,n);case"put":return await i.put(e,r,o,n);case"delete":return await i.delete(e,r,o,n);default:return[`Unsupported HTTP method: ${s}`,null]}}applyMappings(e,s){if(!s.mappings||s.mappings.length===0)return e;const r={};return s.mappings.forEach(o=>{const n=this.getNestedValue(e,o.from),i=o.transform?this.applyTransform(n,o.transform):n;Dg(i,o.from,s.path,o.required||!1);const a=xg(i,o.default);r[o.to]=a}),r}getNestedValue(e,s){return s.split(".").reduce((r,o)=>r==null?void 0:r[o],e)}applyTransform(e,s){if(typeof s=="function")return s(e);switch(s){case"string":return String(e);case"number":return Number(e);case"boolean":return!!e;case"date":return e?new Date(e):void 0;case"json":return typeof e=="string"?JSON.parse(e):e;default:return et.warn(`Unknown transformer: ${s}`),e}}async handleIteration(e,s){if(!s.iterateOver)return e;const r=this.getNestedValue(e,s.iterateOver);return Array.isArray(r)?s.modelFactory?r.map(o=>{const n=s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o,i=s.idExtractor?s.idExtractor(n):n.id;if(!i)throw new Error("Cannot create model instance: no ID found in response data. Provide an 'idExtractor' function or ensure response items have an 'id' field.");const a=s.modelFactory;return typeof a=="function"?a(i)(n):a.instance(i).options(n).build()}):r.map(o=>s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o):(et.warn(`iterateOver path '${s.iterateOver}' did not resolve to an array`),[])}async handleError(e,s){const r=s.errorHandler||{strategy:"throw"};switch(r.onError&&r.onError(e,this.model),r.strategy){case"throw":throw e;case"log":if(et.error(`Service request failed for ${s.path}:`,e.message),r.defaultValue!==void 0){const o=er(s.path,s.method||"get");this.responseStore.set(o,r.defaultValue,s.cache||{retention:se.SINGLE}),await s.originalHandler.call(this.model,e.message,r.defaultValue)}break;case"ignore":if(r.defaultValue!==void 0){const o=er(s.path,s.method||"get");this.responseStore.set(o,r.defaultValue,s.cache||{retention:se.SINGLE}),await s.originalHandler.call(this.model,e.message,r.defaultValue)}break;case"default":if(r.defaultValue!==void 0){const o=er(s.path,s.method||"get");this.responseStore.set(o,r.defaultValue,s.cache||{retention:se.SINGLE}),await s.originalHandler.call(this.model,e.message,r.defaultValue)}break}}}class Rg{constructor(e){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=e,this.subscription={queue:[],resolvers:[],closed:!1};const s=C(e,r=>{if(!this.subscription.closed&&r!==void 0){const o=this.subscription.resolvers.shift();o?o(r):this.subscription.queue.push(r)}});this.unsubscribe=s.unsubscribe}async next(){return this.subscription.closed&&this.subscription.queue.length===0?{done:!0,value:void 0}:this.subscription.queue.length>0?{done:!1,value:this.subscription.queue.shift()}:new Promise(e=>{this.subscription.closed?e({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{e({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(e=>{e(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(e){throw this.subscription.closed=!0,this.unsubscribe(),e}[Symbol.asyncIterator](){return this}}function Ui(t){return new Rg(t)}const ll=({path:t,requestId:e,method:s,destinationAddress:r})=>{let o=`${qr}:${s}
31
+ - Error: ${y}`),o===qe.FAIL?new Error(`Dependency resolution failed (policy: FAIL) - Model ${t.modelId} cannot resolve dependency ${e.modelType} [${r}]: ${y}`):p}},sl=(t,e=x.READY)=>{var o;const s=((o=t.modelData)==null?void 0:o[F])||{};return Object.keys(s).length===0?(m.debug(`${t.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===e).map(n=>{const i=s[n],a=tl(t,i);if(!a.success||!a.dependentModel)return m.debug(`Skipping dependency ${i.modelType} with id ${a.dataModelId} - resolution failed with CONTINUE policy`),t.modelData[n]=void 0,null;const{dependentModel:c,dataModelId:u}=a;t.modelData[n]=c.data,m.debug(`waiting for dependent model ${i.modelType} with id ${u} - waiting for WHENREADY`);const d=async(p,y,w)=>{var E;await((E=p.whenReady)==null?void 0:E.call(p)),m.debug(`dependent model ${y} with id ${w} - READY`)},{promise:h,cancel:f}=Jc(Zc,t,t.status);return Promise.race([d(c.model,i.modelType,u).then(()=>{f()}).catch(p=>{const y=Ot(p,{modelType:i.modelType,modelId:u,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:e,operation:"dependency whenReady()"});throw m.error(y.toDetailedString()),f(),y}),h])}).filter(n=>!!n)},rl=async(t,e,s,r)=>{if(m.debug(`Execute lifecycle with ${e.length} models`),e.length===0){m.debug(`${t.modelId} has no children. Returning`);return}if(!s){m.error(`${t.modelId} is not transitioning with a valid target ${s}`);return}const o=e.map(a=>{let c;return ur[s]&&a?c=ur[s](a):(a||m.error("model is undefined. This shouldn't happen"),ur[s]||m.error(`There is no promise in the Transition Map for ${s}`)),{promise:c,modelId:a==null?void 0:a.modelId,model:a,type:a==null?void 0:a.modelTypeName,status:a==null?void 0:a.status}}).filter(a=>a.promise?a.model?!0:(m.error(`No model found ${a.modelId}`),!1):(m.error(`No promise found ${a.modelId}`),!1)),n=await Promise.allSettled(o.map(a=>{var d;if(!a.model||!a.status)return Promise.resolve();const{promise:c,cancel:u}=Jc(Zc,a.model,a.status);return Promise.race([(d=a.promise)==null?void 0:d.then(()=>{u()}).catch(h=>{const f=Ot(h,{modelType:a.type||"unknown",modelId:a.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`});throw m.error(f.toDetailedString()),u(),f}),c])})),i=n.filter(a=>a.status==="rejected");if(i.length>0){const a=i.map(c=>{const u=o[n.indexOf(c)];return{error:c.status==="rejected"?c.reason:new Error("Unknown error"),context:{modelType:u.type||"unknown",modelId:u.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`}}});Xp(a,`Model ${t.modelId} had ${i.length} failed child model(s) on ${r}`)}},ol=async(t,e,s)=>{await rl(t,t.getChildren().filter(r=>!!r),e,s)},ts=async(t,e)=>{const r=(await Promise.allSettled(sl(t,e))).filter(o=>o.status==="rejected");r.length&&(m.error(`There were ${r.length} failed dependent models on ${e}`),m.error(r))};function ig(t){const e=`KosModel(${t.modelTypeName}:${t.modelId})`;try{Object.defineProperty(t,Symbol.toStringTag,{value:e,configurable:!0})}catch{t.toString=()=>e}try{Object.defineProperty(t.constructor,"name",{value:`KosModel_${t.modelTypeName}`,configurable:!0})}catch{t.constructor.name=`KosModel_${t.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in t&&Object.defineProperty(t,r,{enumerable:!1});Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var r,o,n;return{id:t.modelId,type:t.modelTypeName,initialized:t.initialized,loaded:t.loaded,status:t.status,onlineStatus:t.onlineStatus,activeStatus:t.activeStatus,companions:(o=(r=t.companionManager)==null?void 0:r.all())==null?void 0:o.map(i=>i.modelTypeName),children:(n=t.getChildren)==null?void 0:n.call(t).map(i=>i.modelId),effects:!!t.effectManager,subs:!!t.subscriptionManager}}}),ag(t.modelData,t.modelTypeName,t.modelId,t)}function ag(t,e,s,r){Object.defineProperty(t,Symbol.toStringTag,{value:`KosModelData(${e}:${s})`,configurable:!0});try{Object.defineProperty(t.constructor,"name",{value:`${e}ModelData`,configurable:!0})}catch{t.constructor.name=`${e}ModelData`}Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,u;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[F]||{};return{id:s,type:e,companions:{count:n.length,data:n.map(d=>({type:d.modelTypeName,id:d.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(d=>({id:d.id||d.modelType,type:d.modelType,options:d.options,lifecycle:d.lifecycle}))},children:{count:o.length,data:o.map(d=>({id:d.modelId,type:d.modelTypeName}))},data:((u=t.toJSON)==null?void 0:u.call(t))||{},subs:!!r.subscriptionManager}}}),Object.defineProperty(t,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const o={};for(const n of Object.keys(t))if(!(n.startsWith("_")||typeof t[n]=="function"))try{const i=t[n];Es(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:$n(i)?o[`[KOS Container] ${n}`]=typeof i.toJSON=="function"?i.toJSON():["Container"]:Array.isArray(i)?o[n]=`[Array(${i.length})]`:typeof i=="object"&&i!==null?o[n]=JSON.parse(JSON.stringify(i)):o[n]=i}catch{o[n]="[unreadable]"}return o}})}class cg{constructor(e){this.model=e}resolve(){const e=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(e).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==v.FAILED).filter(r=>!!r);return s.forEach(r=>{try{G.setParentContext(r.modelId,this.model.modelId)}catch(o){console.error(`Failed to set parent context for ${r.modelId} under ${this.model.modelId}`,o)}}),s}getResolvedDecoratedChildren(){var s;const e=((s=this.model.modelData)==null?void 0:s[ze])||{};return Object.keys(e).map(r=>el(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var e,s;return((s=(e=this.model.modelData)==null?void 0:e.getChildren)==null?void 0:s.call(e))||[]}}class lg{constructor(e){l(this,"companions",new M.ObservableMap);this.hostModel=e}add(e){this.companions.set(e.modelTypeName,e)}clear(){this.companions.clear()}get(e){return this.companions.get(e)}all(){return[...this.companions.values()]}get data(){return this.companions}}class ug{constructor(e,s,r,o){l(this,"disposers",[]);this.modelTypeName=e,this.modelId=s,this.modelData=r,this.log=o}setup(){var s;const e=((s=this.modelData)==null?void 0:s[it])||{};for(const r of Object.keys(e)){const{value:o,dependencies:n,options:i}=e[r],a=o.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),M.runInAction(()=>a())},u=n?M.reaction(()=>n(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):M.autorun(c);this.disposers.push(u)}}disposeAll(){for(const e of this.disposers)try{e()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const dg=m.createLogger({name:"model-active-machine"}),hg=t=>{const e=b.createMachine(v.INACTIVE,{[v.FAILED]:b.state(b.transition(k.GO_ACTIVE,v.ACTIVATING)),[v.INACTIVE]:b.state(b.transition(k.GO_ACTIVE,v.ACTIVATING)),[v.ACTIVATING]:b.invoke(()=>(t.activeStatus=v.ACTIVATING,t.activate()),b.transition("done",v.ACTIVE,b.action(()=>{t.activeStatus=v.ACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED}))),[v.ACTIVE]:b.state(b.transition(k.GO_INACTIVE,v.DEACTIVATING)),[v.DEACTIVATING]:b.invoke(()=>(t.activeStatus=v.DEACTIVATING,t.deactivate()),b.transition("done",v.INACTIVE,b.action(()=>{t.activeStatus=v.INACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED})))});return{service:b.interpret(e,r=>dg.debug(r.machine.current)),machine:e}},Ni=m.createLogger({name:"model-online-machine"}),fg=t=>{const e=b.createMachine(v.OFFLINE,{[v.ONLINE]:b.state(b.transition(k.GO_OFFLINE,v.OFFLINE,b.action(async()=>{await t.offline(),t.onlineStatus=v.OFFLINE}))),[v.OFFLINE]:b.state(b.transition(k.GO_ONLINE,v.ONLINE,b.action(async()=>{Ni.debug(`Going online with model ${t.modelId}`),await t.online(),t.onlineStatus=v.ONLINE,await t.fsm.transitionTo(k.INITIALIZE,v.INITIALIZED)})))}),s=b.interpret(e,r=>Ni.debug(r.machine.current));return{machine:e,service:s}},pg=t=>{var r;const e=hg(t).service,s=fg(t).service;return b.createMachine(v.CREATING,{[v.CREATING]:b.state(b.transition(k.CREATE,v.CREATED)),[v.CREATED]:b.state(b.immediate(v.INITIALIZING)),[v.INITIALIZING]:b.invoke(()=>(X(()=>{t.status=v.INITIALIZING}),t.init()),b.transition("done",v.INITIALIZED,b.action(()=>{t.status=v.INITIALIZED})),b.transition("error",v.FAILED,b.action(()=>{m.error(`Model ${t.modelId} - ${t.modelTypeName} failed to initialize. Transitioning to FAILED state.`),t.status=v.FAILED}))),[v.INITIALIZED]:b.state(b.immediate(v.LOADING)),[v.LOADING]:b.invoke(()=>(X(()=>{t.status=v.LOADING}),t.load()),b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.LOADED]:b.state(b.immediate(v.READYING),b.transition(k.UNLOAD,v.UNLOADING)),[v.RESETTING]:b.invoke(()=>{var o;return X(()=>{t.status=v.RESETTING}),(o=t.unload)==null||o.call(t),t.load()},b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED}))),[v.READYING]:b.invoke(()=>(X(()=>{t.status=v.READYING}),t.ready()),b.transition("done",v.READY,b.action(()=>{X(()=>{t.status=v.READY}),s.send(k.GO_ONLINE)})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.READY]:b.state(b.transition(k.UNLOAD,v.UNLOADED,b.action((r=t.unload)==null?void 0:r.bind(t))),b.transition(k.RESET,v.RESETTING),b.transition(k.GO_ONLINE,v.READY,b.action(()=>{s.send(k.GO_ONLINE)})),b.transition(k.GO_OFFLINE,v.READY,b.action(()=>{s.send(k.GO_OFFLINE)})),b.transition(k.GO_ACTIVE,v.READY,b.action(()=>{e.send(k.GO_ACTIVE)})),b.transition(k.GO_INACTIVE,v.READY,b.action(()=>{e.send(k.GO_INACTIVE)}))),[v.UNLOADED]:b.state(),[v.FAILED]:b.state()})},gg=m.createLogger({name:"kos-model-lifecycle"}),mg=t=>({service:b.interpret(pg(t),s=>gg.debug(`state machine for model ${t.modelId}: ${s.machine.current});`))});class yg{constructor(e,s){l(this,"disposer");l(this,"service");this.model=e,this.log=s;const r=mg(e);this.service=r.service,this.service.send(k.CREATE)}get current(){return this.service.machine.current}async transitionTo(e,s,r=v.FAILED){return this.getTransitionStatusFor(s)===s?(this.log.debug(`Model ${this.model.modelId} already in state ${s}, skipping transition`),Promise.resolve()):(this.log.debug(`Transitioning model ${this.model.modelId} with event ${e} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=M.when(()=>{const c=this.getTransitionStatusFor(s);return c===s||c===r},()=>{this.getTransitionStatusFor(s)===r?(this.log.error(`Model ${this.model.modelId} entered error state ${r} during transition`),i(new Error(`FSM transition failed for model ${this.model.modelId} with event ${e}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(e)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(e){return[v.ACTIVE,v.INACTIVE].includes(e)?this.model.activeStatus:this.model.status}}const nl="browser-router-model";class Cn{constructor(e,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=e,this.logger=s}registerAll(){var s;if(!yr(this.model))return;let e=this.model.__httpBrowserRouter;if(!e)for(const r of Object.keys(this.model)){const o=this.model[r];if(o&&typeof o=="object"&&"use"in o&&typeof o.use=="function"){e=o;break}}if(e||(e=(s=$e(nl))==null?void 0:s.model),!e)throw this.logger.error("Cannot register HTTP routes: BrowserRouter not found. The HTTP decorators should have auto-injected it, but something went wrong."),new Error("BrowserRouter is required for HTTP route decorators but was not found. This should not happen as HTTP decorators auto-inject the dependency.");this.setRouter(e)}setRouter(e){this.router=e,this.registered||this.registerRoutes()}hasRoutes(){return yr(this.model)}registerRoutes(){if(!this.router){this.logger.warn("Cannot register routes: router not set");return}if(this.registered){this.logger.debug("Routes already registered");return}const e=Dc(this.model);e.length!==0&&(this.logger.debug(`Registering ${e.length} HTTP routes`),e.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(e){const s=/\{PROP_([^}]+)\}/g;let r=e;if(r.includes("{MODEL_ID}")){const n=this.model.id||this.model._id||"unknown";r=r.replace(/\{MODEL_ID\}/g,n)}let o;for(;(o=s.exec(e))!==null;){const n=o[1];if(n in this.model){const i=this.model[n];r=r.replace(o[0],String(i))}else this.logger.warn(`Property '${n}' not found on model for PropKey resolution in path: ${e}`)}return r}registerRoute(e){if(!this.router)return;const s=this.model[e.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${e.handler}' not found on model`);return}const r=this.resolvePropKey(e.path);this.logger.debug(`Registering ${e.method} ${r} -> ${e.handler}`+(r!==e.path?` (resolved from ${e.path})`:""));const o=async(n,i)=>{var a;try{await s.call(this.model,n,i)}catch(c){this.logger.error(`Error in route handler ${e.method} ${r}:`,c),(a=i.status)==null||a.call(i,500).send({error:"Internal server error",message:c instanceof Error?c.message:String(c)})}};this.checkForDuplicateRoute(e.method,r),this.router.use(e.method,r,o),this.registeredRoutes.push({method:e.method,path:r})}checkForDuplicateRoute(e,s){if(!this.router)return;this.router.getRoutes().find(n=>n.method===e&&n.path===s)&&this.logger.warn(`Duplicate route detected: ${e} ${s}. This route is already registered by another model. The new handler from model '${this.model.id||"unknown"}' will override the existing one. Only the last registered handler will receive requests. Consider using different paths or namespacing to avoid conflicts.`)}dispose(){if(this.router&&this.registeredRoutes.length>0){this.logger.debug(`Removing ${this.registeredRoutes.length} HTTP routes for model ${this.model.id||"unknown"}`);let e=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);e+=r,r>0?this.logger.debug(`Removed route: ${s.method} ${s.path}`):this.logger.warn(`Failed to remove route: ${s.method} ${s.path} (not found)`)}this.logger.debug(`Successfully removed ${e} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function bg(t,e){if(!yr(t))return;const s=$e(nl);if(!(s!=null&&s.model))throw e.error("Cannot register HTTP routes: BrowserRouter not found. Make sure to include BrowserRouter in your model dependencies or create an instance."),new Error("BrowserRouter is required for HTTP route decorators but was not found. Add it as a dependency using @kosDependency or ensure an instance exists.");new Cn(t,e).setRouter(s.model)}class vg{constructor(e){l(this,"queue",[]);this.log=e}enqueue(e,s,r){this.queue.push({handler:e,receivedAt:Date.now(),topic:s,payload:r})}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const e of this.queue)try{e.handler()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}flushWithStrategy(e,s,r){if(this.queue.length===0)return;const o=this.queue.length,n=this.filterEventsByStrategy(e,s,r),i=o-n.length;this.log.warn(`Processing ${n.length}/${o} offline message(s) with strategy: ${e}`);for(const a of n)try{a.handler()}catch(c){this.log.error(`Error while processing offline message for topic ${a.topic}:`,c)}this.queue=[],this.log.info(`Offline queue flushed with strategy ${e}. Replayed: ${n.length}, Discarded: ${i}`)}filterEventsByStrategy(e,s,r){switch(e){case nt.ALL:return[...this.queue];case nt.AFTER_REQUEST:return s===void 0?(this.log.warn("AFTER_REQUEST strategy requires baselineRequestedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=s);case nt.AFTER_RESPONSE:return r===void 0?(this.log.warn("AFTER_RESPONSE strategy requires baselineReceivedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=r);case nt.NONE:return[];default:return this.log.warn(`Unknown replay strategy: ${e}, replaying all`),[...this.queue]}}getStatistics(e,s){if(this.queue.length===0)return{total:0};const r=this.queue.map(n=>n.receivedAt),o={total:this.queue.length,oldestEventAt:Math.min(...r),newestEventAt:Math.max(...r)};return e!==void 0&&(o.afterRequest=this.queue.filter(n=>n.receivedAt>=e).length),s!==void 0&&(o.afterResponse=this.queue.filter(n=>n.receivedAt>=s).length),o}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class wg{constructor(e,s){l(this,"unsubscribers",[]);this.model=e,this.log=s}register(){const e=this.model.modelId,s=C("/kosCore/online",async()=>{this.log.debug(`Online event received for ${e}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${e} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(k.GO_ONLINE,v.ONLINE)}),r=C("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${e} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(k.GO_OFFLINE,v.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}}const il=()=>({isMock:!1,URL:exports.BASE_URL}),Eg=m.createLogger({name:"kos-service-request"}),Mg="errUnknown";async function Js(t,e,s,r,o){const n=r!=null&&r.path?Object.keys(r.path).reduce((h,f)=>String(h).replace(`{${f}}`,r==null?void 0:r.path[f]),String(t)):String(t),i=r!=null&&r.query?Object.keys(r.query).map(h=>`${encodeURIComponent(h)}=${encodeURIComponent(r.query[h])}`).join("&"):"",a=`${il().URL}${n}${i?`?${i}`:""}`;Eg.debug(`fullUrl: ${a}`);const c={method:String(e).toUpperCase(),body:null,...s};o&&(c.body=JSON.stringify(o));const u=await exports.kosFetch(a,c);return u.status<200||u.status>=400?[`${u.statusText||Mg}`,null]:[null,(await u.json()).data]}function Be(){return{get:(t,e,s)=>Js(t,"get",s,e),post:(t,e,s,r)=>Js(t,"post",r,e,s),put:(t,e,s,r)=>Js(t,"put",r,e,s),delete:(t,e,s,r)=>Js(t,"delete",r,e,s)}}const Ae=Be(),al=Object.freeze(Object.defineProperty({__proto__:null,default:Ae},Symbol.toStringTag,{value:"Module"})),et=m.createLogger({name:"kos-service-request-manager",group:"Model"});function Tg(t,e){return!t.condition||t.condition(e)}function _g(t,e){return he({value:t.path,modelId:e.id,modelData:e})}function Sg(t,e){if(t.pathParams)return he({value:typeof t.pathParams=="function"?t.pathParams(e):t.pathParams,modelId:e.id,modelData:e})}function Og(t,e){if(t.queryParams)return he({value:typeof t.queryParams=="function"?t.queryParams(e):t.queryParams,modelId:e.id,modelData:e})}function Ig(t,e){if(t.body)return he({value:typeof t.body=="function"?t.body(e):t.body,modelId:e.id,modelData:e})}function $g(t,e){if(t.requestOptions)return typeof t.requestOptions=="function"?t.requestOptions(e):t.requestOptions}function Cg(t){return(t||"get").toLowerCase()}function er(t,e){return`${e.toUpperCase()}:${t}`}function cl(t){return t==null}function Dg(t,e,s,r){r&&cl(t)&&et.warn(`Required field '${e}' is missing in response for ${s}`)}function xg(t,e){return cl(t)&&e!==void 0?e:t}class Ag{constructor(e,s){l(this,"model");l(this,"responseStore");l(this,"handlers");this.model=e,this.responseStore=s,this.handlers=new Map,this.discoverHandlers()}discoverHandlers(){const s=Object.getPrototypeOf(this.model)[at]||{};Object.values(s).forEach(r=>{const o=r.lifecycle;this.handlers.has(o)||this.handlers.set(o,[]),this.handlers.get(o).push(r)}),Object.keys(s).length>0&&et.debug(`Discovered ${Object.keys(s).length} service request handlers for model ${this.model.id}`)}async executeForLifecycle(e){const s=this.handlers.get(e);!s||s.length===0||(et.debug(`Executing ${s.length} service requests for lifecycle ${e}`),await Promise.all(s.map(r=>this.executeHandler(r))))}async executeHandler(e){try{if(!this.shouldProcessRequest(e))return;const s=await this.prepareAndExecuteRequest(e);await this.processAndStoreResponse(s,e)}catch(s){const r=s instanceof Error?s:new Error(String(s));await this.handleError(r,e)}}shouldProcessRequest(e){return Tg(e,this.model)?!0:(et.debug(`Skipping request ${e.path} - condition returned false`),!1)}async prepareAndExecuteRequest(e){const s=this.prepareRequest(e),r=this.captureRequestTiming(),[o,n]=await this.performRequest(s),i=this.captureResponseTiming();return{requestContext:s,error:o,response:n,requestedAt:r.requestedAt,receivedAt:i.receivedAt}}captureRequestTiming(){return{requestedAt:Date.now()}}captureResponseTiming(){return{receivedAt:Date.now()}}async processAndStoreResponse(e,s){if(e.error){await this.handleError(new Error(e.error),s);return}const r=await this.processResponse(e.response,s);await this.storeAndInvokeHandler(r,s,e.requestContext.resolvedPath,e.requestedAt,e.receivedAt)}prepareRequest(e){const s=_g(e,this.model),r=Sg(e,this.model),o=Og(e,this.model),n=Ig(e,this.model),i=$g(e,this.model),a=Cg(e.method);return{resolvedPath:s,method:a,pathParams:r,queryParams:o,body:n,requestOptions:i}}async performRequest(e){return await this.makeRequest(e.resolvedPath,e.method,{path:e.pathParams,query:e.queryParams},e.body,e.requestOptions)}async processResponse(e,s){let r=e;return s.transform&&(r=s.transform(e)),s.mappings&&s.mappings.length>0&&(r=this.applyMappings(r,s)),s.iterateOver&&(r=await this.handleIteration(r,s)),r}async storeAndInvokeHandler(e,s,r,o,n){const i=s.cache||{retention:se.SINGLE},a=er(r,s.method||"get");this.responseStore.set(a,e,i,o,n),await s.originalHandler.call(this.model,null,e),this.triggerBaselineQueueFlush(r),this.responseStore.shouldCleanupAfterHandler(a)&&this.responseStore.delete(a)}triggerBaselineQueueFlush(e){const s=this.model.subscriptionManager;!s||!s.flushQueueForBaseline||s.flushQueueForBaseline(e)}async makeRequest(e,s,r,o,n){const i=Ae;switch(s){case"get":return await i.get(e,r,n);case"post":return await i.post(e,r,o,n);case"put":return await i.put(e,r,o,n);case"delete":return await i.delete(e,r,o,n);default:return[`Unsupported HTTP method: ${s}`,null]}}applyMappings(e,s){if(!s.mappings||s.mappings.length===0)return e;const r={};return s.mappings.forEach(o=>{const n=this.getNestedValue(e,o.from),i=o.transform?this.applyTransform(n,o.transform):n;Dg(i,o.from,s.path,o.required||!1);const a=xg(i,o.default);r[o.to]=a}),r}getNestedValue(e,s){return s.split(".").reduce((r,o)=>r==null?void 0:r[o],e)}applyTransform(e,s){if(typeof s=="function")return s(e);switch(s){case"string":return String(e);case"number":return Number(e);case"boolean":return!!e;case"date":return e?new Date(e):void 0;case"json":return typeof e=="string"?JSON.parse(e):e;default:return et.warn(`Unknown transformer: ${s}`),e}}async handleIteration(e,s){if(!s.iterateOver)return e;const r=this.getNestedValue(e,s.iterateOver);return Array.isArray(r)?s.modelFactory?r.map(o=>{const n=s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o,i=s.idExtractor?s.idExtractor(n):n.id;if(!i)throw new Error("Cannot create model instance: no ID found in response data. Provide an 'idExtractor' function or ensure response items have an 'id' field.");const a=s.modelFactory;return typeof a=="function"?a(i)(n):a.instance(i).options(n).build()}):r.map(o=>s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o):(et.warn(`iterateOver path '${s.iterateOver}' did not resolve to an array`),[])}async handleError(e,s){const r=s.errorHandler||{strategy:"throw"};switch(r.onError&&r.onError(e,this.model),r.strategy){case"throw":throw e;case"log":if(et.error(`Service request failed for ${s.path}:`,e.message),r.defaultValue!==void 0){const o=er(s.path,s.method||"get");this.responseStore.set(o,r.defaultValue,s.cache||{retention:se.SINGLE}),await s.originalHandler.call(this.model,e.message,r.defaultValue)}break;case"ignore":if(r.defaultValue!==void 0){const o=er(s.path,s.method||"get");this.responseStore.set(o,r.defaultValue,s.cache||{retention:se.SINGLE}),await s.originalHandler.call(this.model,e.message,r.defaultValue)}break;case"default":if(r.defaultValue!==void 0){const o=er(s.path,s.method||"get");this.responseStore.set(o,r.defaultValue,s.cache||{retention:se.SINGLE}),await s.originalHandler.call(this.model,e.message,r.defaultValue)}break}}}class Rg{constructor(e){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=e,this.subscription={queue:[],resolvers:[],closed:!1};const s=C(e,r=>{if(!this.subscription.closed&&r!==void 0){const o=this.subscription.resolvers.shift();o?o(r):this.subscription.queue.push(r)}});this.unsubscribe=s.unsubscribe}async next(){return this.subscription.closed&&this.subscription.queue.length===0?{done:!0,value:void 0}:this.subscription.queue.length>0?{done:!1,value:this.subscription.queue.shift()}:new Promise(e=>{this.subscription.closed?e({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{e({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(e=>{e(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(e){throw this.subscription.closed=!0,this.unsubscribe(),e}[Symbol.asyncIterator](){return this}}function Ui(t){return new Rg(t)}const ll=({path:t,requestId:e,method:s,destinationAddress:r})=>{let o=`${qr}:${s}
32
32
  `;return o+=`topic:${t}
33
33
  `,o+=`${Bt}:${t}
34
34
  `,o+=`${Ns}:${e}
@@ -104,10 +104,10 @@ cmd:${s}
104
104
  ${u}topics:${e}
105
105
  `:`${u}type:kos.broker.${s}
106
106
 
107
- ["${e}"]`;if(r?(p=this.fosSocket)==null?void 0:p.connectionEstablished:(y=this.socket)==null?void 0:y.connectionEstablished){const E=r?this.fosSocket:this.socket;(w=E==null?void 0:E.socket)==null||w.send(d)}else{Xe.debug("no connection adding to offline messages");const E=r?this.fosSocket:this.socket;E==null||E.addOfflineMessage(d)}}subscribeTopic({topic:e,callback:s,fos:r,bridge:o,destinationAddress:n}){const{unsubscribe:i,count:a}=C(e,s);return Xe.debug(`Topic ${e} currently has ${a} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,o,n),()=>{const{count:c}=i();Xe.debug(`Topic ${e} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(e,"unsubscribe",r,o,n)}}async whenReady(){const e=this;return this.webSocketSupported?(await M.when(()=>{var s,r;return!!((s=e.socket)!=null&&s.connectionEstablished)&&(!e.useFosTransport||!!((r=e.fosSocket)!=null&&r.connectionEstablished))&&e.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(e){this._token=e,this.init()}static host(e="localhost"){return this.getInstance().host=e,this}static port(e=8080){return this.getInstance().port=e,this}static alias(e){this.getInstance().alias=e}static getInstance(e=8080,s){if(!this._instance){const r=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:e,token:s,fos:r})}return this._instance}}l(Ct,"_instance");class Vg{constructor(e,s,r,o,n){l(this,"disposers",[]);l(this,"activatableDisposers",[]);l(this,"flowControllers",new Map);l(this,"baselineDependencies",new Map);this.model=e,this.modelData=s,this.modelId=r,this.offlineQueue=o,this.log=n}registerAll(e){var o;const s=((o=this.modelData)==null?void 0:o[J])||{},r=Object.keys(s);this.log.debug(`Found ${r.length} subscriptions in ${this.modelId} (lifecycle: ${e??"any"})`),r.forEach(n=>{const i=s[n],a=i.lifecycle;if(e&&e!==a)return;const c=this.resolvePropKey(n);if(this.log.debug(`Resolved topic: ${n} → ${c}`),i.requiresBaseline&&(this.baselineDependencies.set(c,i.requiresBaseline),this.log.debug(`Registered baseline dependency for ${c}: ${i.requiresBaseline.path}`)),i.flow)this.subscribeWithFlowControl(i,c,a);else{const u=this.createHandler(c,i);this.subscribe(i,c,u,a===x.ACTIVATE)}})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const e of this.activatableDisposers)try{e()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const e=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${e.length} subscriptions for ${this.modelId}`);for(const[s,r]of this.flowControllers)this.log.debug(`Disposing flow controller for ${s}`);this.flowControllers.clear();for(const s of e)try{s()}catch(r){this.log.error("Error during subscription disposal",r)}this.disposers=[],this.activatableDisposers=[]}subscribe(e,s,r,o){const n=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;if(e.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=Ct.getInstance().subscribeTopic({topic:s,callback:r,fos:e.fos,bridge:e.bridge,destinationAddress:n});o?this.activatableDisposers.push(i):this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=C(s,r);o?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(e,s){return async r=>{var o;try{const n=(o=r==null?void 0:r.headers)==null?void 0:o["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),a=i?n===i:!0,c=this.extractWildcardCapture(e,r,s),u=this.isBaselineReady(e);if(!this.model.isReady()||!u){u?this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${e}`):this.log.warn(`Baseline not ready for ${e}. Queuing message.`);const d=()=>{const h=No(r,s.skipParse),f=s.transform(h);if(a&&s.condition(f,this.modelData,r))return this.callHandlerWithWildcard(s,f,c,r)};this.offlineQueue.enqueue(d,e,r)}else{const d=No(r,s.skipParse),h=s.transform(d);if(a&&s.condition(h,this.modelData,r))return this.callHandlerWithWildcard(s,h,c,r)}}catch(n){this.log.error(`Error handling subscription for ${e}`,n)}}}extractWildcardCapture(e,s,r){var n;if(!r.wildcardName||!Vc(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return zc(e,o,r.wildcardName)}callHandlerWithWildcard(e,s,r,o){if(r&&Object.keys(r).length>0){const n={...o,wildcardCapture:r};return e.handler.call(this.modelData,s,n,this.modelData)}else return e.handler.call(this.modelData,s,o,this.modelData)}resolvePropKey(e){const s=/.*({PROP_(.+)})/;let r=e.includes("{MODEL_ID}")?e.replace("{MODEL_ID}",this.modelId):e;const o=r.match(s);return o&&o[2]in this.modelData&&(r=r.replace(o[1],this.modelData[o[2]])),r}async subscribeWithFlowControl(e,s,r){this.log.debug(`Setting up flow control for topic: ${s}`);const o=new Ng(e.flow);this.flowControllers.set(s,o);const n=this.createFlowControlHandler(s,e),i=this.startFlowProcessing(e,s,n,o),a=()=>{this.flowControllers.delete(s),i.then(c=>c==null?void 0:c.abort())};r===x.ACTIVATE?this.activatableDisposers.push(a):this.disposers.push(a)}async startFlowProcessing(e,s,r,o){const n=new AbortController;try{let i;if(e.websocket){const a=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;Ct.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a}),i=Ui(s)}else i=Ui(s);return(async()=>{try{for await(const a of o.processEvents(i)){if(n.signal.aborted)break;const c=r(a);c instanceof Promise&&await o.trackPromise(c)}}catch(a){this.log.error(`Flow control error for ${s}:`,a)}})(),n}catch(i){return this.log.error(`Failed to start flow processing for ${s}:`,i),null}}createFlowControlHandler(e,s){return async r=>{var o,n,i,a;try{if(s.condition&&!s.condition(r,this.modelData,r))return;if(this.model.isReady())return s.handler.call(this.modelData,r,r,this.modelData);{this.log.warn(`Model ${this.modelId} not ready. Queuing flow-controlled message for ${e}`);const c=()=>s.handler.call(this.modelData,r,r,this.modelData);this.offlineQueue.enqueue(c,e,r)}}catch(c){if(this.log.error(`Error in flow control handler for ${e}:`,c),(n=(o=s.flow)==null?void 0:o.errorHandling)!=null&&n.retry)await this.retryHandler(s,r,c);else if(!((a=(i=s.flow)==null?void 0:i.errorHandling)!=null&&a.continueOnError))throw c}}}async retryHandler(e,s,r){const o=e.flow.errorHandling.retry;let n=r;for(let i=1;i<=o.attempts;i++)try{return this.log.debug(`Retry attempt ${i}/${o.attempts} for handler`),await new Promise(a=>setTimeout(a,o.backoffMs*i)),e.handler.call(this.modelData,s,s,this.modelData)}catch(a){n=a,this.log.warn(`Retry attempt ${i} failed:`,a)}throw this.log.error("All retry attempts failed, throwing last error:",n),n}getFlowControlStats(){const e={};for(const[s,r]of this.flowControllers)e[s]=r.getStats();return e}getResponseStore(){return this.modelData.serviceResponses}isBaselineReady(e){const s=this.baselineDependencies.get(e);if(!s)return!0;const r=this.getResponseStore();if(!r)return this.log.warn(`ServiceResponseStore not found for baseline check on topic: ${e}`),!1;const n=`${(s.method||"get").toUpperCase()}:${s.path}`;return r.has(n)}flushQueueForBaseline(e){const s=this.baselineDependencies.get(e);if(!s){this.log.debug(`No baseline dependency for topic: ${e}`);return}const r=this.getResponseStore();if(!r){this.log.warn("ServiceResponseStore not found, falling back to standard flush"),this.offlineQueue.flush();return}const o=s.method||"get",n=r.getTemporalMetadataByPath(s.path,o);if(!n){this.log.warn(`Baseline temporal metadata not found for ${s.path}, falling back to standard flush`),this.offlineQueue.flush();return}const i=s.replayStrategy||ot.AFTER_REQUEST;this.log.info(`Flushing queue with strategy ${i} for topic: ${e}`),this.log.debug(`Baseline timing - requested: ${n.requestedAt}, received: ${n.receivedAt}`),this.offlineQueue.flushWithStrategy(i,n.requestedAt,n.receivedAt)}}function yt(t,e){const s=`[Model:${e}]`;return{debug:(...r)=>t.debug(s,...r),info:(...r)=>t.info(s,...r),warn:(...r)=>t.warn(s,...r),error:(...r)=>t.error(s,...r)}}function Gg(t){return!!(t!=null&&t[nt])&&Object.keys(t[nt]).length>0}function Yg(t){return!!(t!=null&&t[J])&&Object.keys(t[J]).length>0}function Wg(t){return!!(t!=null&&t[ke])&&t[ke].length>0}function Qg(t){const e=Object.getPrototypeOf(t);return!!(e!=null&&e[it])&&Object.keys(e[it]).length>0}function Zg(t){return t.retention===se.TTL&&t.extendOnRefresh===!0&&t.ttl!==void 0}function Xg(t,e){return t.has(e)}function Jg(t){return!t.expiresAt||Date.now()<t.expiresAt}function Hi(t,e,s,r){const o=setTimeout(()=>r(t),e);s.set(t,o)}class em{constructor(){l(this,"responses",new Map);l(this,"retentionPolicies",new Map);l(this,"cleanupTimers",new Map)}set(e,s,r={retention:se.SINGLE},o=Date.now(),n=Date.now()){if(this.shouldExtendTTL(e,r))return this.extendExistingTTL(e,r.ttl),!1;const i=this.createCachedResponse(s,e,r,o,n);return this.storeResponse(e,i,r),!0}get(e){const s=this.responses.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.delete(e);return}return s.data}}getByPath(e,s="get"){return this.get(this.makeKey(e,s))}has(e){return this.get(e)!==void 0}delete(e){this.responses.delete(e),this.retentionPolicies.delete(e);const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}clearPath(e){Array.from(this.responses.keys()).filter(r=>this.extractPath(r)===e).forEach(r=>this.delete(r))}clear(){this.cleanupTimers.forEach(e=>clearTimeout(e)),this.responses.clear(),this.retentionPolicies.clear(),this.cleanupTimers.clear()}get size(){return this.responses.size}shouldCleanupAfterHandler(e){const s=this.retentionPolicies.get(e);return(s==null?void 0:s.retention)===se.IMMEDIATE}shouldExtendTTL(e,s){if(!Zg(s)||!Xg(this.responses,e))return!1;const r=this.responses.get(e);return Jg(r)}extendExistingTTL(e,s){const r=this.responses.get(e);r.expiresAt=Date.now()+s,this.resetCleanupTimer(e,s)}resetCleanupTimer(e,s){this.clearTimerIfExists(e),Hi(e,s,this.cleanupTimers,r=>this.delete(r))}clearTimerIfExists(e){const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}createCachedResponse(e,s,r,o,n){return{data:e,timestamp:n,requestedAt:o,receivedAt:n,path:this.extractPath(s),method:this.extractMethod(s),expiresAt:this.calculateExpiresAt(r)}}calculateExpiresAt(e){return e.retention===se.TTL&&e.ttl?Date.now()+e.ttl:void 0}storeResponse(e,s,r){this.responses.set(e,s),this.retentionPolicies.set(e,r),this.applyRetentionPolicy(e,r)}applyRetentionPolicy(e,s){switch(s.retention){case se.IMMEDIATE:break;case se.TTL:s.ttl&&Hi(e,s.ttl,this.cleanupTimers,r=>this.delete(r));break;case se.SINGLE:break;case se.PERMANENT:case se.MANUAL:break}}makeKey(e,s){return`${s.toUpperCase()}:${e}`}extractPath(e){return e.split(":",2)[1]||e}extractMethod(e){return e.split(":",2)[0]||"get"}getTemporalMetadata(e){const s=this.responses.get(e);if(s)return{requestedAt:s.requestedAt,receivedAt:s.receivedAt}}getTemporalMetadataByPath(e,s="get"){return this.getTemporalMetadata(this.makeKey(e,s))}cleanup(){const e=Date.now();Array.from(this.responses.entries()).filter(([r,o])=>o.expiresAt&&e>o.expiresAt).map(([r])=>r).forEach(r=>this.delete(r))}}class tm{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=xc.create({modelId:s,modelTypeName:r}),i=new yg(e,yt(n,"fsm")),a=new vg(yt(n,"offline-queue")),c=new lg(e),u=new cg(e),d=new em;o.serviceResponses=d;const h={fsm:i,offlineQueue:a,serviceResponseStore:d,companionManager:c,childResolver:u};if(Gg(o)&&(h.effectManager=new ug(r,s,o,yt(n,"effect"))),Yg(o)){const f=yt(n,"subscription");h.subscriptionManager=new Vg(e,o,s,a,f),h.onlineLifecycleManager=new wg(e,yt(n,"online"))}return Wg(o)&&(h.httpRouteManager=new Cn(o,yt(n,"http-routes"))),Qg(o)&&(h.serviceRequestManager=new Ag(o,d)),h}}const N=D.getLogger("kos-model"),sm="kos.extension.model.loader";class El{constructor({modelTypeName:e,id:s,modelData:r}){l(this,"_id");l(this,"_status");l(this,"_activeStatus");l(this,"_onlineStatus");l(this,"modelData");l(this,"modelTypeName");l(this,"initialized");l(this,"loaded");l(this,"_isLoadExecuting");l(this,"offlineQueue");l(this,"subscriptionManager");l(this,"effectManager");l(this,"httpRouteManager");l(this,"onlineLifecycleManager");l(this,"serviceResponses");l(this,"serviceRequestManager");l(this,"companionManager");l(this,"childResolver");l(this,"fsm");this._id=typeof s<"u"?`${s}`:e,this.modelTypeName=e,this.initialized=!1,this.loaded=!1,this._isLoadExecuting=!1,this.modelData=r,this._status=v.CREATED,this._activeStatus=v.INACTIVE,this._onlineStatus=v.OFFLINE;const o=tm.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,this.serviceResponses=o.serviceResponseStore,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.httpRouteManager&&(this.httpRouteManager=o.httpRouteManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),o.serviceRequestManager&&(this.serviceRequestManager=o.serviceRequestManager),M.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,serviceRequestManager:!1,serviceResponses:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),ig(this)}get companionModels(){return this.companionManager}set status(e){this._status=e}get status(){return this._status}get modelId(){return this._id}get id(){return this._id}get activeStatus(){return this._activeStatus}set activeStatus(e){this._activeStatus=e}get onlineStatus(){return this._onlineStatus}set onlineStatus(e){this._onlineStatus=e}get modelManager(){return globalThis.kos.modelManager}isActive(){return this._status===v.ACTIVE}isOnline(){return this._onlineStatus===v.ONLINE}isReady(){return this._status===v.READY}async deactivate(){var e,s,r;N.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=V.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,o)),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw N.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var e,s,r,o;N.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await ts(this,x.ACTIVATE);try{await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(x.ACTIVATE));const n=V.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.activate)==null?void 0:r.call(s,n)),this.initializeStateMachineForLifecycle(x.ACTIVATE),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(x.ACTIVATE),this.createLifecycleCompanions(x.ACTIVATE),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(n){throw N.debug(`Model ${this.modelId} failed to activate`),n}}async whenLoaded(){await _o([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{N.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await _o([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{N.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await _o([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===v.READY,onMatch:()=>{N.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r,o;if(this.fsm.current===v.READY){N.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{N.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await ts(this,x.READY),await ol(this,In.READY,x.READY),await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(x.READY));const n=V.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.ready)==null?void 0:r.call(s,n)),this.offlineQueue.flush(),this.initializeStateMachineForLifecycle(x.READY),(o=this.subscriptionManager)==null||o.registerAll(x.READY),this.createLifecycleCompanions(x.READY),N.debug(`Model ${this.modelId} is ready`);const i={modelId:this.modelId,modelType:this.modelTypeName};q(Wc(this.modelTypeName,this.modelId),i),q(Qc(this.modelTypeName),i)}catch(n){throw N.error(n),Error(n)}}async load(){var o,n,i,a,c,u;const e=this[Ve];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===v.LOADED){N.debug(`Model ${s} with id ${r} already loaded`);return}if(this._isLoadExecuting){N.debug(`Model ${s} with id ${r} is currently executing load`);return}this._isLoadExecuting=!0;try{N.debug(`Loading model ${s} with id ${r}`),await ts(this,x.LOAD);const d=V.getContext(r),h=`${sm}.${s}`,f=await $.loader.executeLoader(h,{});f&&(N.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(h,f)),await((o=this.serviceRequestManager)==null?void 0:o.executeForLifecycle(x.LOAD)),await((i=(n=this.modelData)==null?void 0:n.load)==null?void 0:i.call(n,d)),X(()=>{this.loaded=!0}),N.debug(`Model ${s} with id ${r} successfully loaded`),this.initializeStateMachineForLifecycle(x.LOAD),(a=this.subscriptionManager)==null||a.registerAll(x.LOAD),(c=this.httpRouteManager)==null||c.registerAll(),(u=this.effectManager)==null||u.setup(),this.createLifecycleCompanions(x.LOAD)}catch(d){throw N.error(`Model ${r} failed to load`,d),d}finally{this._isLoadExecuting=!1}}async unload(){var e,s,r,o,n,i,a;N.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const c=this.getChildren().map(d=>{var h;return(h=d.unload)==null?void 0:h.call(d)}).filter(d=>!!d);await Promise.allSettled(c);const u=V.getContext(this.modelId);if(await((s=(e=this.modelData)==null?void 0:e.unload)==null?void 0:s.call(e,u)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),this.modelData){const d=this.modelData;if(d._fsmInitialized=!1,d._fsmConfig){const h=((o=d._fsmOptions)==null?void 0:o.stateProperty)||"currentState";d[h]=void 0}d.stateHistory&&(d.stateHistory=[])}N.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(n=this.effectManager)==null||n.disposeAll(),(i=this.subscriptionManager)==null||i.disposeAll(),(a=this.httpRouteManager)==null||a.dispose()}catch(c){throw N.debug(`Model ${this.modelId} failed to unload`),c}}async init(){var n,i,a,c;const e=this[Ve];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=V.getContext(s);N.debug(`Initializing model ${r} with id ${s}`),await ts(this,x.INIT);try{await((n=this.serviceRequestManager)==null?void 0:n.executeForLifecycle(x.INIT)),await((a=(i=this.modelData)==null?void 0:i.init)==null?void 0:a.call(i,o)),this.initialized=!0,N.debug(`Model ${r} with id ${s} initialized`),(c=this.onlineLifecycleManager)==null||c.register(),this.initializeStateMachineForLifecycle(x.INIT),this.registerSubscribers(x.INIT),this.createLifecycleCompanions(x.INIT)}catch(u){throw N.error(`Model ${s} failed to initialize`,u),u}}async registerSubscribers(e){var s;N.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}initializeStateMachineForLifecycle(e){this.modelData&&Oc(this.modelData,e)}createLifecycleCompanions(e){this.modelManager.createLifecycleCompanions(this,{},e)}async online(){var s,r;N.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=V.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e)),this.createLifecycleCompanions(x.ONLINE)}async offline(){var s,r,o;N.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=V.getContext(this.modelId);await((o=(r=this.modelData)==null?void 0:r.offline)==null?void 0:o.call(r,e))}accept(e){e.visit(this)}getChildren(){return this.childResolver.resolve()}addCompanionModel(e){this.companionManager.add(e)}clearCompanionModels(){this.companionManager.clear()}}const So=m.createLogger({name:"kos-model-instantiator"});class rm{constructor(e,s){l(this,"companionInstantiator");this.registry=e,this.cache=s,this.companionInstantiator=new Jp(e,s,this.createModelInstance.bind(this))}createModelInstance(e,s,r={}){var a;const o=this.registry.models[e];if(!o){const c=`No model registered for type ${e}`;throw So.error(c,{modelType:e,requestedId:s,providedOptions:r,availableModelTypes:Object.keys(this.registry.models)}),Ot(new Error(c),{modelType:e,modelId:s,operation:"model instantiation - registry lookup",options:r,metadata:{availableModelTypes:Object.keys(this.registry.models)}})}const n=o.singleton?e:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){So.debug(`Creating model instance: ${e} [${n}]`);const c=r&&Object.keys(r).length>0,u=o.class||o.create;if(((a=u==null?void 0:u.prototype)==null?void 0:a[Hs])===!0&&!c){const h=new Error(`Model ${e} requires options but none were provided`);throw Fi(h,{modelType:e,options:r,registryId:this.registry.alias||"unknown"}),Ot(h,{modelType:e,modelId:n,operation:"model instantiation - options validation",options:r,metadata:{requiresOptions:!0,hasOptions:!1}})}try{const h=o.create?o.create({modelTypeId:e,id:n,options:r}):new o.class(n,r),f=new El({modelTypeName:e,id:n,modelData:h});this.cache.addModel(f),this._createCompanionModels(f,r)}catch(h){throw Fi(h,{modelType:e,options:r,registryId:this.registry.alias||"unknown"}),Ot(h,{modelType:e,modelId:n,operation:"model instantiation",options:r})}}const i=this.cache.getModelById(n);if(!i)throw So.error(`Model ${e} [${n}] not found in cache`),new Error(`Model ${e} [${n}] not found in cache`);return{model:i,data:i.modelData}}createCompanionModels(e,s,r){this.companionInstantiator.createCompanionModels(e,s,r)}_createCompanionModels(e,s){this.createCompanionModels(e,s)}}let om=class{constructor(e){this._registry=e}get registry(){return this._registry}getModelTypeRegistry(e){const s=this.registry.models[e];if(!s)throw new Error(`No registration for model type ${e}`);return s}registerModel(e){const s=e.type;this.registry.models[s]||(this.registry.models={...this.registry.models,...e.registration})}registerCompanionModel(e,s){var r,o;(r=this.registry).companionModels??(r.companionModels={}),(o=this.registry.companionModels)[e]??(o[e]=[]),this.registry.companionModels[e].some(n=>n.type===s)||this.registry.companionModels[e].push({type:s})}getModelSubscriptions(e){var s;return((s=this.getModelTypeRegistry(e))==null?void 0:s.subscriptions)||{}}getDataModelBuilder(e){var r;const s=(r=this.getModelTypeRegistry(e))==null?void 0:r.builder;if(!s)throw new Error(`No builder found for model type ${e}`);return s}getModelFactory(e){return Kt(e)}};const Ml=10,Ki=m.createLogger({name:"kos-model-manager"});class Tl{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Qp,globalThis.kos.modelManager=this,globalThis.kos.resolveKosModel=e=>{const s=this.getModelById(e);if(s)return s.modelData||{}},globalThis.kos.kosModelJson=e=>{var r,o;const s=this.getModelById(e);if(s)return((o=(r=s.modelData).toJSON)==null?void 0:o.call(r))||{}},globalThis.kos.kosModelDebug=e=>{var r;const s=this.getModelById(e);if(s)return((r=s.modelData)==null?void 0:r.debugState)||{}},globalThis.kos.kmd=globalThis.kos.kosModelDebug,globalThis.kos.kmj=globalThis.kos.kosModelJson}static create(e,s){const r=this.getInstance(s);return r._registry=new om(e),r.cache=new Zp(e.preloadModels),r.instantiator=new rm(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(Ki.debug("Creating new instance of KosModelManager"),new this),(r=globalThis.kos)==null?void 0:r.modelManager}get registry(){return this._registry.registry}get preloadedModels(){return this.cache.preload(e=>(Ki.debug(`preloading ${e}`),typeof e=="string"?this.createModelInstance(e).model:this.createModelInstance(e.modelType,e.modelId,e.options).model))}get models(){return this.cache.models}getModelById(e){return this.cache.getModelById(e)}addModel(e){return this.cache.addModel(e)}removeModel(e){this.cache.removeModel(e.modelId)}hasModel(e){return this.cache.hasModel(e)}getModelsByType(e,s){return Array.from(this.models).filter(r=>r.modelTypeName===e).filter(r=>s?s(r.modelData):!0).map(r=>r.modelData)}getModelSubscriptions(e){return this._registry.getModelSubscriptions(e)}getDataModelBuilder(e){return this._registry.getDataModelBuilder(e)}getModelFactory(e){return Kt(e)}addDependency(e,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(e,s)}removeDependency(e,s){this.dependencies.remove(e,s)}async reloadModel(e){if(e.id){const s=this.getModelById(e.id);s&&await s.fsm.transitionTo(k.RESET,v.RESETTING)}}async initiateDestroyModel(e){if(!e.id)throw new Error("Model ID is required");if(!this.dependencies.canDestroy(e.id))return;const s=this.getModelById(e.id);s&&(this.cache.markForDeletion(s),Gc.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),Ml)))}async destroyModel(e){var s;e!=null&&e.modelId&&this.dependencies.canDestroy(e.modelId)&&(await((s=e.unload)==null?void 0:s.call(e)),this.removeModel(e))}createModelInstance(e,s,r={}){return this.instantiator.createModelInstance(e,s,r)}createLifecycleCompanions(e,s,r){this.instantiator.createCompanionModels(e,s,r)}registerCompanionModel(e,s){this._registry.registerCompanionModel(e,s)}registerModel(e){this._registry.registerModel(e)}}var dr=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.RELOADING="reloading",t))(dr||{}),Mt=(t=>(t.CREATE="create",t.INITIALIZE="init",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.UNLOAD="unload",t.RELOAD="reload",t))(Mt||{});const nm=t=>{const e=b.createMachine("offline",{online:b.state(b.transition("go_offline","offline",b.action(()=>{t.offline(),M.runInAction(()=>{t.isOnline=!1})}))),offline:b.state(b.transition("go_online","online",b.action(()=>{t.online(),M.runInAction(()=>{t.isOnline=!0})})))}),s=b.interpret(e,n=>D.debug(n.machine.current)),r=b.createMachine({creating:b.state(b.transition("create","created")),created:b.state(b.immediate("initializing")),initializing:b.invoke(()=>t.init(),b.transition("done","initialized")),initialized:b.state(b.immediate("loading")),loading:b.invoke(()=>t.load(),b.transition("done","loaded")),loaded:b.state(b.immediate("readying"),b.transition("unload","unloading")),readying:b.invoke(()=>t.ready(),b.transition("done","ready",b.action(()=>{M.runInAction(()=>{t.status="ready"})}))),reloading:b.invoke(()=>t.reload(),b.transition("done","loading")),ready:b.state(b.transition("reload","reloading"),b.transition("unload","unloaded",b.action(t.unload.bind(t))),b.transition("go_online","ready",b.action(()=>{s.send("go_online")})),b.transition("go_offline","ready",b.action(()=>{s.send("go_offline")}))),unloaded:b.state()});return{service:b.interpret(r,n=>D.debug(n.machine.current)),online:s}},W=m.createLogger({name:"kos-core"}),im=()=>{const t=be(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},am=()=>{const t=window.location.protocol,e=be(),s=e==null?void 0:e.host;let r;try{r=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return r||(t==="https:"?"wss://":"ws://")},cm=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=be(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??e??t},lm=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=be(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??e??t},um=(t,e)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{e?m.error(`Model ${e.modelId} - ${e.modelTypeName} preloading - timed out after ${t}ms`):m.error(`KOS Core preloading timed out after ${t}ms`),i(new Error(`Model ${e==null?void 0:e.modelId} - ${e==null?void 0:e.modelTypeName} - timed out after ${t}ms`))},t)}),cancel:()=>{s&&clearTimeout(s)}}},qi=t=>typeof t.reload=="function",dm=t=>typeof t.unload=="function";var _l=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(_l||{});class O{constructor(e){l(this,"fsmService");l(this,"status");l(this,"initialized");l(this,"loaded");l(this,"_transport");l(this,"modelManager");l(this,"authState");l(this,"isOnline");l(this,"_reloading");l(this,"_unloading");l(this,"connectionAlias");this.initialized=!1,this.connectionAlias=e,this.loaded=!1,this.isOnline=!1,this.status=dr.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),C("token",a=>{a&&(this.transport.token=a.body)}),C(Ms.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(Mt.GO_ONLINE)}),C(Ms.DISCONNECTED,async()=>{this.fsmService.service.send(Mt.GO_OFFLINE)}),C("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),C("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),C(Ms.RELOAD,()=>{W.warn("WebSocket requested reload"),this.fsmService.service.send(Mt.RELOAD)}),C("/studio/project/reload",()=>{W.warn("Project requested reload"),this.fsmService.service.send(Mt.RELOAD)});const s=Ct.getInstance(),r=cm(),o=lm(),n=am();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=im()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=nm(this),this.fsmService.service.send(Mt.CREATE)}get onlineStatus(){return this.isOnline&&!this._reloading&&!this._unloading}get reloading(){return this._reloading}get unloading(){return this._unloading}async reload(){var o,n,i,a;const e=Date.now();if(this._reloading){W.info("reload already in progress");return}this._reloading=!0,W.warn("reloading KOS Core"),W.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)qi(c.modelData)&&(W.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),W.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&qi(c.modelData)&&((i=c.unload)==null||i.call(c),await c.modelData.reload(),(a=c.registerSubscribers)==null||a.call(c));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{W.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){W.debug("KOS Core going online"),await this._transport.whenReady(),W.debug("KOS Transport Ready. Calling online() for models"),q("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){W.debug("KOS Core going offline"),q("/kosCore/offline","/kosCore/offline")}async unload(){var o;W.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,W.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)dm(n.modelData)&&((o=n.unload)==null||o.call(n));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{this._unloading=!1})},1e3-r)}async whenReady(){await M.when(()=>this.status===dr.READY)}async ready(){W.debug("Readying KOS Core"),await this._transport.whenReady();const e=this.modelManager.preloadedModels.map(o=>({modelId:o.modelId,model:o,promise:o.whenReady()})),r=(await Promise.allSettled(e.map(o=>{const{promise:n,cancel:i}=um(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw W.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);W.debug("leaving kos-core ready() ")}get isReady(){return this.status===dr.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){W.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,W.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){W.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,W.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(e,s,r){var i,a,c;const o=this.getInstance({reset:s,connectionAlias:r});(i=e.extensions)!=null&&i.dataMapper&&Object.keys(e.extensions.dataMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.dataMapper)==null?void 0:f[u];d&&(Array.isArray(d)?d.forEach(p=>{$.dataMapper.registerDataMapper(u,p)}):$.dataMapper.registerDataMapper(u,d))}),(a=e.extensions)!=null&&a.propertyMapper&&Object.keys(e.extensions.propertyMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.propertyMapper)==null?void 0:f[u];d&&$.propertyMapper.registerPropertyMapper(u,d)}),(c=e.extensions)!=null&&c.contextLoader&&Object.keys(e.extensions.contextLoader).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.contextLoader)==null?void 0:f[u];d&&$.loader.registerLoader(u,d)}),A.model.getAll().forEach(([,u])=>{e.models={...e.models,...u.registration}}),e.models={...e.models,...A.model.getLegacyModels()},A.companion.getAll().forEach(([u,d])=>{e.companionModels={...e.companionModels},e.companionModels[u]=e.companionModels[u]||[];for(const h of d){let f;if(typeof h=="string"){const p=e.models[h];if(p!=null&&p.class){const y=p.class.prototype[Ve];f=y==null?void 0:y.lifecycle}}e.companionModels[u].push({type:h,lifecycle:f})}}),A.model.getPreloadModels().forEach(u=>{e.preloadModels.includes(u)||e.preloadModels.push(u)});const n=Tl.create(e,s);return o.modelManager=n,o}static getInstance(e){return this._instance=window.KosCore,(!this._instance||e!=null&&e.reset)&&(window.KosCore=new this(e==null?void 0:e.connectionAlias),this._instance=window.KosCore),this._instance}}l(O,"_instance");function jo(t){const e=new Uint8Array(t);let s="";for(let r=0;r<e.byteLength;r++)s+=String.fromCharCode(e[r]);return btoa(s)}function hm(t){const e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s.buffer}async function fm(t){return await t.arrayBuffer()}function pm(t,e){return new Blob([t],{type:e})}async function gm(t){const e={},s=[],r=[];t.forEach((o,n)=>{r.push([n,o])});for(const[o,n]of r)if(n instanceof File){const i=await n.arrayBuffer();s.push({name:o,filename:n.name,type:n.type,data:jo(i)})}else e[o]=n.toString();return{fields:e,files:s}}function mm(t){return new ReadableStream({async start(){},async pull(e){await t(e)},cancel(){}})}async function ym(t){if(!t)return{data:"",contentType:"text/plain"};if(typeof t=="string")return{data:t,contentType:"text/plain"};if(t instanceof ArrayBuffer||t instanceof Uint8Array){let e;return t instanceof Uint8Array?(e=new ArrayBuffer(t.byteLength),new Uint8Array(e).set(t)):e=t,{data:jo(e),contentType:"application/octet-stream",encoding:"base64"}}if(t instanceof Blob){const e=await fm(t);return{data:jo(e),contentType:t.type||"application/octet-stream",encoding:"base64"}}if(t instanceof FormData){const e=await gm(t);return{data:JSON.stringify(e),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const tr=m.createLogger({name:"kos-fetch"}),bm=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,vm=()=>new Promise(t=>{setTimeout(()=>{t(!0)},0)}),wm=t=>t!=null&&t.studio?ll:t!=null&&t.fos?ul:dl,Em=async(t,e)=>{const s=O.getInstance().transport;await s.whenReady();const r=lt(),o=new URL(t),n=`${o.pathname}${o.search}`;tr.debug(`path: ${n}`);const i=(e==null?void 0:e.timeout)||bm,a=wm(e),c=await ym(e==null?void 0:e.body),u={};c.contentType&&(u["content-type"]=c.contentType),c.encoding&&(u["content-encoding"]=c.encoding);const d=Qe(a({path:n,requestId:r,method:(e==null?void 0:e.method)||"GET",destinationAddress:(e==null?void 0:e.destinationAddress)||"",ordered:e==null?void 0:e.ordered,tracker:e==null?void 0:e.tracker,bridge:e==null?void 0:e.bridge,headers:{...e==null?void 0:e.headers,...u}}),c.data);return new Promise(h=>{let f=null,p=null;if(e!=null&&e.signal){if(e.signal.aborted){h({headers:ss({}),status:0,ok:!1,json:async()=>null,body:rs(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}});return}e.signal.addEventListener("abort",()=>{p&&clearTimeout(p),f&&f(),h({headers:ss({}),status:0,ok:!1,json:async()=>null,body:rs(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})})}p=setTimeout(()=>{tr.error(`Timeout occurred - url: ${t}`),f&&f(),h({headers:ss({}),status:404,ok:!1,json:async()=>null,body:rs(""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})},i);const y=C(r,E=>{p&&clearTimeout(p);const _=(E==null?void 0:E.headers)||{},L=_["content-type"]||"text/plain",U=_["content-encoding"],I=(E==null?void 0:E.body)||"";let S=I;if(U==="base64"&&I)try{S=hm(I)}catch(Y){tr.error("Failed to decode base64 response",Y)}const Z={headers:ss(_),status:_.status&&parseInt(_.status)||200,ok:_.status==="200",json:async()=>{try{if(typeof S=="string")return S.length?JSON.parse(S):null;{const le=new TextDecoder().decode(S);return le.length?JSON.parse(le):null}}catch{throw Error("Not a JSON response")}},text:async()=>typeof S=="string"?S:new TextDecoder().decode(S),arrayBuffer:async()=>S instanceof ArrayBuffer?S:new TextEncoder().encode(S).buffer,blob:async()=>S instanceof ArrayBuffer?pm(S,L):new Blob([S],{type:L}),formData:async()=>{const Y=new FormData;if(L==="multipart/form-data"&&typeof S=="string")try{const le=JSON.parse(S);le.fields&&Object.entries(le.fields).forEach(([Zt,Xt])=>{Y.append(Zt,Xt)}),le.files&&tr.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return Y},body:e!=null&&e.stream?mm(async Y=>{if(S instanceof ArrayBuffer)Y.enqueue(new Uint8Array(S));else{const le=new TextEncoder;Y.enqueue(le.encode(S))}Y.close()}):rs(typeof S=="string"?S:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};y.unsubscribe(),vm().then(()=>h(Z))});f=y.unsubscribe;const w=e!=null&&e.fos?s.fosSocket:s.socket;if(!w)throw Error(`No web socket transport available: ${e}`);w==null||w.send(d)})};exports.BASE_URL="kos:";exports.kosFetch=Em;if(process.env.KOS_MOCK_FETCH==="true"){const t=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${t}`}const Mm=m.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Tm{constructor(){l(this,"visitedModels",new Set);this.visitedModels=new Set}start(e){var r;if(e.id===void 0)throw new Error("rootModel must have an id");const s=O.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error(`Could not find rootModel with id: ${e.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(e){var r;if(this.visitedModels.has(e.modelId)){Mm.info(`model ${e.modelId} already visited`);return}const s=!!this.visitModel(e.modelData,this);this.visitedModels.add(e.modelId),!s&&((r=e.getChildren)==null||r.call(e).forEach(o=>{var n;(n=o.accept)==null||n.call(o,this)}))}}class Sl{constructor(){l(this,"middlewares",[])}use(e){this.middlewares.push(e)}async execute(e){let s=0;const r=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](e,r)};await this.middlewares[s](e,r)}}const _m=async(t,e)=>{const s=new Sl;e.forEach(o=>s.use(o));const r={data:t,result:{}};return await s.execute(r),r.result},Kt=t=>({type:t,build:(e,s)=>O.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=O.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),Sm=t=>{O.getInstance().modelManager.registerModel(t)},Om=(t,e)=>{O.getInstance().modelManager.registerCompanionModel(t,e)},zi="/kos/ui/internal/heartbeat/",Im=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:o})=>{const n=O.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${zi}${t}`,callback:()=>{a=performance.now()}}),u=r??3e3,d=window.setInterval(()=>{let w=performance.now()-a;w=w/1e3,w>u/1e3&&i.abort()},u),h=o??2e3,f=window.setInterval(()=>{bl({msg:{},options:{topic:`${zi}${t}`,destinationAddress:e}})},h),p=()=>{window.clearInterval(f),window.clearInterval(d),c()},y=()=>{p(),s&&s(),i.signal.removeEventListener("abort",y)};return i.signal.addEventListener("abort",y),{cleanUpHeartbeat:p}},Ol=(...t)=>e=>t.reduce((s,r)=>r(s),e),$m={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function Cm(t,e){let s=1;const r={...$m,...e},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await t()}catch(c){if(m.error(`Attempt ${s} failed: ${c}`),s<o)a=n*Math.pow(i,s),await new Promise(u=>setTimeout(u,a)),s++;else throw c}throw new Error("All attempts failed")}const Dm=m.createLogger({name:"kos-service-request"}),ce=t=>({isMock:!1,URL:exports.BASE_URL}),xm=(t,e,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:c,bridge:u,destinationAddress:d})=>{const h={method:"DELETE"};t&&(h.destinationAddress=t),o&&(h.tracker=o),qt(h,{ordered:i,studio:a,fos:c,bridge:u,destinationAddress:d});const f=await s(n||`${e}/${r}`,h);if(!f.ok)throw Error(`There was a problem deleting the model; returned status ${f.status}`);return await f.json()},qt=(t,{ordered:e,studio:s,fos:r,destinationAddress:o,bridge:n,timeout:i})=>(i&&(t.timeout=i),e&&(t.ordered=e),s&&(t.studio=s),r&&(t.fos=r),n&&(t.bridge=n),(o||o==="")&&(t.destinationAddress=o),t),Am=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:c,destinationAddress:u})=>{const d={method:"GET"};t&&(d.destinationAddress=t),qt(d,{timeout:c,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:u});const f=await s(r||e,d);if(!f.ok){let y;try{y=await f.json()}catch{}throw new ye(`There was a problem retrieving the model; returned status ${f.status}`,y)}return await f.json()},Rm=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:c,timeout:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),c&&(h.tracker=c),qt(h,{timeout:u,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:d});const f=r||e;Dm.debug(`resolvedUrl: ${f}`);const p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ye(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()},Pm=(t,e,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:c,timeout:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),qt(h,{timeout:u,ordered:n,studio:i,fos:a,bridge:c,destinationAddress:d});const f=r||`${e}/${o}`,p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ye(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()};class ye extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const Vi=(t,e,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:c,bridge:u,timeout:d,destinationAddress:h})=>{const f={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};t&&(f.destinationAddress=t),i&&(f.tracker=i),qt(f,{timeout:d,ordered:n,studio:a,fos:c,bridge:u,destinationAddress:h});const p=await s(o||e,f);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ye(`There was a problem sending the POST data; returned status ${p.status}`,w)}return await p.json()},Gi=(t="POST",e,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:c,fos:u,bridge:d,timeout:h,destinationAddress:f})=>{const p={method:t};o&&(p.body=JSON.stringify(o)),e&&(p.destinationAddress=e),qt(p,{timeout:h,ordered:a,studio:c,fos:u,bridge:d,destinationAddress:f});const y=await r(i||`${s}/${n}`,p);if(!y.ok){let E;try{E=await y.json()}catch{}throw new ye(`There was a problem modifying the model; returned status ${y.status}`,E)}return await y.json()},oe={build:({destinationAddress:t="",basePath:e,getAllPath:s,getOnePath:r,deleteModelPath:o,addModelPath:n,modifyModelPath:i,mock:a=!1})=>{const c=a?fetch:exports.kosFetch;return{getAll:Am(t,s||e,c),getModelById:Pm(t,r||e,c),getOne:Rm(t,r||e,c),addModel:Vi(t,n||e,c),deleteModel:xm(t,o||e,c),modifyModel:Gi("POST",t,i||e,c),putModel:Gi("PUT",t,i||e,c),postModel:Vi(t,n||e,c)}}};function km(t,e,s="get"){const r=t.serviceResponses;if(r)return r.getByPath(e,s)}function Lm(t,e,s="get"){const r=t.serviceResponses;return r?r.has(`${s.toUpperCase()}:${e}`):!1}function Fm(t,e,s="get"){const r=t.serviceResponses;r&&r.delete(`${s.toUpperCase()}:${e}`)}function Nm(t,e){const s=t.serviceResponses;s&&s.clearPath(e)}function Um(t){const e=t.serviceResponses;e&&e.clear()}const jm=lt(),Il=()=>`kos-${jm}`,Bm=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(Il()),xn=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=C(t,i=>{D.debug(`recieved response for refId ${t}: ${i}`),o(),clearTimeout(n);try{const a=i!=null&&i.body?JSON.parse(i.body):{};s(a)}catch{const a=(i==null?void 0:i.body)||{};s(a)}}),n=setTimeout(()=>{o(),r(Error(`Request with ID ${t} timed out. Cancelling.`))},e)}),Hm=async(t,e,s)=>{const r=xn(s),o=await Promise.allSettled([t(e),r]);if(o[0].status==="fulfilled"){if(o[1].status==="rejected")throw Error(o[1].reason);if(o[0].value){if(o[1].value.error)throw Error(o[1].value.error);return o[0].value.data=o[1].value,o[0].value}}else throw Error(o[0].reason)},Km=async({topic:t,msg:e,requestId:s})=>{const r=s??lt(),o=xn(r);q(t,e,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},pe=new Map;class $l{constructor(e){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=e,this._context=new M.ObservableMap({}),this._parent="",M.makeAutoObservable(this)}setParent(e){X(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=$e(this._parent))==null?void 0:e.model}get companionModels(){const e=$e(this._id);return e!=null&&e.model?Bc(e.model):[]}get(e){var s,r;if(this._context.has(e))return this._context.get(e);if(this.companionModels.length>0){const o=this.companionModels.find(n=>{var i;return!n.id||!pe.has(n.id)?!1:(i=pe.get(n.id))==null?void 0:i.context.has(e)});if(o)return(s=pe.get(o.id))==null?void 0:s.get(e)}if(this._parent)return(r=pe.get(this._parent))==null?void 0:r.get(e)}set(e,s){this._context.set(e,s)}remove(e){this._context.delete(e)}clear(){this._context.clear()}}const V={createContext:(t,e)=>{const s=pe.get(t)??new $l(t);if(e){if(!pe.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return pe.set(t,s),s},getContext:t=>pe.get(t),deleteContext:t=>{pe.delete(t)},setParentContext:(t,e)=>{var s;if(!pe.has(e))throw new Error(`Parent context ${e} does not exist`);(s=pe.get(t))==null||s.setParent(e)},rootContext:()=>pe.get("root")};V.createContext("root");const qm=t=>V.getContext(t.id),Je=m.createLogger({name:"kos-data-container"});class An{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"idx");l(this,"_maxCapacity");l(this,"_evictionStrategy");l(this,"_evictionBatchSize");l(this,"_insertionOrder",[]);l(this,"_accessTimes");l(this,"_customEvictionFilter");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1,this._optionsMap=(e==null?void 0:e.indexMap)||{};const s=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((r,o)=>(r[o]=void 0,r),{}):{};this._index=M.observable.map(s),this.idx=Ie(),this._maxCapacity=e==null?void 0:e.maxCapacity,this._evictionStrategy=(e==null?void 0:e.evictionStrategy)||"fifo",this._evictionBatchSize=(e==null?void 0:e.evictionBatchSize)??Math.max(10,Math.ceil(((e==null?void 0:e.maxCapacity)??100)*.1)),this._customEvictionFilter=e==null?void 0:e.customEvictionFilter,this._evictionStrategy==="lru"&&this._maxCapacity&&(this._accessTimes=M.observable.map(new Map)),M.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new Sn({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}get revision(){return this._revision}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s))})}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s))})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addModel(e,s){const r=this._ensureObservable(e);this._cleanupExistingDisposer(e.id),this._persistData(r),this._trackDataMetadata(r),this._enforceCapacityLimits(),this._configureDataMonitoring(r),s||this.increment()}_ensureObservable(e){return M.isObservable(e)?e:M.observable.object(e)}_cleanupExistingDisposer(e){if(!e)return;const s=this._disposerMap.get(e);s&&(s(),this._disposerMap.delete(e))}_persistData(e){this._data.set(e.id||"",e)}_trackDataMetadata(e){this._maxCapacity&&(this._insertionOrder.push(e.id||""),this._accessTimes&&this._accessTimes.set(e.id||"",Date.now()))}_enforceCapacityLimits(){this._maxCapacity&&this._data.size>this._maxCapacity&&this._evictModels()}_configureDataMonitoring(e){const s=M.observe(e,r=>{Object.values(this._optionsMap||{}).includes(r.name)&&this.increment()});this._disposerMap.set(e.id||"",s)}removeModel(e){this._data.delete(e);const s=this._insertionOrder.indexOf(e);s!==-1&&this._insertionOrder.splice(s,1),this._accessTimes&&this._accessTimes.delete(e),this.increment();const r=this._disposerMap.get(e);r&&(r(),this._disposerMap.delete(e))}updateModel(e){const s=M.observable.object(e);this._data.set(s.id||"",s),this.increment()}getModel(e){const s=this._data.get(e);return s&&this._accessTimes&&this._accessTimes.set(e,Date.now()),s}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(Je.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(e,s){if(this.index.has(e)){const r=this.index.get(e);return r.index.has(s)?r.getByKey(s):(Je.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return Je.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}_evictModels(){if(!this._maxCapacity)return;const e=this._data.size-this._maxCapacity;if(e<=0)return;const s=Math.min(this._evictionBatchSize,e);this._logDataCapacityWarning(s);const r=this._selectDataForEviction(s);this._removeEvictedData(r),this._logDataEvictionComplete(r.length)}_logDataCapacityWarning(e){Je.info(`Data container capacity exceeded (${this._data.size}/${this._maxCapacity}). Evicting ${e} items using ${this._evictionStrategy} strategy. This may indicate missing cleanup handlers or data inconsistency.`)}_selectDataForEviction(e){switch(this._evictionStrategy){case"fifo":return this._selectFifoData(e);case"lru":return this._selectLruData(e);case"custom":return this._selectCustomData(e);default:return this._selectFifoData(e)}}_selectFifoData(e){const s=[];for(let r=0;r<e&&this._insertionOrder.length>0;r++){const o=this._insertionOrder.shift();o&&this._data.has(o)&&s.push(o)}return s}_selectLruData(e){const s=[];return this._accessTimes&&Array.from(this._accessTimes.entries()).sort((o,n)=>o[1]-n[1]).slice(0,e).forEach(([o])=>{this._data.has(o)&&s.push(o)}),s}_selectCustomData(e){return this._customEvictionFilter?this._customEvictionFilter(this.data).slice(0,e).map(r=>r.id):(Je.error("Custom eviction strategy specified but no customEvictionFilter provided. Falling back to FIFO."),this._selectFifoData(e))}_removeEvictedData(e){e.forEach(s=>{var o;const r=this._data.get(s);Je.info(`Evicting data item: ${s}`,{itemId:s,itemType:r?(o=r.constructor)==null?void 0:o.name:"unknown",strategy:this._evictionStrategy}),this.removeModel(s)})}_logDataEvictionComplete(e){Je.info(`Evicted ${e} data items. Current size: ${this._data.size}/${this._maxCapacity}`)}async clear(){this._data.clear(),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id}))}}}class zm{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"childRegistration");l(this,"model");this.type=e,this.model=s,this.childRegistration=r}get factory(){return ae.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return _e(this.type)}}class Vm{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"model");l(this,"childRegistration");this.type=e,this.model=s,this.childRegistration=r}get factory(){return ae.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return _e(this.type)}}class Cl{constructor(){l(this,"_token");M.makeAutoObservable(this),C("token",e=>{this.token=e==null?void 0:e.body})}get token(){return this._token}set token(e){this._token=e}}class Dl{constructor(){l(this,"routes",[]);l(this,"openApiRoutes",[])}use(e,s,...r){this.routes.push({method:e,path:s,middlewares:r});const o=this.extractOpenApiParams(s);this.openApiRoutes.push({method:e,path:s,parameters:o})}remove(e,s){const r=this.routes.length;return this.routes=this.routes.filter(o=>!(o.method===e&&o.path===s)),this.openApiRoutes=this.openApiRoutes.filter(o=>!(o.method===e&&o.path===s)),r-this.routes.length}removeAllForPath(e){const s=this.routes.length;return this.routes=this.routes.filter(r=>r.path!==e),this.openApiRoutes=this.openApiRoutes.filter(r=>r.path!==e),s-this.routes.length}getRoutes(){return this.routes.map(e=>({method:e.method,path:e.path}))}async handle(e,s){var a;const{path:r,query:o,params:n}=this.extractPathParams(e.path),i={...e,params:n,query:o};for(const c of this.routes){const u=this.matchRoute(c.path,r);if(c.method===e.method&&u){i.params=u;let d=0;const h=async()=>{if(d<c.middlewares.length){const f=c.middlewares[d++];await f(i,s,h)}};await h();return}}(a=s.status)==null||a.call(s,404).send({error:"Route not found"})}extractOpenApiParams(e){return e.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const e={};for(const s of this.openApiRoutes)e[s.path]||(e[s.path]={}),e[s.path][s.method.toLowerCase()]={summary:s.description||`Handles ${s.method} ${s.path}`,parameters:s.parameters||[],responses:{200:{description:"Successful response"}}};return{openapi:"3.0.0",info:{title:"Kos Router API",version:"1.0.0",description:"Dynamically generated OpenAPI documentation"},paths:e}}extractPathParams(e){const[s,r]=e.split("?"),o=this.parseQueryParams(r);for(const n of this.routes){const i=this.matchRoute(n.path,s);if(i)return{path:s,query:o,params:i}}return{path:s,query:o,params:{}}}matchRoute(e,s){const r=e.split("/").filter(Boolean),o=s.split("/").filter(Boolean);if(r.length!==o.length)return null;const n={};for(let i=0;i<r.length;i++)if(r[i].startsWith(":"))n[r[i].slice(1)]=decodeURIComponent(o[i]);else if(r[i]!==o[i])return null;return n}parseQueryParams(e){return e?e.split("&").reduce((s,r)=>{const[o,n]=r.split("=").map(decodeURIComponent);return s[o]=n??"",s},{}):{}}}const xl=m.createLogger({name:"intent-service"}),Gm=t=>{cn(`/kos/intent/${t.type}`)?q(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):xl.info(`No subscribers for intent ${t.type}. Intent not sent.`)},Ym=async t=>new Promise(e=>{const{type:s,options:r}=t;if(cn(`/kos/intent/${t.type}`)){const o=lt(),{unsubscribe:n}=C(o,a=>{clearTimeout(i),n(),a&&(a.headers=a.headers||{},a.headers["kos.intent.type"]=s,a.headers.responseId=o),e([null,{body:a==null?void 0:a.body,payload:a}])}),i=setTimeout(()=>{n(),e([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);q(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else xl.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),Pe=m.createLogger({name:"app-startup-service"});async function Al(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=e;if(t.length===0)return Pe.warn("No app IDs provided to waitForAppsToStart"),!0;Pe.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const n=t.map(c=>`/kos/app/started/${c}`),i=await dn(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>al),[u,d]=await c.get("/api/kos/apps/started");return u?(Pe.error("Error fetching started apps:",u),[]):d}catch(c){Pe.error("Failed to fetch app startup status:",c)}return[]},shouldUseFetchedState:c=>t.every(u=>{const d=c.find(h=>h.appId===u);return!(!d||!d.started||o&&!d.postStarted)}),timeout:s}),a=t.filter(c=>{const u=i.find(d=>d.appId===c);return!!(!u||!u.started||o&&!u.postStarted)});if(a.length>0){const c=`Apps not started: ${a.join(", ")}`;if(Pe.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return Pe.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(Pe.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function Wm(t,e={}){return Al([t],e)}async function Qm(t,e=!1){const s={};try{const r=await exports.kosFetch("kos:///api/kos/apps/started");if(!r.ok)return t.forEach(i=>s[i]=!1),s;const o=await r.json(),n=(o==null?void 0:o.data)??[];t.forEach(i=>{const a=n.find(c=>c.appId===i);s[i]=(a==null?void 0:a.started)===!0&&(!e||(a==null?void 0:a.postStarted)===!0)})}catch(r){Pe.error("Failed to check app startup status:",r),t.forEach(o=>s[o]=!1)}return s}async function Zm(){try{const t=await exports.kosFetch("kos:///api/kos/apps/started");if(!t.ok)return[];const e=await t.json();return(e==null?void 0:e.data)??[]}catch(t){return Pe.error("Failed to fetch started apps:",t),[]}}const Bo=M.when,Rn=M.computed,X=M.runInAction,G=M.autorun,Rl=M.reaction,Pn=M.observable,kn="Not Assigned",Xm="kos.trouble.added",Jm="kos.trouble.removed";var Ee=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t))(Ee||{}),Ts=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(Ts||{});const Pl=m.createLogger({name:"config-bean-service",group:"Services"}),Ln=exports.BASE_URL,kl=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:ey,getOne:ty}=oe.build({destinationAddress:"",basePath:`${Ln}/kos/config/`}),Ll=async(t,e,s="/api/kos/config")=>(Pl.debug(`sending modify request for ConfigBean: ${t}`),ey({model:e,urlOverride:`${Ln}${s}/${t}`})),Fl=async(t,e="/api/kos/config")=>(Pl.debug(`sending get request for ConfigBean: ${t}`),await ty({urlOverride:`${Ln}${e}/details/${t}/15`})),Fn=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",Jr=t=>{try{const e=Number(t);return!isNaN(e)}catch{return!1}};function Nl(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function Ul(t,e="",s={}){for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=e?`${e}.${r}`:r;typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])?Ul(t[r],o,s):s[o]=t[r]}return s}const jl=(t,e)=>{const s=t.details[0].bean||Nl(t.details[0].scopes),r=Ul(s);M.runInAction(()=>{const o={...r};e.props.setValues(o)})},Bl=(t,e)=>{M.runInAction(()=>{t.changes.forEach(s=>{const r=s.attr;let o=s.currentValue,n=s.previousValue;typeof o=="string"&&Fn(o)&&(o=o.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof o=="string"&&Jr(o)&&(o=Number(o),n=Number(n)),e.props[r]=o,e.prevProps[r]=n})})},Hl=t=>Object.fromEntries(t.props.entries),sy=t=>e=>s=>t.build(e,s);var ry=Object.defineProperty,oy=Object.getOwnPropertyDescriptor,Kl=(t,e,s,r)=>{for(var o=r>1?void 0:r?oy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ry(e,s,o),o};function ny(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const Nn="config-bean-model",sr=m.getLogger(Nn),iy=ut("path");let vr=class{constructor(t,e){l(this,"_modifyConfigBean");l(this,"_getConfigBean");l(this,"_schema");l(this,"id");l(this,"path");l(this,"props");l(this,"prevProps");l(this,"serviceBasePath");Object.assign(this,e),this.id=t,this.path=e.path,this.serviceBasePath=e.serviceBasePath;const{modifyConfigBean:s=Ll,getConfigBean:r=Fl}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=Ie(),this.prevProps=Ie()}get values(){return this.props.values}async ready(){sr.debug(`readying config bean ${this.path}`),sr.debug(`complete readying config bean ${this.path}`)}async load(){sr.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;jl(e,this),sr.debug(this.values);const s=t==null?void 0:t.data.details[0].schema;X(()=>{s&&(this._schema=s)})}}get schemaKeys(){var t;return Object.keys(((t=this._schema)==null?void 0:t.schema)||{})}getSchemaForProperty(t){var s,r;if(this.schemaKeys.includes(t))return(s=this._schema)==null?void 0:s.schema[t];const e=ny(this.schemaKeys,t);if(e)return(r=this._schema)==null?void 0:r.schema[e]}async updateProperty(t,e){this.props[t]=e,await this.updateConfigBean()}async updateConfigBean(){const t=Hl(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){Bl(t,this)}};Kl([B({topic:`/kos/config/${iy}`,websocket:!0})],vr.prototype,"handleConfigBeanUpdated",1);vr=Kl([R(Nn)],vr);const Os=new ve({class:vr,type:Nn}),eo=({path:t,lazy:e,serviceBasePath:s})=>(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:Os.type,id:`${Os.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:x.INIT,lazy:e}},{URL:ql}=ce(),{getOne:ay,getAll:cy}=oe.build({basePath:`${ql}/api/kos/regions/info`}),zl=async()=>{try{return await ay({})}catch{return}},Vl=async()=>{try{return await cy({urlOverride:`${ql}/api/kos/regions`})}catch{return}},ly=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:zl,getRegions:Vl},Symbol.toStringTag,{value:"Module"}));var de=(t=>(t[t.family=0]="family",t[t.scale=1]="scale",t[t.offset=2]="offset",t[t.decimals=3]="decimals",t[t.alias=4]="alias",t[t.system=5]="system",t))(de||{});const Gl={s:["time",1,0,0],second:["time",1,0,0],m:["time",1/60,0,0],minute:["time",1/60,0,0],h:["time",1/3600,0,0],hour:["time",1/3600,0,0],day:["time",1/86400,0,0],week:["time",1/604800,0,0],month:["time",1/2628e3,0,0],year:["time",1/31536e3,0,0],default:["time",1/.001,0,0],ms:["time",1/.001,0,0],millisecond:["time",1/.001,0,0],microsecond:["time",1/1e-6,0,0],nanosecond:["time",1/1e-9,0,0],picosecond:["time",1/1e-12,0,0]};function uy(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return o[n.name]=i,n.alias&&(o[n.alias]=i),o},{...Gl});return{...t,...r}}function dy(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{},a=i[s]||{};i[s]=a;const c=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return a[n.name]=c,n.alias&&(a[n.alias]=c),Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,o},{time:{[s]:{...Gl}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function hy(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{};return Object.hasOwn(n,"default")&&(i[s]=n.name),o[n.measure]=i,o},{time:{[s]:"millisecond"}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}var fy=Object.defineProperty,py=Object.getOwnPropertyDescriptor,Un=(t,e,s,r)=>{for(var o=r>1?void 0:r?py(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&fy(e,s,o),o};const hr="region-info-model",es=m.createLogger({name:"region-info-model"});let Is=class{constructor(t){l(this,"id");l(this,"unitSystemMap");l(this,"measureMap");l(this,"defaultMeasureMap");l(this,"regionMap");l(this,"timeFormats");l(this,"dateFormats");l(this,"unitSystems");l(this,"regionSource");l(this,"region");l(this,"regions",[]);l(this,"timeZoneMap",{});this.id=t,this.unitSystems={},this.unitSystemMap={},this.measureMap={},this.defaultMeasureMap={},this.timeFormats={},this.regions=[],this.dateFormats={},this.timeZoneMap={},this.regionMap={}}get availableRegions(){return this.regions}get defaultUnitSystem(){return String(this.regionSource.props.unitSystemId).toLowerCase()||""}get unitSystemId(){return this.defaultUnitSystem}get timeFormatId(){const t=this.regionSource.props.timeFormatId;if(!t)return"";const e=String(t),s=this.timeFormats[e];return s?String(s.id):""}get selectedTimeFormat(){const t=this.timeFormatId;return t?String(this.timeFormats[t].format):"HH:mm:ss"}get is12HourTimeFormat(){const t=this.timeFormatId;return t?this.timeFormats[t].ampm:!0}get dateFormatId(){const t=this.regionSource.props.dateFormatId;if(!t)return"";const e=String(t);return e?this.dateFormats[e].id:""}get selectedDateFormat(){const t=this.dateFormatId;return t?this.dateFormats[t].format:""}get selectedDateOrder(){const t=this.dateFormatId;return t?this.dateFormats[t].order.toLowerCase():"dmy"}get selectedCountry(){return this.regionSource.props.country||"en"}get selectedTimeZone(){return this.regionSource.props.timeZone||""}get timeZones(){return this.regionId?this.timeZoneMap[this.regionId]||[]:[]}get allTimeZones(){return Intl.supportedValuesOf("timeZone")}get regionId(){return this.region.props.regionId||""}get selectedRegion(){return this.regionMap[this.regionId]}get selectedUnitSystem(){return String(this.regionSource.props.unitSystemId)||""}get timeFormatOptions(){return Object.keys(this.timeFormats).map(t=>({id:t,format:this.timeFormats[t].format,ampm:this.timeFormats[t].ampm}))}get dateFormatOptions(){return Object.keys(this.dateFormats).map(t=>({id:t,format:this.dateFormats[t].format,order:this.dateFormats[t].order}))}get unitSystemOptions(){return Object.keys(this.unitSystems).map(t=>({id:t,name:t}))}setSelectedTimeFormat(t){if(!this.timeFormatOptions.find(e=>e.id===t))throw Error(`Invalid time format id. Must be one of ${this.timeFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("timeFormatId",t)}setSelectedDateFormat(t){if(!this.dateFormatOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.dateFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("dateFormatId",t)}setSelectedUnitSystem(t){if(!this.unitSystemOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.unitSystemOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("unitSystemId",t)}getUnitSystem(t){if(!t)return this.defaultUnitSystem;const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[de.system]}getUnitMeasure(t){const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[de.family]}getDefaultUnitDecimalPlaces(t,e,s){if(!t||!e)throw Error("Measure and unit system are required");const r=s==="drt"?"second":s,o=this.measureMap[t];if(!o)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const n=o[e.toLowerCase()];if(!n)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(o).join(", ")}`);const i=n[r||"default"];if(!i)throw Error(`No unit "${r||"default"}" found for measure: ${t} and unit system: ${e}. Unit should come from list of units: ${Object.keys(n).join(", ")}`);return i[de.decimals]}getDefaultUnitForMeasure(t,e){if(!t||!e)throw Error("Measure and unit system are required");const s=this.defaultMeasureMap[t];if(!s)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const r=s[e.toLowerCase()];if(!r)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(s).join(", ")}`);return r}convertByUnit(t,e,s){if(e[de.family]!==s[de.family])throw new Error(`Cannot convert between units of different families: ${e[de.family]} and ${s[de.family]}`);const r=e[de.offset],o=e[de.scale],n=s[de.scale],i=s[de.offset],a=s[de.decimals];return((t-r)/(o/n)+i).toFixed(a)}convertByUnitName(t,e,s){const r=this.unitSystemMap[e],o=this.unitSystemMap[s];if(!r||!o)throw new Error(`No unit found with name: ${e} or ${s}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return this.convertByUnit(t,r,o)}convert(t,e,s){var a,c;if(e.unit&&s.unit)return this.convertByUnitName(t,e.unit,s.unit);const r=e.unit||"",o=s.unit||"";let n=this.unitSystemMap[r],i=this.unitSystemMap[o];if(!i&&s.measure&&s.system){const u=this.measureMap[s.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(a=u[s.system])==null?void 0:a.default,i||es.info("Could not find default unit for measure",s.measure)}if(!n&&e.measure&&e.system){const u=this.measureMap[e.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(c=u[e.system])==null?void 0:c.default,n||es.info("Could not find default unit for measure",e.measure)}return!n||!i?(es.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,n,i)}async init(){es.debug("initializing region info")}async load(){es.debug("loading region info");const t=await Vl();t&&(this.regions=t.data.map(s=>s.id),this.timeZoneMap=t.data.reduce((s,r)=>({...s,[r.id]:r.timeZones}),this.timeZoneMap),this.regionMap=t.data.reduce((s,r)=>({...s,[r.id]:r}),{}));const e=await zl();e&&(this.unitSystems=e.data.unitSystems.reduce((s,r)=>{const o={id:r.id,name:r.id};return s[r.id]=o,s},this.unitSystems),this.unitSystemMap=e.data.unitSystems.reduce(uy,{}),this.measureMap=e.data.unitSystems.reduce(dy,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(hy,{}),this.timeFormats=e.data.timeFormats.reduce((s,r)=>({...s,[r.id]:r}),{}),this.dateFormats=e.data.dateFormats.reduce((s,r)=>({...s,[r.id]:r}),{}))}async ready(){var t,e;await((e=(t=this.regionSource).ready)==null?void 0:e.call(t))}};Un([eo({path:"kos:service:region:settings"})],Is.prototype,"regionSource",2);Un([eo({path:"kos:service:region"})],Is.prototype,"region",2);Is=Un([R(hr)],Is);const re={registration:{[hr]:{class:Is,singleton:!0}},type:hr,factory:ae.Singleton.create(hr)},wr=({source:t,defaultSystem:e="si",defaultMeasure:s})=>{let r={system:e,measure:s};return typeof t=="string"?r={...r,unit:t}:r={...r,...t},r},jn=(t,e,s)=>{const{model:r}=$e(re.type);if(!r)throw new Error("RegionInfo model not found");if(!br(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=wr({source:e}),i=wr({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(t,n,i)};function Yi(t,e,s){const r=e.toLowerCase().replace(/_/g,"-").replace(/s$/,""),o=new Intl.NumberFormat().resolvedOptions().locale??"en-US";try{const n=(s==null?void 0:s.mode)||"long",i=(s==null?void 0:s.maxDecimals)??2,a=(s==null?void 0:s.minDecimals)??0;return new Intl.NumberFormat(o,{style:"unit",unit:r,unitDisplay:n,minimumFractionDigits:a,maximumFractionDigits:i}).format(t)}catch{return e}}const gy=(t,e,s,r)=>{const o=jn(t,e,s),n=wr({source:e}),{model:i}=$e(re.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},u=wr({source:s||c,defaultMeasure:i.getUnitMeasure(n.unit||"")}),d=i.getDefaultUnitForMeasure(a,u.system),h=i.getDefaultUnitDecimalPlaces(a,u.system),f={...r,minDecimals:(r==null?void 0:r.minDecimals)??h,maxDecimals:(r==null?void 0:r.maxDecimals)??h};return{value:o,unit:d||n.unit||"",display:Yi(o,d||n.unit||"",{...f,mode:"long"}),shortDisplay:Yi(o,d||n.unit||"",{...f,mode:"short"})}};function Wi({start:t,end:e,count:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<2)throw new Error("Count should be at least 2 for distribution.");if(t>=e)throw new Error("Start should be less than end.");const o=(e-t)/(s-1),n=[];for(let i=0;i<s;i++){const a=Math.round(t+i*o);n.push(a.toFixed(r))}return n}function Qi({start:t,end:e,interval:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<=0)throw new Error("Interval should be a positive number.");if(t>=e)throw new Error("Start should be less than end.");const o=[];let n=t;for(;n<=e;)o.push(n.toFixed(r)),n+=s;return o[o.length-1]!==e.toString()&&o.push(e.toString()),o}const bt=(t,e)=>s=>!t||!e?s:Jr(s)?jn(Number(s),t,e):s,my=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return Wi(t.options).map(bt(s,r));if(t.options.type==="rangeInterval")return Qi(t.options).map(bt(s,r));if(t.options.type==="list"){const{list:o}=t.options;return o.map(bt(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return Wi(t.options.unitSystems[e]).map(bt(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return Qi(t.options.unitSystems[e]).map(bt(s,r));if(t.options.type==="unitSystemList"&&e){const{list:o}=t.options.unitSystems[e];return o.map(bt(s,r))}}return[]},yy=(t,e)=>{if(!((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options)))return t.options.type==="unitSystemRangeCount"&&e?{type:"rangeCount",...t.options.unitSystems[e]}:t.options.type==="unitSystemRangeInterval"&&e?{type:"rangeInterval",...t.options.unitSystems[e]}:t.options.type==="unitSystemList"&&e?{type:"list",...t.options.unitSystems[e]}:t.options.type==="unitSystemKeypad"&&e?{type:"keypad",...t.options.unitSystems[e]}:t.options};var by=Object.defineProperty,vy=Object.getOwnPropertyDescriptor,Bn=(t,e,s,r)=>{for(var o=r>1?void 0:r?vy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&by(e,s,o),o};function wy(t){return(t==null?void 0:t.type)==="enum"}function Ey(t){switch(t){case"s":return"second";case"ms":return"millisecond";case"min":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"m":return"month";case"y":return"year";case"ml":return"milliliter";default:return t}}function My(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return Ke.format(r,e)}const fr="config-bean-prop-model",vt=m.createLogger({name:"config-bean-prop-model"}),Ty=ut("path"),_y=ut("serviceBasePath");let $s=class{constructor(t,e){l(this,"id");l(this,"path");l(this,"attribute");l(this,"converter");l(this,"formatter");l(this,"optionsExpander");l(this,"serviceBasePath");l(this,"regionInfo");l(this,"bean");this.id=t,this.path=e.path,this.attribute=e.attribute,this.converter=e.converter,this.formatter=e.formatter,this.serviceBasePath=e.serviceBasePath,this.optionsExpander=e.optionsExpander}getDefaultUnitDecimalPlaces(t,e,s){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return kl(this.displayOptions)?this.displayOptions.decimals:this.regionInfo.getDefaultUnitDecimalPlaces(t,e,s)}getDefaultUnitForMeasure(t,e){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return this.regionInfo.getDefaultUnitForMeasure(t,e)}get schemaType(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.type?t.type:"String"}get schemaFormat(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.format?Ey(t.format):""}get options(){var i;const t=this.regionInfo.defaultUnitSystem,e=this.getConverter(),s=((i=e==null?void 0:e.to)==null?void 0:i.system)??t,r=this.bean.getSchemaForProperty(this.attribute),o=wy(r)?r.values:my(r,s,e==null?void 0:e.from,e==null?void 0:e.to),n=o.length>0?o.map(a=>({label:a,value:a})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,o):this.optionsExpander:n}convertUnit(t,e,s){const r=(t==null?void 0:t.measure)||s,o=(t==null?void 0:t.system)||e,n=t==null?void 0:t.unit;return{measure:r,system:o,unit:n}}getConverterUnits(){const t=this.regionInfo.defaultUnitSystem,e=this.getConverter();if(!e)throw Error("No converter defined");const s=e.measure,r=this.convertUnit(e.from,"si",s),o=this.convertUnit(e.to,t,s);return{backend:r,display:o}}set value(t){this.updateProperty(t)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var o,n;const t=this.value,e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=(s==null?void 0:s.measure)||((o=s==null?void 0:s.to)==null?void 0:o.measure);if(!isNaN(t)&&s&&r){const i=this.getDefaultUnitDecimalPlaces(r,e,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const c=this.getFormatterOptions(s);if(c){let u=String(t);return u=c.formatToParts(Number(t))[0].value,Number(u)}}catch(c){vt.info(`error formatting value ${t}`,c)}return Number(t).toFixed(i)}return t}get previousValue(){return this.getValue(!1)}getValue(t){const e=this.bean[t?"props":"prevProps"][this.attribute];if(typeof e=="boolean")return e;if(this.getConverter()&&!isNaN(e)){const{backend:r,display:o}=this.getConverterUnits();return this.regionInfo.convert(Number(e),r,o)}return e||""}async activate(){vt.debug(`activating config bean ${this.id}`)}get displayValue(){const t=this.value;if(typeof t=="boolean")return String(t);if(this.schemaFormat==="drt"){const s=this.regionInfo.is12HourTimeFormat?"h:mm:ss a":"HH:mm:ss";return My(t,s)}if(!isNaN(t))try{const e=this.getConverter(),s=this.getFormatterOptions(e);if(s){let r=String(t);return r=s.format(Number(t)),r}}catch(e){vt.error(`error formatting value ${t}`,e)}return String(t)}get unit(){const t=this.getConverter();if(!isNaN(this.value)){const e=this.getFormatterOptions(t);if(e){const r=e.formatToParts(Number(this.value)).find(o=>o.type==="unit");return(r==null?void 0:r.value)??this.getDefaultUnit(t)}}return this.getDefaultUnit(t)}get displayOptions(){var o;const t=this.bean.getSchemaForProperty(this.attribute),e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=((o=s==null?void 0:s.to)==null?void 0:o.system)??e;return yy(t,r)}getMeasureFromFormat(){const t=this.schemaFormat;return t?this.regionInfo.getUnitMeasure(t):""}getConverterFromFormat(){const t=this.getMeasureFromFormat();if(t){const e=this.regionInfo.selectedUnitSystem;return{unit:this.schemaFormat||this.regionInfo.getDefaultUnitForMeasure(t,e),measure:t}}return{}}getDefaultUnit(t){var r,o;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure;return s?((r=t==null?void 0:t.to)==null?void 0:r.unit)||this.getDefaultUnitForMeasure(s,((o=t==null?void 0:t.to)==null?void 0:o.system)||e):this.getConverterFromFormat().unit}getFormatterOptions(t){var n,i,a;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure,r=new Intl.NumberFormat().resolvedOptions().locale;let o=null;if(s||this.formatter){const c=s?{style:"unit",unit:this.getDefaultUnit(t)}:null,u=this.formatter||c;if(u){let d=typeof u=="function"?u(((n=t==null?void 0:t.to)==null?void 0:n.system)||e):u;s&&(d={unit:this.getDefaultUnit(t),...d},d.style==="unit"&&(d.maximumFractionDigits=d.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=t==null?void 0:t.to)==null?void 0:i.system)||e,(a=t==null?void 0:t.to)==null?void 0:a.unit)));try{o=new Intl.NumberFormat(r,{...d})}catch(h){vt.error(`error creating formatter ${d}. Returning the raw value`,h)}}else vt.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return o}getConverter(){var r,o,n,i,a,c,u,d,h,f,p;const{unit:t,measure:e}=this.getConverterFromFormat(),s=t==="drt"?"second":t;if(this.converter){const y=(r=this.converter)==null?void 0:r.measure,w=(n=(o=this.converter)==null?void 0:o.to)==null?void 0:n.measure,E=(a=(i=this.converter)==null?void 0:i.from)==null?void 0:a.measure,_=y||w||E||e,L=((u=(c=this.converter)==null?void 0:c.to)==null?void 0:u.unit)||this.regionInfo.getDefaultUnitForMeasure(_,((h=(d=this.converter)==null?void 0:d.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),U=((p=(f=this.converter)==null?void 0:f.to)==null?void 0:p.system)??this.regionInfo.getUnitSystem(L),I=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:I,...this.converter.from},to:{...this.converter.to,unit:L,system:U},measure:_}}if(s&&e){const y=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),w=this.regionInfo.getUnitSystem(s),E=this.regionInfo.getUnitSystem(y);return{measure:e,to:{unit:w===E?s:y}}}}async updateProperty(t){vt.debug(`updating property ${this.attribute} with value ${t}`);let e=t;if(this.getConverter()&&!isNaN(e)){const{backend:o,display:n}=this.getConverterUnits();e=this.regionInfo.convert(Number(e),n,o)}const r=Array.isArray(e)?JSON.stringify(e):String(e);await this.bean.updateProperty(this.attribute,r)}};Bn([Ht({modelType:re.type})],$s.prototype,"regionInfo",2);Bn([eo({path:Ty,serviceBasePath:_y})],$s.prototype,"bean",2);$s=Bn([R(fr)],$s);const ht={registration:{[fr]:{class:$s,singleton:!1}},type:fr,factory:ae.Factory.create(fr)};function Sy(t){const{path:e,attribute:s,converter:r,formatter:o,lazy:n,optionsExpander:i,serviceBasePath:a}=t,c=r;return c&&(typeof c!="function"&&typeof c.from=="string"&&(c.from={unit:c.from}),typeof c!="function"&&typeof c.to=="string"&&(c.to={unit:c.to})),(u,d)=>{u[F]=u[F]||{},u[F][d]={modelType:ht.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:x.INIT,lazy:n}}}const Yl="future-model",zt=Kt(Yl),to=m.createLogger({name:"future-service",group:"Services"}),{isMock:Oy,URL:qs}=ce();var Ge=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(Ge||{});const{getAll:Iy,modifyModel:$y,addModel:Cy,deleteModel:Dy,postModel:xy}=oe.build({destinationAddress:"",basePath:`${qs}/api/future`,mock:Oy}),Ay=async()=>await Iy({}),Wl=async(t,e="/api/kos/future")=>(to.info(`sending delete request for Future: ${t}`),await Dy({id:t,urlOverride:`${qs}${e}/${t}`})),Ql=async(t,e="/api/kos/future")=>(to.info("sending add request for Future"),await Cy({model:t,urlOverride:`${qs}${e}`})),Ry=async(t,e,s="/api/kos/future")=>(to.info(`sending modify request for Future: ${t}`),$y({model:e,id:t,urlOverride:`${qs}${s}/${t}`})),Zl=async(t,e="/api/kos/future")=>(to.info(`sending cancel request for Future: ${t}`),xy({urlOverride:`${qs}${e}/${t}/cancel`,ordered:!0,model:{}})),Hn=t=>({id:String(t.id),progress:t.progress,remainingTimeMs:t.remainingTimeMs,endState:t.endState,reason:t.reason,clientData:t.clientData,reasonData:t.reasonData,note:t.note,tracker:t.tracker}),Kn=(t,e)=>{m.debug(`future dto ${t.id} end state ${t.endState}`),m.debug(`future model ${e.id} end state ${e.endState}`),e.endState?m.debug(`future model ${e.id} is already complete`):(m.debug(`updating future model ${e.id}`),M.runInAction(()=>{const s=Hn(t);X(()=>{Object.keys(s).forEach(r=>{r==="id"?(e.futureId=s.id,s.tracker||(e.id=s.id)):r==="tracker"?e.id=s.tracker:e[r]=s[r]})})}))},Xl=t=>e=>s=>t.build(String(e),s),qn=t=>e=>Ol(Hn,Xl(t)(e.tracker||e.id))(e);var Py=Object.defineProperty,ky=Object.getOwnPropertyDescriptor,Jl=(t,e,s,r)=>{for(var o=r>1?void 0:r?ky(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Py(e,s,o),o};const Oo=m.getLogger(zt.type);let Er=class{constructor(t,e,s){l(this,"logger");l(this,"_cancelFuture");l(this,"futureId");Object.assign(this,e),this.logger=s.logger,this.id=t,this.futureId=e.id,this.namespace=e.namespace||"kos",this._cancelFuture=Zl,Bo(()=>this.status===Ge.Success||this.status===Ge.Fail,()=>{Oo.info(`Future ${this.id} has completed with status ${this.status}`),Oe(this)})}async load(){Oo.debug(`loading Future ${this.id}`)}unload(){Oo.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await Bo(()=>this.futureId!==kn),await this._cancelFuture(this.futureId,t)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,c;const t=this.remainingTimeMs||-1;if(t<0)return"";const e={year:1e3*60*60*24*365,month:1e3*60*60*24*30,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60,second:1e3};let s="second",r=0;for(const[u,d]of Object.entries(e))if(Math.abs(t)>=d){s=u,r=Math.round(t/d);break}const n=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(r,s);return n.length===3?`${((a=n[1])==null?void 0:a.value)??0} ${((c=n[2])==null?void 0:c.value)??""}`:"0 seconds"}handleFutureUpdated(t){this.logger.debug(`Future ${this.id} updated. future: ${t.id} endState: ${t.endState} progress: ${t.progress} remainingTimeMs: ${t.remainingTimeMs}`),Kn(t,this)}};Jl([B({topic:`kos.future/${gr}`})],Er.prototype,"handleFutureUpdated",1);Er=Jl([R(zt.type)],Er);const eu=Er,tu=Be();var Ly=Object.defineProperty,Fy=Object.getOwnPropertyDescriptor,su=(t,e,s,r)=>{for(var o=r>1?void 0:r?Fy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ly(e,s,o),o};const ru="browser-router-model",Ny="kos.http.request",Uy="kos.http.response";let Mr=class{constructor(t,e,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=t,this.logger=s.logger,this.router=new Dl}get id(){return this._id}async handleRequest(t,e){const s=e.headers["src-addr"],r=e.headers["dst-addr"],o=e.headers.url,n=e.headers.method,i=e.headers["request-id"],a={id:i,method:n,path:o,body:t};let c=200;const u={send:d=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(d),vl({msg:d,options:{responseId:i,destinationAddress:s,type:Uy,sourceAddress:r,status:c}})},status:function(d){return c=d,this}};if(a.path==="/openapi.json"){u.send(this.router.generateOpenApiSpec());return}await this.router.handle(a,u)}use(t,e,...s){this.router.use(t,e,...s)}remove(t,e){return this.router.remove(t,e)}removeAllForPath(t){return this.router.removeAllForPath(t)}getRoutes(){return this.router.getRoutes()}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};su([B({topic:Ny})],Mr.prototype,"handleRequest",1);Mr=su([R(ru)],Mr);const zn=new Se({class:Mr,type:ru}),ou="future-container-model",Ye=Kt(ou),nu=t=>qn(zt)(t),jy=t=>{const e=nu(t);return Ye.build(Ye.type,{}).addFutureModel(e),e},By=t=>Ye.build(Ye.type,{}).getFuture(String(t)),at={buildFutureModel:nu,initiateFuture:jy,getFuture:By};var Hy=Object.defineProperty,Ky=Object.getOwnPropertyDescriptor,Vn=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ky(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Hy(e,s,o),o};const rr=m.getLogger(Ye.type);let Cs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_deleteFuture");l(this,"_addFuture");l(this,"_futures");l(this,"createModel");l(this,"deleteModel");const{deleteFuture:r=Wl,addFuture:o=Ql}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=t,this._futures=new xe,this.createModel=this.createFuture,this.deleteModel=this.removeFuture}get futures(){return this._futures.data}get models(){return this.futures}getFuture(t){return this._futures.getModel(t)}addFutureModel(t){this._futures.addModel(t)}removeFutureModel(t){this._futures.removeModel(t)}async removeFuture(t){try{await this._deleteFuture(t)}catch(e){rr.error("error deleting a Future"),rr.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=qn(zt)(s);return this.addFutureModel(r),r}}catch(e){throw rr.error("error creating a Future"),rr.error(e),e}}handleFutureUpdated(t,e){const s=at.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),q(r,e.body,e.headers)}};Vn([De],Cs.prototype,"_futures",2);Vn([B({topic:"kos.future"})],Cs.prototype,"handleFutureUpdated",1);Cs=Vn([R(Ye.type)],Cs);const iu=Cs,{URL:zs}=ce(),{getOne:qy,postModel:zy,deleteModel:au}=oe.build({basePath:`${zs}/api/keyVal`}),Ho=m.createLogger({name:"key-value-service",group:"Services"}),cu=async(t,e)=>{await au({urlOverride:`${zs}/api/keyVal/${t}/${e}`,id:e})},lu=async(t,e,s)=>{const r=await zy({urlOverride:`${zs}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw Ho.error("Failed to update key-value data",r),new Error(`Failed to update key-value data for namespace ${t}`);return r.data},uu=async(t="studio")=>{Ho.debug(`Retrieving all key-value data for namespace: ${t}`);const e=await qy({urlOverride:`${zs}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw Ho.error("Failed to retrieve key-value data",e),new Error(`Failed to retrieve key-value data for namespace ${t}`);return e.data},Vy=async t=>{await au({urlOverride:`${zs}/api/keyVal/${t}`,id:""})},Gy=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:cu,deleteKeyValueNamespace:Vy,getKeyValue:uu,updateKeyValue:lu},Symbol.toStringTag,{value:"Module"}));var Yy=Object.defineProperty,Wy=Object.getOwnPropertyDescriptor,Gn=(t,e,s,r)=>{for(var o=r>1?void 0:r?Wy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Yy(e,s,o),o};const du="key-value-model";let Ds=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"namespace");l(this,"data");this.id=t,this.logger=s.logger,this.data=Ie(),this.namespace=e.namespace||"studio"}async init(){this.logger.debug(`initializing studio-state ${this.id}`)}async updateState(t,e){this.logger.debug(`updating studio-state ${t} with value ${e}`),e!==void 0?(await lu(this.namespace,t,e),this.data[t]=e):(await cu(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await uu(this.namespace);this.data.setValues(t)}handleStateUpdate(t){t.namespace===this.namespace&&(this.data[t.key]=t.value)}handleStateDelete(t){t.namespace===this.namespace&&(this.data[t.key]=void 0)}};Gn([B({topic:"/keyVal/set"})],Ds.prototype,"handleStateUpdate",1);Gn([B({topic:"/keyVal/remove"})],Ds.prototype,"handleStateDelete",1);Ds=Gn([R(du)],Ds);const Yn=new ve({class:Ds,type:du});var ge="INUMBER",Vt="IOP1",Gt="IOP2",Yt="IOP3",Le="IVAR",ct="IVARNAME",Dt="IFUNCALL",so="IFUNDEF",ie="IEXPR",Wn="IEXPREVAL",ft="IMEMBER",ro="IENDSTATEMENT",xt="IARRAY";function P(t,e){this.type=t,this.value=e??0}P.prototype.toString=function(){switch(this.type){case ge:case Vt:case Gt:case Yt:case Le:case ct:case ro:return this.value;case Dt:return"CALL "+this.value;case so:return"DEF "+this.value;case xt:return"ARRAY "+this.value;case ft:return"."+this.value;default:return"Invalid Instruction"}};function oo(t){return new P(Vt,t)}function He(t){return new P(Gt,t)}function hu(t){return new P(Yt,t)}function Ko(t,e,s,r,o){for(var n=[],i=[],a,c,u,d,h=0;h<t.length;h++){var f=t[h],p=f.type;if(p===ge||p===ct)Array.isArray(f.value)?n.push.apply(n,Ko(f.value.map(function(y){return new P(ge,y)}).concat(new P(xt,f.value.length)),e,s,r,o)):n.push(f);else if(p===Le&&o.hasOwnProperty(f.value))f=new P(ge,o[f.value]),n.push(f);else if(p===Gt&&n.length>1)c=n.pop(),a=n.pop(),d=s[f.value],f=new P(ge,d(a.value,c.value)),n.push(f);else if(p===Yt&&n.length>2)u=n.pop(),c=n.pop(),a=n.pop(),f.value==="?"?n.push(a.value?c.value:u.value):(d=r[f.value],f=new P(ge,d(a.value,c.value,u.value)),n.push(f));else if(p===Vt&&n.length>0)a=n.pop(),d=e[f.value],f=new P(ge,d(a.value)),n.push(f);else if(p===ie){for(;n.length>0;)i.push(n.shift());i.push(new P(ie,Ko(f.value,e,s,r,o)))}else if(p===ft&&n.length>0)a=n.pop(),n.push(new P(ge,a.value[f.value]));else{for(;n.length>0;)i.push(n.shift());i.push(f)}}for(;n.length>0;)i.push(n.shift());return i}function fu(t,e,s){for(var r=[],o=0;o<t.length;o++){var n=t[o],i=n.type;if(i===Le&&n.value===e)for(var a=0;a<s.tokens.length;a++){var c=s.tokens[a],u;c.type===Vt?u=oo(c.value):c.type===Gt?u=He(c.value):c.type===Yt?u=hu(c.value):u=new P(c.type,c.value),r.push(u)}else i===ie?r.push(new P(ie,fu(n.value,e,s))):r.push(n)}return r}function st(t,e,s){var r=[],o,n,i,a,c,u;if(Qn(t))return Re(t,s);for(var d=t.length,h=0;h<d;h++){var f=t[h],p=f.type;if(p===ge||p===ct)r.push(f.value);else if(p===Gt)n=r.pop(),o=r.pop(),f.value==="and"?r.push(o?!!st(n,e,s):!1):f.value==="or"?r.push(o?!0:!!st(n,e,s)):f.value==="="?(a=e.binaryOps[f.value],r.push(a(o,st(n,e,s),s))):(a=e.binaryOps[f.value],r.push(a(Re(o,s),Re(n,s))));else if(p===Yt)i=r.pop(),n=r.pop(),o=r.pop(),f.value==="?"?r.push(st(o?n:i,e,s)):(a=e.ternaryOps[f.value],r.push(a(Re(o,s),Re(n,s),Re(i,s))));else if(p===Le)if(f.value in e.functions)r.push(e.functions[f.value]);else if(f.value in e.unaryOps&&e.parser.isOperatorEnabled(f.value))r.push(e.unaryOps[f.value]);else{var y=s[f.value];if(y!==void 0)r.push(y);else throw new Error("undefined variable: "+f.value)}else if(p===Vt)o=r.pop(),a=e.unaryOps[f.value],r.push(a(Re(o,s)));else if(p===Dt){for(u=f.value,c=[];u-- >0;)c.unshift(Re(r.pop(),s));if(a=r.pop(),a.apply&&a.call)r.push(a.apply(void 0,c));else throw new Error(a+" is not a function")}else if(p===so)r.push(function(){for(var w=r.pop(),E=[],_=f.value;_-- >0;)E.unshift(r.pop());var L=r.pop(),U=function(){for(var I=Object.assign({},s),S=0,Z=E.length;S<Z;S++)I[E[S]]=arguments[S];return st(w,e,I)};return Object.defineProperty(U,"name",{value:L,writable:!1}),s[L]=U,U}());else if(p===ie)r.push(Qy(f,e));else if(p===Wn)r.push(f);else if(p===ft)o=r.pop(),r.push(o[f.value]);else if(p===ro)r.pop();else if(p===xt){for(u=f.value,c=[];u-- >0;)c.unshift(r.pop());r.push(c)}else throw new Error("invalid Expression")}if(r.length>1)throw new Error("invalid Expression (parity)");return r[0]===0?0:Re(r[0],s)}function Qy(t,e,s){return Qn(t)?t:{type:Wn,value:function(r){return st(t.value,e,r)}}}function Qn(t){return t&&t.type===Wn}function Re(t,e){return Qn(t)?t.value(e):t}function Zn(t,e){for(var s=[],r,o,n,i,a,c,u=0;u<t.length;u++){var d=t[u],h=d.type;if(h===ge)typeof d.value=="number"&&d.value<0?s.push("("+d.value+")"):Array.isArray(d.value)?s.push("["+d.value.map(Zi).join(", ")+"]"):s.push(Zi(d.value));else if(h===Gt)o=s.pop(),r=s.pop(),i=d.value,e?i==="^"?s.push("Math.pow("+r+", "+o+")"):i==="and"?s.push("(!!"+r+" && !!"+o+")"):i==="or"?s.push("(!!"+r+" || !!"+o+")"):i==="||"?s.push("(function(a,b){ return Array.isArray(a) && Array.isArray(b) ? a.concat(b) : String(a) + String(b); }(("+r+"),("+o+")))"):i==="=="?s.push("("+r+" === "+o+")"):i==="!="?s.push("("+r+" !== "+o+")"):i==="["?s.push(r+"[("+o+") | 0]"):s.push("("+r+" "+i+" "+o+")"):i==="["?s.push(r+"["+o+"]"):s.push("("+r+" "+i+" "+o+")");else if(h===Yt)if(n=s.pop(),o=s.pop(),r=s.pop(),i=d.value,i==="?")s.push("("+r+" ? "+o+" : "+n+")");else throw new Error("invalid Expression");else if(h===Le||h===ct)s.push(d.value);else if(h===Vt)r=s.pop(),i=d.value,i==="-"||i==="+"?s.push("("+i+r+")"):e?i==="not"?s.push("(!"+r+")"):i==="!"?s.push("fac("+r+")"):s.push(i+"("+r+")"):i==="!"?s.push("("+r+"!)"):s.push("("+i+" "+r+")");else if(h===Dt){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());i=s.pop(),s.push(i+"("+a.join(", ")+")")}else if(h===so){for(o=s.pop(),c=d.value,a=[];c-- >0;)a.unshift(s.pop());r=s.pop(),e?s.push("("+r+" = function("+a.join(", ")+") { return "+o+" })"):s.push("("+r+"("+a.join(", ")+") = "+o+")")}else if(h===ft)r=s.pop(),s.push(r+"."+d.value);else if(h===xt){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());s.push("["+a.join(", ")+"]")}else if(h===ie)s.push("("+Zn(d.value,e)+")");else if(h!==ro)throw new Error("invalid Expression")}return s.length>1&&(e?s=[s.join(",")]:s=[s.join(";")]),String(s[0])}function Zi(t){return typeof t=="string"?JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"):t}function _t(t,e){for(var s=0;s<t.length;s++)if(t[s]===e)return!0;return!1}function Xn(t,e,s){s=s||{};for(var r=!!s.withMembers,o=null,n=0;n<t.length;n++){var i=t[n];i.type===Le||i.type===ct?!r&&!_t(e,i.value)?e.push(i.value):(o!==null&&(_t(e,o)||e.push(o)),o=i.value):i.type===ft&&r&&o!==null?o+="."+i.value:i.type===ie?Xn(i.value,e,s):o!==null&&(_t(e,o)||e.push(o),o=null)}o!==null&&!_t(e,o)&&e.push(o)}function Me(t,e){this.tokens=t,this.parser=e,this.unaryOps=e.unaryOps,this.binaryOps=e.binaryOps,this.ternaryOps=e.ternaryOps,this.functions=e.functions}Me.prototype.simplify=function(t){return t=t||{},new Me(Ko(this.tokens,this.unaryOps,this.binaryOps,this.ternaryOps,t),this.parser)};Me.prototype.substitute=function(t,e){return e instanceof Me||(e=this.parser.parse(String(e))),new Me(fu(this.tokens,t,e),this.parser)};Me.prototype.evaluate=function(t){return t=t||{},st(this.tokens,this,t)};Me.prototype.toString=function(){return Zn(this.tokens,!1)};Me.prototype.symbols=function(t){t=t||{};var e=[];return Xn(this.tokens,e,t),e};Me.prototype.variables=function(t){t=t||{};var e=[];Xn(this.tokens,e,t);var s=this.functions;return e.filter(function(r){return!(r in s)})};Me.prototype.toJSFunction=function(t,e){var s=this,r=new Function(t,"with(this.functions) with (this.ternaryOps) with (this.binaryOps) with (this.unaryOps) { return "+Zn(this.simplify(e).tokens,!0)+"; }");return function(){return r.apply(s,arguments)}};var xs="TEOF",j="TOP",no="TNUMBER",pu="TSTRING",Fe="TPAREN",At="TBRACKET",io="TCOMMA",Jn="TNAME",ei="TSEMICOLON";function gu(t,e,s){this.type=t,this.value=e,this.index=s}gu.prototype.toString=function(){return this.type+": "+this.value};function z(t,e){this.pos=0,this.current=null,this.unaryOps=t.unaryOps,this.binaryOps=t.binaryOps,this.ternaryOps=t.ternaryOps,this.consts=t.consts,this.expression=e,this.savedPosition=0,this.savedCurrent=null,this.options=t.options,this.parser=t}z.prototype.newToken=function(t,e,s){return new gu(t,e,s??this.pos)};z.prototype.save=function(){this.savedPosition=this.pos,this.savedCurrent=this.current};z.prototype.restore=function(){this.pos=this.savedPosition,this.current=this.savedCurrent};z.prototype.next=function(){if(this.pos>=this.expression.length)return this.newToken(xs,"EOF");if(this.isWhitespace()||this.isComment())return this.next();if(this.isRadixInteger()||this.isNumber()||this.isOperator()||this.isString()||this.isParen()||this.isBracket()||this.isComma()||this.isSemicolon()||this.isNamedOp()||this.isConst()||this.isName())return this.current;this.parseError('Unknown character "'+this.expression.charAt(this.pos)+'"')};z.prototype.isString=function(){var t=!1,e=this.pos,s=this.expression.charAt(e);if(s==="'"||s==='"')for(var r=this.expression.indexOf(s,e+1);r>=0&&this.pos<this.expression.length;){if(this.pos=r+1,this.expression.charAt(r-1)!=="\\"){var o=this.expression.substring(e+1,r);this.current=this.newToken(pu,this.unescape(o),e),t=!0;break}r=this.expression.indexOf(s,r+1)}return t};z.prototype.isParen=function(){var t=this.expression.charAt(this.pos);return t==="("||t===")"?(this.current=this.newToken(Fe,t),this.pos++,!0):!1};z.prototype.isBracket=function(){var t=this.expression.charAt(this.pos);return(t==="["||t==="]")&&this.isOperatorEnabled("[")?(this.current=this.newToken(At,t),this.pos++,!0):!1};z.prototype.isComma=function(){var t=this.expression.charAt(this.pos);return t===","?(this.current=this.newToken(io,","),this.pos++,!0):!1};z.prototype.isSemicolon=function(){var t=this.expression.charAt(this.pos);return t===";"?(this.current=this.newToken(ei,";"),this.pos++,!0):!1};z.prototype.isConst=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&s!=="."&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(r in this.consts)return this.current=this.newToken(no,this.consts[r]),this.pos+=r.length,!0}return!1};z.prototype.isNamedOp=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(this.isOperatorEnabled(r)&&(r in this.binaryOps||r in this.unaryOps||r in this.ternaryOps))return this.current=this.newToken(j,r),this.pos+=r.length,!0}return!1};z.prototype.isName=function(){for(var t=this.pos,e=t,s=!1;e<this.expression.length;e++){var r=this.expression.charAt(e);if(r.toUpperCase()===r.toLowerCase()){if(e===this.pos&&(r==="$"||r==="_")){r==="_"&&(s=!0);continue}else if(e===this.pos||!s||r!=="_"&&(r<"0"||r>"9"))break}else s=!0}if(s){var o=this.expression.substring(t,e);return this.current=this.newToken(Jn,o),this.pos+=o.length,!0}return!1};z.prototype.isWhitespace=function(){for(var t=!1,e=this.expression.charAt(this.pos);(e===" "||e===" "||e===`
107
+ ["${e}"]`;if(r?(p=this.fosSocket)==null?void 0:p.connectionEstablished:(y=this.socket)==null?void 0:y.connectionEstablished){const E=r?this.fosSocket:this.socket;(w=E==null?void 0:E.socket)==null||w.send(d)}else{Xe.debug("no connection adding to offline messages");const E=r?this.fosSocket:this.socket;E==null||E.addOfflineMessage(d)}}subscribeTopic({topic:e,callback:s,fos:r,bridge:o,destinationAddress:n}){const{unsubscribe:i,count:a}=C(e,s);return Xe.debug(`Topic ${e} currently has ${a} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,o,n),()=>{const{count:c}=i();Xe.debug(`Topic ${e} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(e,"unsubscribe",r,o,n)}}async whenReady(){const e=this;return this.webSocketSupported?(await M.when(()=>{var s,r;return!!((s=e.socket)!=null&&s.connectionEstablished)&&(!e.useFosTransport||!!((r=e.fosSocket)!=null&&r.connectionEstablished))&&e.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(e){this._token=e,this.init()}static host(e="localhost"){return this.getInstance().host=e,this}static port(e=8080){return this.getInstance().port=e,this}static alias(e){this.getInstance().alias=e}static getInstance(e=8080,s){if(!this._instance){const r=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:e,token:s,fos:r})}return this._instance}}l(Ct,"_instance");class Vg{constructor(e,s,r,o,n){l(this,"disposers",[]);l(this,"activatableDisposers",[]);l(this,"flowControllers",new Map);l(this,"baselineDependencies",new Map);this.model=e,this.modelData=s,this.modelId=r,this.offlineQueue=o,this.log=n}registerAll(e){var o;const s=((o=this.modelData)==null?void 0:o[J])||{},r=Object.keys(s);this.log.debug(`Found ${r.length} subscriptions in ${this.modelId} (lifecycle: ${e??"any"})`),r.forEach(n=>{const i=s[n],a=i.lifecycle;if(e&&e!==a)return;const c=this.resolvePropKey(n);if(this.log.debug(`Resolved topic: ${n} → ${c}`),i.requiresBaseline&&(this.baselineDependencies.set(c,i.requiresBaseline),this.log.debug(`Registered baseline dependency for ${c}: ${i.requiresBaseline.path}`)),i.flow)this.subscribeWithFlowControl(i,c,a);else{const u=this.createHandler(c,i);this.subscribe(i,c,u,a===x.ACTIVATE)}})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const e of this.activatableDisposers)try{e()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const e=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${e.length} subscriptions for ${this.modelId}`);for(const[s,r]of this.flowControllers)this.log.debug(`Disposing flow controller for ${s}`);this.flowControllers.clear();for(const s of e)try{s()}catch(r){this.log.error("Error during subscription disposal",r)}this.disposers=[],this.activatableDisposers=[]}subscribe(e,s,r,o){const n=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;if(e.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=Ct.getInstance().subscribeTopic({topic:s,callback:r,fos:e.fos,bridge:e.bridge,destinationAddress:n});o?this.activatableDisposers.push(i):this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=C(s,r);o?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(e,s){return async r=>{var o;try{const n=(o=r==null?void 0:r.headers)==null?void 0:o["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),a=i?n===i:!0,c=this.extractWildcardCapture(e,r,s),u=this.isBaselineReady(e);if(!this.model.isReady()||!u){u?this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${e}`):this.log.warn(`Baseline not ready for ${e}. Queuing message.`);const d=()=>{const h=No(r,s.skipParse),f=s.transform(h);if(a&&s.condition(f,this.modelData,r))return this.callHandlerWithWildcard(s,f,c,r)};this.offlineQueue.enqueue(d,e,r)}else{const d=No(r,s.skipParse),h=s.transform(d);if(a&&s.condition(h,this.modelData,r))return this.callHandlerWithWildcard(s,h,c,r)}}catch(n){this.log.error(`Error handling subscription for ${e}`,n)}}}extractWildcardCapture(e,s,r){var n;if(!r.wildcardName||!Vc(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return zc(e,o,r.wildcardName)}callHandlerWithWildcard(e,s,r,o){if(r&&Object.keys(r).length>0){const n={...o,wildcardCapture:r};return e.handler.call(this.modelData,s,n,this.modelData)}else return e.handler.call(this.modelData,s,o,this.modelData)}resolvePropKey(e){const s=/.*({PROP_(.+)})/;let r=e.includes("{MODEL_ID}")?e.replace("{MODEL_ID}",this.modelId):e;const o=r.match(s);return o&&o[2]in this.modelData&&(r=r.replace(o[1],this.modelData[o[2]])),r}async subscribeWithFlowControl(e,s,r){this.log.debug(`Setting up flow control for topic: ${s}`);const o=new Ng(e.flow);this.flowControllers.set(s,o);const n=this.createFlowControlHandler(s,e),i=this.startFlowProcessing(e,s,n,o),a=()=>{this.flowControllers.delete(s),i.then(c=>c==null?void 0:c.abort())};r===x.ACTIVATE?this.activatableDisposers.push(a):this.disposers.push(a)}async startFlowProcessing(e,s,r,o){const n=new AbortController;try{let i;if(e.websocket){const a=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;Ct.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a}),i=Ui(s)}else i=Ui(s);return(async()=>{try{for await(const a of o.processEvents(i)){if(n.signal.aborted)break;const c=r(a);c instanceof Promise&&await o.trackPromise(c)}}catch(a){this.log.error(`Flow control error for ${s}:`,a)}})(),n}catch(i){return this.log.error(`Failed to start flow processing for ${s}:`,i),null}}createFlowControlHandler(e,s){return async r=>{var o,n,i,a;try{if(s.condition&&!s.condition(r,this.modelData,r))return;if(this.model.isReady())return s.handler.call(this.modelData,r,r,this.modelData);{this.log.warn(`Model ${this.modelId} not ready. Queuing flow-controlled message for ${e}`);const c=()=>s.handler.call(this.modelData,r,r,this.modelData);this.offlineQueue.enqueue(c,e,r)}}catch(c){if(this.log.error(`Error in flow control handler for ${e}:`,c),(n=(o=s.flow)==null?void 0:o.errorHandling)!=null&&n.retry)await this.retryHandler(s,r,c);else if(!((a=(i=s.flow)==null?void 0:i.errorHandling)!=null&&a.continueOnError))throw c}}}async retryHandler(e,s,r){const o=e.flow.errorHandling.retry;let n=r;for(let i=1;i<=o.attempts;i++)try{return this.log.debug(`Retry attempt ${i}/${o.attempts} for handler`),await new Promise(a=>setTimeout(a,o.backoffMs*i)),e.handler.call(this.modelData,s,s,this.modelData)}catch(a){n=a,this.log.warn(`Retry attempt ${i} failed:`,a)}throw this.log.error("All retry attempts failed, throwing last error:",n),n}getFlowControlStats(){const e={};for(const[s,r]of this.flowControllers)e[s]=r.getStats();return e}getResponseStore(){return this.modelData.serviceResponses}isBaselineReady(e){const s=this.baselineDependencies.get(e);if(!s)return!0;const r=this.getResponseStore();if(!r)return this.log.warn(`ServiceResponseStore not found for baseline check on topic: ${e}`),!1;const n=`${(s.method||"get").toUpperCase()}:${s.path}`;return r.has(n)}flushQueueForBaseline(e){const s=this.baselineDependencies.get(e);if(!s){this.log.debug(`No baseline dependency for topic: ${e}`);return}const r=this.getResponseStore();if(!r){this.log.warn("ServiceResponseStore not found, falling back to standard flush"),this.offlineQueue.flush();return}const o=s.method||"get",n=r.getTemporalMetadataByPath(s.path,o);if(!n){this.log.warn(`Baseline temporal metadata not found for ${s.path}, falling back to standard flush`),this.offlineQueue.flush();return}const i=s.replayStrategy||nt.AFTER_REQUEST;this.log.info(`Flushing queue with strategy ${i} for topic: ${e}`),this.log.debug(`Baseline timing - requested: ${n.requestedAt}, received: ${n.receivedAt}`),this.offlineQueue.flushWithStrategy(i,n.requestedAt,n.receivedAt)}}function bt(t,e){const s=`[Model:${e}]`;return{debug:(...r)=>t.debug(s,...r),info:(...r)=>t.info(s,...r),warn:(...r)=>t.warn(s,...r),error:(...r)=>t.error(s,...r)}}function Gg(t){return!!(t!=null&&t[it])&&Object.keys(t[it]).length>0}function Yg(t){return!!(t!=null&&t[J])&&Object.keys(t[J]).length>0}function Wg(t){return!!(t!=null&&t[ke])&&t[ke].length>0}function Qg(t){const e=Object.getPrototypeOf(t);return!!(e!=null&&e[at])&&Object.keys(e[at]).length>0}function Zg(t){return t.retention===se.TTL&&t.extendOnRefresh===!0&&t.ttl!==void 0}function Xg(t,e){return t.has(e)}function Jg(t){return!t.expiresAt||Date.now()<t.expiresAt}function Hi(t,e,s,r){const o=setTimeout(()=>r(t),e);s.set(t,o)}class em{constructor(){l(this,"responses",new Map);l(this,"retentionPolicies",new Map);l(this,"cleanupTimers",new Map)}set(e,s,r={retention:se.SINGLE},o=Date.now(),n=Date.now()){if(this.shouldExtendTTL(e,r))return this.extendExistingTTL(e,r.ttl),!1;const i=this.createCachedResponse(s,e,r,o,n);return this.storeResponse(e,i,r),!0}get(e){const s=this.responses.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.delete(e);return}return s.data}}getByPath(e,s="get"){return this.get(this.makeKey(e,s))}has(e){return this.get(e)!==void 0}delete(e){this.responses.delete(e),this.retentionPolicies.delete(e);const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}clearPath(e){Array.from(this.responses.keys()).filter(r=>this.extractPath(r)===e).forEach(r=>this.delete(r))}clear(){this.cleanupTimers.forEach(e=>clearTimeout(e)),this.responses.clear(),this.retentionPolicies.clear(),this.cleanupTimers.clear()}get size(){return this.responses.size}shouldCleanupAfterHandler(e){const s=this.retentionPolicies.get(e);return(s==null?void 0:s.retention)===se.IMMEDIATE}shouldExtendTTL(e,s){if(!Zg(s)||!Xg(this.responses,e))return!1;const r=this.responses.get(e);return Jg(r)}extendExistingTTL(e,s){const r=this.responses.get(e);r.expiresAt=Date.now()+s,this.resetCleanupTimer(e,s)}resetCleanupTimer(e,s){this.clearTimerIfExists(e),Hi(e,s,this.cleanupTimers,r=>this.delete(r))}clearTimerIfExists(e){const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}createCachedResponse(e,s,r,o,n){return{data:e,timestamp:n,requestedAt:o,receivedAt:n,path:this.extractPath(s),method:this.extractMethod(s),expiresAt:this.calculateExpiresAt(r)}}calculateExpiresAt(e){return e.retention===se.TTL&&e.ttl?Date.now()+e.ttl:void 0}storeResponse(e,s,r){this.responses.set(e,s),this.retentionPolicies.set(e,r),this.applyRetentionPolicy(e,r)}applyRetentionPolicy(e,s){switch(s.retention){case se.IMMEDIATE:break;case se.TTL:s.ttl&&Hi(e,s.ttl,this.cleanupTimers,r=>this.delete(r));break;case se.SINGLE:break;case se.PERMANENT:case se.MANUAL:break}}makeKey(e,s){return`${s.toUpperCase()}:${e}`}extractPath(e){return e.split(":",2)[1]||e}extractMethod(e){return e.split(":",2)[0]||"get"}getTemporalMetadata(e){const s=this.responses.get(e);if(s)return{requestedAt:s.requestedAt,receivedAt:s.receivedAt}}getTemporalMetadataByPath(e,s="get"){return this.getTemporalMetadata(this.makeKey(e,s))}cleanup(){const e=Date.now();Array.from(this.responses.entries()).filter(([r,o])=>o.expiresAt&&e>o.expiresAt).map(([r])=>r).forEach(r=>this.delete(r))}}class tm{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=xc.create({modelId:s,modelTypeName:r}),i=new yg(e,bt(n,"fsm")),a=new vg(bt(n,"offline-queue")),c=new lg(e),u=new cg(e),d=new em;o.serviceResponses=d;const h={fsm:i,offlineQueue:a,serviceResponseStore:d,companionManager:c,childResolver:u};if(Gg(o)&&(h.effectManager=new ug(r,s,o,bt(n,"effect"))),Yg(o)){const f=bt(n,"subscription");h.subscriptionManager=new Vg(e,o,s,a,f),h.onlineLifecycleManager=new wg(e,bt(n,"online"))}return Wg(o)&&(h.httpRouteManager=new Cn(o,bt(n,"http-routes"))),Qg(o)&&(h.serviceRequestManager=new Ag(o,d)),h}}const N=D.getLogger("kos-model"),sm="kos.extension.model.loader";class El{constructor({modelTypeName:e,id:s,modelData:r}){l(this,"_id");l(this,"_status");l(this,"_activeStatus");l(this,"_onlineStatus");l(this,"modelData");l(this,"modelTypeName");l(this,"initialized");l(this,"loaded");l(this,"_isLoadExecuting");l(this,"offlineQueue");l(this,"subscriptionManager");l(this,"effectManager");l(this,"httpRouteManager");l(this,"onlineLifecycleManager");l(this,"serviceResponses");l(this,"serviceRequestManager");l(this,"companionManager");l(this,"childResolver");l(this,"fsm");this._id=typeof s<"u"?`${s}`:e,this.modelTypeName=e,this.initialized=!1,this.loaded=!1,this._isLoadExecuting=!1,this.modelData=r,this._status=v.CREATED,this._activeStatus=v.INACTIVE,this._onlineStatus=v.OFFLINE;const o=tm.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,this.serviceResponses=o.serviceResponseStore,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.httpRouteManager&&(this.httpRouteManager=o.httpRouteManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),o.serviceRequestManager&&(this.serviceRequestManager=o.serviceRequestManager),M.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,serviceRequestManager:!1,serviceResponses:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),ig(this)}get companionModels(){return this.companionManager}set status(e){this._status=e}get status(){return this._status}get modelId(){return this._id}get id(){return this._id}get activeStatus(){return this._activeStatus}set activeStatus(e){this._activeStatus=e}get onlineStatus(){return this._onlineStatus}set onlineStatus(e){this._onlineStatus=e}get modelManager(){return globalThis.kos.modelManager}isActive(){return this._status===v.ACTIVE}isOnline(){return this._onlineStatus===v.ONLINE}isReady(){return this._status===v.READY}async deactivate(){var e,s,r;N.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=G.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,o)),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw N.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var e,s,r,o;N.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await ts(this,x.ACTIVATE);try{await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(x.ACTIVATE));const n=G.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.activate)==null?void 0:r.call(s,n)),this.initializeStateMachineForLifecycle(x.ACTIVATE),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(x.ACTIVATE),this.createLifecycleCompanions(x.ACTIVATE),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(n){throw N.debug(`Model ${this.modelId} failed to activate`),n}}async whenLoaded(){await _o([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{N.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await _o([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{N.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await _o([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===v.READY,onMatch:()=>{N.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r,o;if(this.fsm.current===v.READY){N.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{N.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await ts(this,x.READY),await ol(this,In.READY,x.READY),await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(x.READY));const n=G.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.ready)==null?void 0:r.call(s,n)),this.offlineQueue.flush(),this.initializeStateMachineForLifecycle(x.READY),(o=this.subscriptionManager)==null||o.registerAll(x.READY),this.createLifecycleCompanions(x.READY),N.debug(`Model ${this.modelId} is ready`);const i={modelId:this.modelId,modelType:this.modelTypeName};q(Wc(this.modelTypeName,this.modelId),i),q(Qc(this.modelTypeName),i)}catch(n){throw N.error(n),Error(n)}}async load(){var o,n,i,a,c,u;const e=this[Ve];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===v.LOADED){N.debug(`Model ${s} with id ${r} already loaded`);return}if(this._isLoadExecuting){N.debug(`Model ${s} with id ${r} is currently executing load`);return}this._isLoadExecuting=!0;try{N.debug(`Loading model ${s} with id ${r}`),await ts(this,x.LOAD);const d=G.getContext(r),h=`${sm}.${s}`,f=await $.loader.executeLoader(h,{});f&&(N.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(h,f)),await((o=this.serviceRequestManager)==null?void 0:o.executeForLifecycle(x.LOAD)),await((i=(n=this.modelData)==null?void 0:n.load)==null?void 0:i.call(n,d)),X(()=>{this.loaded=!0}),N.debug(`Model ${s} with id ${r} successfully loaded`),this.initializeStateMachineForLifecycle(x.LOAD),(a=this.subscriptionManager)==null||a.registerAll(x.LOAD),(c=this.httpRouteManager)==null||c.registerAll(),(u=this.effectManager)==null||u.setup(),this.createLifecycleCompanions(x.LOAD)}catch(d){throw N.error(`Model ${r} failed to load`,d),d}finally{this._isLoadExecuting=!1}}async unload(){var e,s,r,o,n,i,a;N.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const c=this.getChildren().map(d=>{var h;return(h=d.unload)==null?void 0:h.call(d)}).filter(d=>!!d);await Promise.allSettled(c);const u=G.getContext(this.modelId);if(await((s=(e=this.modelData)==null?void 0:e.unload)==null?void 0:s.call(e,u)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),this.modelData){const d=this.modelData;if(d._fsmInitialized=!1,d._fsmConfig){const h=((o=d._fsmOptions)==null?void 0:o.stateProperty)||"currentState";d[h]=void 0}d.stateHistory&&(d.stateHistory=[])}N.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(n=this.effectManager)==null||n.disposeAll(),(i=this.subscriptionManager)==null||i.disposeAll(),(a=this.httpRouteManager)==null||a.dispose()}catch(c){throw N.debug(`Model ${this.modelId} failed to unload`),c}}async init(){var n,i,a,c;const e=this[Ve];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=G.getContext(s);N.debug(`Initializing model ${r} with id ${s}`),await ts(this,x.INIT);try{await((n=this.serviceRequestManager)==null?void 0:n.executeForLifecycle(x.INIT)),await((a=(i=this.modelData)==null?void 0:i.init)==null?void 0:a.call(i,o)),this.initialized=!0,N.debug(`Model ${r} with id ${s} initialized`),(c=this.onlineLifecycleManager)==null||c.register(),this.initializeStateMachineForLifecycle(x.INIT),this.registerSubscribers(x.INIT),this.createLifecycleCompanions(x.INIT)}catch(u){throw N.error(`Model ${s} failed to initialize`,u),u}}async registerSubscribers(e){var s;N.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}initializeStateMachineForLifecycle(e){this.modelData&&Oc(this.modelData,e)}createLifecycleCompanions(e){this.modelManager.createLifecycleCompanions(this,{},e)}async online(){var s,r;N.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=G.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e)),this.createLifecycleCompanions(x.ONLINE)}async offline(){var s,r,o;N.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=G.getContext(this.modelId);await((o=(r=this.modelData)==null?void 0:r.offline)==null?void 0:o.call(r,e))}accept(e){e.visit(this)}getChildren(){return this.childResolver.resolve()}addCompanionModel(e){this.companionManager.add(e)}clearCompanionModels(){this.companionManager.clear()}}const So=m.createLogger({name:"kos-model-instantiator"});class rm{constructor(e,s){l(this,"companionInstantiator");this.registry=e,this.cache=s,this.companionInstantiator=new Jp(e,s,this.createModelInstance.bind(this))}createModelInstance(e,s,r={}){var a;const o=this.registry.models[e];if(!o){const c=`No model registered for type ${e}`;throw So.error(c,{modelType:e,requestedId:s,providedOptions:r,availableModelTypes:Object.keys(this.registry.models)}),Ot(new Error(c),{modelType:e,modelId:s,operation:"model instantiation - registry lookup",options:r,metadata:{availableModelTypes:Object.keys(this.registry.models)}})}const n=o.singleton?e:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){So.debug(`Creating model instance: ${e} [${n}]`);const c=r&&Object.keys(r).length>0,u=o.class||o.create;if(((a=u==null?void 0:u.prototype)==null?void 0:a[Hs])===!0&&!c){const h=new Error(`Model ${e} requires options but none were provided`);throw Fi(h,{modelType:e,options:r,registryId:this.registry.alias||"unknown"}),Ot(h,{modelType:e,modelId:n,operation:"model instantiation - options validation",options:r,metadata:{requiresOptions:!0,hasOptions:!1}})}try{const h=o.create?o.create({modelTypeId:e,id:n,options:r}):new o.class(n,r),f=new El({modelTypeName:e,id:n,modelData:h});this.cache.addModel(f),this._createCompanionModels(f,r)}catch(h){throw Fi(h,{modelType:e,options:r,registryId:this.registry.alias||"unknown"}),Ot(h,{modelType:e,modelId:n,operation:"model instantiation",options:r})}}const i=this.cache.getModelById(n);if(!i)throw So.error(`Model ${e} [${n}] not found in cache`),new Error(`Model ${e} [${n}] not found in cache`);return{model:i,data:i.modelData}}createCompanionModels(e,s,r){this.companionInstantiator.createCompanionModels(e,s,r)}_createCompanionModels(e,s){this.createCompanionModels(e,s)}}let om=class{constructor(e){this._registry=e}get registry(){return this._registry}getModelTypeRegistry(e){const s=this.registry.models[e];if(!s)throw new Error(`No registration for model type ${e}`);return s}registerModel(e){const s=e.type;this.registry.models[s]||(this.registry.models={...this.registry.models,...e.registration})}registerCompanionModel(e,s){var r,o;(r=this.registry).companionModels??(r.companionModels={}),(o=this.registry.companionModels)[e]??(o[e]=[]),this.registry.companionModels[e].some(n=>n.type===s)||this.registry.companionModels[e].push({type:s})}getModelSubscriptions(e){var s;return((s=this.getModelTypeRegistry(e))==null?void 0:s.subscriptions)||{}}getDataModelBuilder(e){var r;const s=(r=this.getModelTypeRegistry(e))==null?void 0:r.builder;if(!s)throw new Error(`No builder found for model type ${e}`);return s}getModelFactory(e){return Kt(e)}};const Ml=10,Ki=m.createLogger({name:"kos-model-manager"});class Tl{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Qp,globalThis.kos.modelManager=this,globalThis.kos.resolveKosModel=e=>{const s=this.getModelById(e);if(s)return s.modelData||{}},globalThis.kos.kosModelJson=e=>{var r,o;const s=this.getModelById(e);if(s)return((o=(r=s.modelData).toJSON)==null?void 0:o.call(r))||{}},globalThis.kos.kosModelDebug=e=>{var r;const s=this.getModelById(e);if(s)return((r=s.modelData)==null?void 0:r.debugState)||{}},globalThis.kos.kmd=globalThis.kos.kosModelDebug,globalThis.kos.kmj=globalThis.kos.kosModelJson}static create(e,s){const r=this.getInstance(s);return r._registry=new om(e),r.cache=new Zp(e.preloadModels),r.instantiator=new rm(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(Ki.debug("Creating new instance of KosModelManager"),new this),(r=globalThis.kos)==null?void 0:r.modelManager}get registry(){return this._registry.registry}get preloadedModels(){return this.cache.preload(e=>(Ki.debug(`preloading ${e}`),typeof e=="string"?this.createModelInstance(e).model:this.createModelInstance(e.modelType,e.modelId,e.options).model))}get models(){return this.cache.models}getModelById(e){return this.cache.getModelById(e)}addModel(e){return this.cache.addModel(e)}removeModel(e){this.cache.removeModel(e.modelId)}hasModel(e){return this.cache.hasModel(e)}getModelsByType(e,s){return Array.from(this.models).filter(r=>r.modelTypeName===e).filter(r=>s?s(r.modelData):!0).map(r=>r.modelData)}getModelSubscriptions(e){return this._registry.getModelSubscriptions(e)}getDataModelBuilder(e){return this._registry.getDataModelBuilder(e)}getModelFactory(e){return Kt(e)}addDependency(e,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(e,s)}removeDependency(e,s){this.dependencies.remove(e,s)}async reloadModel(e){if(e.id){const s=this.getModelById(e.id);s&&await s.fsm.transitionTo(k.RESET,v.RESETTING)}}async initiateDestroyModel(e){if(!e.id)throw new Error("Model ID is required");if(!this.dependencies.canDestroy(e.id))return;const s=this.getModelById(e.id);s&&(this.cache.markForDeletion(s),Gc.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),Ml)))}async destroyModel(e){var s;e!=null&&e.modelId&&this.dependencies.canDestroy(e.modelId)&&(await((s=e.unload)==null?void 0:s.call(e)),this.removeModel(e))}createModelInstance(e,s,r={}){return this.instantiator.createModelInstance(e,s,r)}createLifecycleCompanions(e,s,r){this.instantiator.createCompanionModels(e,s,r)}registerCompanionModel(e,s){this._registry.registerCompanionModel(e,s)}registerModel(e){this._registry.registerModel(e)}}var dr=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.RELOADING="reloading",t))(dr||{}),tt=(t=>(t.CREATE="create",t.INITIALIZE="init",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.UNLOAD="unload",t.RELOAD="reload",t))(tt||{});const nm=t=>{const e=b.createMachine("offline",{online:b.state(b.transition("go_offline","offline",b.action(()=>{t.offline(),M.runInAction(()=>{t.isOnline=!1})}))),offline:b.state(b.transition("go_online","online",b.action(()=>{t.online(),M.runInAction(()=>{t.isOnline=!0})})))}),s=b.interpret(e,n=>D.debug(n.machine.current)),r=b.createMachine({creating:b.state(b.transition("create","created")),created:b.state(b.immediate("initializing")),initializing:b.invoke(()=>t.init(),b.transition("done","initialized")),initialized:b.state(b.immediate("loading")),loading:b.invoke(()=>t.load(),b.transition("done","loaded")),loaded:b.state(b.immediate("readying"),b.transition("unload","unloading")),readying:b.invoke(()=>t.ready(),b.transition("done","ready",b.action(()=>{M.runInAction(()=>{t.status="ready"})}))),reloading:b.invoke(()=>t.reload(),b.transition("done","loading")),ready:b.state(b.transition("reload","reloading"),b.transition("unload","unloaded",b.action(t.unload.bind(t))),b.transition("go_online","ready",b.action(()=>{s.send("go_online")})),b.transition("go_offline","ready",b.action(()=>{s.send("go_offline")}))),unloaded:b.state()});return{service:b.interpret(r,n=>D.debug(n.machine.current)),online:s}},V=m.createLogger({name:"kos-core"}),im=()=>{const t=be(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},am=()=>{const t=window.location.protocol,e=be(),s=e==null?void 0:e.host;let r;try{r=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return r||(t==="https:"?"wss://":"ws://")},cm=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=be(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??e??t},lm=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=be(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??e??t},um=(t,e)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{e?m.error(`Model ${e.modelId} - ${e.modelTypeName} preloading - timed out after ${t}ms`):m.error(`KOS Core preloading timed out after ${t}ms`),i(new Error(`Model ${e==null?void 0:e.modelId} - ${e==null?void 0:e.modelTypeName} - timed out after ${t}ms`))},t)}),cancel:()=>{s&&clearTimeout(s)}}},qi=t=>typeof t.reload=="function",dm=t=>typeof t.unload=="function";var _l=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(_l||{});class O{constructor(e){l(this,"fsmService");l(this,"status");l(this,"initialized");l(this,"loaded");l(this,"_transport");l(this,"modelManager");l(this,"authState");l(this,"isOnline");l(this,"_reloading");l(this,"_unloading");l(this,"connectionAlias");this.initialized=!1,this.connectionAlias=e,this.loaded=!1,this.isOnline=!1,this.status=dr.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),C("token",a=>{a&&(this.transport.token=a.body)}),C(Ms.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(tt.GO_ONLINE)}),C(Ms.DISCONNECTED,async()=>{this.fsmService.service.send(tt.GO_OFFLINE)}),C("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0,this.fsmService.service.send(tt.RELOAD)}),C("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),C(Ms.RELOAD,()=>{V.warn("WebSocket requested reload"),this.fsmService.service.send(tt.RELOAD)}),C("/studio/project/reload",()=>{V.warn("Project requested reload"),this.fsmService.service.send(tt.RELOAD)});const s=Ct.getInstance(),r=cm(),o=lm(),n=am();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=im()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=nm(this),this.fsmService.service.send(tt.CREATE)}get onlineStatus(){return this.isOnline&&!this._reloading&&!this._unloading}get reloading(){return this._reloading}get unloading(){return this._unloading}async reload(){var o,n,i,a;const e=Date.now();if(this._reloading){V.info("reload already in progress");return}this._reloading=!0,V.warn("reloading KOS Core"),V.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)qi(c.modelData)&&(V.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),V.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&qi(c.modelData)&&(V.warn(`reloading model ${c.modelId}`),(i=c.unload)==null||i.call(c),await c.modelData.reload(),(a=c.registerSubscribers)==null||a.call(c));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{V.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){V.debug("KOS Core going online"),await this._transport.whenReady(),V.debug("KOS Transport Ready. Calling online() for models"),q("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){V.debug("KOS Core going offline"),q("/kosCore/offline","/kosCore/offline")}async unload(){var o;V.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,V.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)dm(n.modelData)&&((o=n.unload)==null||o.call(n));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{this._unloading=!1})},1e3-r)}async whenReady(){await M.when(()=>this.status===dr.READY)}async ready(){V.debug("Readying KOS Core"),await this._transport.whenReady();const e=this.modelManager.preloadedModels.map(o=>({modelId:o.modelId,model:o,promise:o.whenReady()})),r=(await Promise.allSettled(e.map(o=>{const{promise:n,cancel:i}=um(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw V.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);V.debug("leaving kos-core ready() ")}get isReady(){return this.status===dr.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){V.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,V.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){V.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,V.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(e,s,r){var i,a,c;const o=this.getInstance({reset:s,connectionAlias:r});(i=e.extensions)!=null&&i.dataMapper&&Object.keys(e.extensions.dataMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.dataMapper)==null?void 0:f[u];d&&(Array.isArray(d)?d.forEach(p=>{$.dataMapper.registerDataMapper(u,p)}):$.dataMapper.registerDataMapper(u,d))}),(a=e.extensions)!=null&&a.propertyMapper&&Object.keys(e.extensions.propertyMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.propertyMapper)==null?void 0:f[u];d&&$.propertyMapper.registerPropertyMapper(u,d)}),(c=e.extensions)!=null&&c.contextLoader&&Object.keys(e.extensions.contextLoader).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.contextLoader)==null?void 0:f[u];d&&$.loader.registerLoader(u,d)}),A.model.getAll().forEach(([,u])=>{e.models={...e.models,...u.registration}}),e.models={...e.models,...A.model.getLegacyModels()},A.companion.getAll().forEach(([u,d])=>{e.companionModels={...e.companionModels},e.companionModels[u]=e.companionModels[u]||[];for(const h of d){let f;if(typeof h=="string"){const p=e.models[h];if(p!=null&&p.class){const y=p.class.prototype[Ve];f=y==null?void 0:y.lifecycle}}e.companionModels[u].push({type:h,lifecycle:f})}}),A.model.getPreloadModels().forEach(u=>{e.preloadModels.includes(u)||e.preloadModels.push(u)});const n=Tl.create(e,s);return o.modelManager=n,o}static getInstance(e){return this._instance=window.KosCore,(!this._instance||e!=null&&e.reset)&&(window.KosCore=new this(e==null?void 0:e.connectionAlias),this._instance=window.KosCore),this._instance}}l(O,"_instance");function jo(t){const e=new Uint8Array(t);let s="";for(let r=0;r<e.byteLength;r++)s+=String.fromCharCode(e[r]);return btoa(s)}function hm(t){const e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s.buffer}async function fm(t){return await t.arrayBuffer()}function pm(t,e){return new Blob([t],{type:e})}async function gm(t){const e={},s=[],r=[];t.forEach((o,n)=>{r.push([n,o])});for(const[o,n]of r)if(n instanceof File){const i=await n.arrayBuffer();s.push({name:o,filename:n.name,type:n.type,data:jo(i)})}else e[o]=n.toString();return{fields:e,files:s}}function mm(t){return new ReadableStream({async start(){},async pull(e){await t(e)},cancel(){}})}async function ym(t){if(!t)return{data:"",contentType:"text/plain"};if(typeof t=="string")return{data:t,contentType:"text/plain"};if(t instanceof ArrayBuffer||t instanceof Uint8Array){let e;return t instanceof Uint8Array?(e=new ArrayBuffer(t.byteLength),new Uint8Array(e).set(t)):e=t,{data:jo(e),contentType:"application/octet-stream",encoding:"base64"}}if(t instanceof Blob){const e=await fm(t);return{data:jo(e),contentType:t.type||"application/octet-stream",encoding:"base64"}}if(t instanceof FormData){const e=await gm(t);return{data:JSON.stringify(e),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const tr=m.createLogger({name:"kos-fetch"}),bm=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,vm=()=>new Promise(t=>{setTimeout(()=>{t(!0)},0)}),wm=t=>t!=null&&t.studio?ll:t!=null&&t.fos?ul:dl,Em=async(t,e)=>{const s=O.getInstance().transport;await s.whenReady();const r=ut(),o=new URL(t),n=`${o.pathname}${o.search}`;tr.debug(`path: ${n}`);const i=(e==null?void 0:e.timeout)||bm,a=wm(e),c=await ym(e==null?void 0:e.body),u={};c.contentType&&(u["content-type"]=c.contentType),c.encoding&&(u["content-encoding"]=c.encoding);const d=Qe(a({path:n,requestId:r,method:(e==null?void 0:e.method)||"GET",destinationAddress:(e==null?void 0:e.destinationAddress)||"",ordered:e==null?void 0:e.ordered,tracker:e==null?void 0:e.tracker,bridge:e==null?void 0:e.bridge,headers:{...e==null?void 0:e.headers,...u}}),c.data);return new Promise(h=>{let f=null,p=null;if(e!=null&&e.signal){if(e.signal.aborted){h({headers:ss({}),status:0,ok:!1,json:async()=>null,body:rs(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}});return}e.signal.addEventListener("abort",()=>{p&&clearTimeout(p),f&&f(),h({headers:ss({}),status:0,ok:!1,json:async()=>null,body:rs(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})})}p=setTimeout(()=>{tr.error(`Timeout occurred - url: ${t}`),f&&f(),h({headers:ss({}),status:404,ok:!1,json:async()=>null,body:rs(""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})},i);const y=C(r,E=>{p&&clearTimeout(p);const _=(E==null?void 0:E.headers)||{},L=_["content-type"]||"text/plain",U=_["content-encoding"],I=(E==null?void 0:E.body)||"";let S=I;if(U==="base64"&&I)try{S=hm(I)}catch(W){tr.error("Failed to decode base64 response",W)}const Z={headers:ss(_),status:_.status&&parseInt(_.status)||200,ok:_.status==="200",json:async()=>{try{if(typeof S=="string")return S.length?JSON.parse(S):null;{const le=new TextDecoder().decode(S);return le.length?JSON.parse(le):null}}catch{throw Error("Not a JSON response")}},text:async()=>typeof S=="string"?S:new TextDecoder().decode(S),arrayBuffer:async()=>S instanceof ArrayBuffer?S:new TextEncoder().encode(S).buffer,blob:async()=>S instanceof ArrayBuffer?pm(S,L):new Blob([S],{type:L}),formData:async()=>{const W=new FormData;if(L==="multipart/form-data"&&typeof S=="string")try{const le=JSON.parse(S);le.fields&&Object.entries(le.fields).forEach(([Zt,Xt])=>{W.append(Zt,Xt)}),le.files&&tr.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return W},body:e!=null&&e.stream?mm(async W=>{if(S instanceof ArrayBuffer)W.enqueue(new Uint8Array(S));else{const le=new TextEncoder;W.enqueue(le.encode(S))}W.close()}):rs(typeof S=="string"?S:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};y.unsubscribe(),vm().then(()=>h(Z))});f=y.unsubscribe;const w=e!=null&&e.fos?s.fosSocket:s.socket;if(!w)throw Error(`No web socket transport available: ${e}`);w==null||w.send(d)})};exports.BASE_URL="kos:";exports.kosFetch=Em;if(process.env.KOS_MOCK_FETCH==="true"){const t=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${t}`}const Mm=m.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Tm{constructor(){l(this,"visitedModels",new Set);this.visitedModels=new Set}start(e){var r;if(e.id===void 0)throw new Error("rootModel must have an id");const s=O.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error(`Could not find rootModel with id: ${e.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(e){var r;if(this.visitedModels.has(e.modelId)){Mm.info(`model ${e.modelId} already visited`);return}const s=!!this.visitModel(e.modelData,this);this.visitedModels.add(e.modelId),!s&&((r=e.getChildren)==null||r.call(e).forEach(o=>{var n;(n=o.accept)==null||n.call(o,this)}))}}class Sl{constructor(){l(this,"middlewares",[])}use(e){this.middlewares.push(e)}async execute(e){let s=0;const r=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](e,r)};await this.middlewares[s](e,r)}}const _m=async(t,e)=>{const s=new Sl;e.forEach(o=>s.use(o));const r={data:t,result:{}};return await s.execute(r),r.result},Kt=t=>({type:t,build:(e,s)=>O.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=O.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),Sm=t=>{O.getInstance().modelManager.registerModel(t)},Om=(t,e)=>{O.getInstance().modelManager.registerCompanionModel(t,e)},zi="/kos/ui/internal/heartbeat/",Im=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:o})=>{const n=O.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${zi}${t}`,callback:()=>{a=performance.now()}}),u=r??3e3,d=window.setInterval(()=>{let w=performance.now()-a;w=w/1e3,w>u/1e3&&i.abort()},u),h=o??2e3,f=window.setInterval(()=>{bl({msg:{},options:{topic:`${zi}${t}`,destinationAddress:e}})},h),p=()=>{window.clearInterval(f),window.clearInterval(d),c()},y=()=>{p(),s&&s(),i.signal.removeEventListener("abort",y)};return i.signal.addEventListener("abort",y),{cleanUpHeartbeat:p}},Ol=(...t)=>e=>t.reduce((s,r)=>r(s),e),$m={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function Cm(t,e){let s=1;const r={...$m,...e},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await t()}catch(c){if(m.error(`Attempt ${s} failed: ${c}`),s<o)a=n*Math.pow(i,s),await new Promise(u=>setTimeout(u,a)),s++;else throw c}throw new Error("All attempts failed")}const Dm=m.createLogger({name:"kos-service-request"}),ce=t=>({isMock:!1,URL:exports.BASE_URL}),xm=(t,e,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:c,bridge:u,destinationAddress:d})=>{const h={method:"DELETE"};t&&(h.destinationAddress=t),o&&(h.tracker=o),qt(h,{ordered:i,studio:a,fos:c,bridge:u,destinationAddress:d});const f=await s(n||`${e}/${r}`,h);if(!f.ok)throw Error(`There was a problem deleting the model; returned status ${f.status}`);return await f.json()},qt=(t,{ordered:e,studio:s,fos:r,destinationAddress:o,bridge:n,timeout:i})=>(i&&(t.timeout=i),e&&(t.ordered=e),s&&(t.studio=s),r&&(t.fos=r),n&&(t.bridge=n),(o||o==="")&&(t.destinationAddress=o),t),Am=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:c,destinationAddress:u})=>{const d={method:"GET"};t&&(d.destinationAddress=t),qt(d,{timeout:c,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:u});const f=await s(r||e,d);if(!f.ok){let y;try{y=await f.json()}catch{}throw new ye(`There was a problem retrieving the model; returned status ${f.status}`,y)}return await f.json()},Rm=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:c,timeout:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),c&&(h.tracker=c),qt(h,{timeout:u,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:d});const f=r||e;Dm.debug(`resolvedUrl: ${f}`);const p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ye(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()},Pm=(t,e,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:c,timeout:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),qt(h,{timeout:u,ordered:n,studio:i,fos:a,bridge:c,destinationAddress:d});const f=r||`${e}/${o}`,p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ye(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()};class ye extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const Vi=(t,e,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:c,bridge:u,timeout:d,destinationAddress:h})=>{const f={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};t&&(f.destinationAddress=t),i&&(f.tracker=i),qt(f,{timeout:d,ordered:n,studio:a,fos:c,bridge:u,destinationAddress:h});const p=await s(o||e,f);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ye(`There was a problem sending the POST data; returned status ${p.status}`,w)}return await p.json()},Gi=(t="POST",e,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:c,fos:u,bridge:d,timeout:h,destinationAddress:f})=>{const p={method:t};o&&(p.body=JSON.stringify(o)),e&&(p.destinationAddress=e),qt(p,{timeout:h,ordered:a,studio:c,fos:u,bridge:d,destinationAddress:f});const y=await r(i||`${s}/${n}`,p);if(!y.ok){let E;try{E=await y.json()}catch{}throw new ye(`There was a problem modifying the model; returned status ${y.status}`,E)}return await y.json()},oe={build:({destinationAddress:t="",basePath:e,getAllPath:s,getOnePath:r,deleteModelPath:o,addModelPath:n,modifyModelPath:i,mock:a=!1})=>{const c=a?fetch:exports.kosFetch;return{getAll:Am(t,s||e,c),getModelById:Pm(t,r||e,c),getOne:Rm(t,r||e,c),addModel:Vi(t,n||e,c),deleteModel:xm(t,o||e,c),modifyModel:Gi("POST",t,i||e,c),putModel:Gi("PUT",t,i||e,c),postModel:Vi(t,n||e,c)}}};function km(t,e,s="get"){const r=t.serviceResponses;if(r)return r.getByPath(e,s)}function Lm(t,e,s="get"){const r=t.serviceResponses;return r?r.has(`${s.toUpperCase()}:${e}`):!1}function Fm(t,e,s="get"){const r=t.serviceResponses;r&&r.delete(`${s.toUpperCase()}:${e}`)}function Nm(t,e){const s=t.serviceResponses;s&&s.clearPath(e)}function Um(t){const e=t.serviceResponses;e&&e.clear()}const jm=ut(),Il=()=>`kos-${jm}`,Bm=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(Il()),xn=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=C(t,i=>{D.debug(`recieved response for refId ${t}: ${i}`),o(),clearTimeout(n);try{const a=i!=null&&i.body?JSON.parse(i.body):{};s(a)}catch{const a=(i==null?void 0:i.body)||{};s(a)}}),n=setTimeout(()=>{o(),r(Error(`Request with ID ${t} timed out. Cancelling.`))},e)}),Hm=async(t,e,s)=>{const r=xn(s),o=await Promise.allSettled([t(e),r]);if(o[0].status==="fulfilled"){if(o[1].status==="rejected")throw Error(o[1].reason);if(o[0].value){if(o[1].value.error)throw Error(o[1].value.error);return o[0].value.data=o[1].value,o[0].value}}else throw Error(o[0].reason)},Km=async({topic:t,msg:e,requestId:s})=>{const r=s??ut(),o=xn(r);q(t,e,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},pe=new Map;class $l{constructor(e){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=e,this._context=new M.ObservableMap({}),this._parent="",M.makeAutoObservable(this)}setParent(e){X(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=$e(this._parent))==null?void 0:e.model}get companionModels(){const e=$e(this._id);return e!=null&&e.model?Bc(e.model):[]}get(e){var s,r;if(this._context.has(e))return this._context.get(e);if(this.companionModels.length>0){const o=this.companionModels.find(n=>{var i;return!n.id||!pe.has(n.id)?!1:(i=pe.get(n.id))==null?void 0:i.context.has(e)});if(o)return(s=pe.get(o.id))==null?void 0:s.get(e)}if(this._parent)return(r=pe.get(this._parent))==null?void 0:r.get(e)}set(e,s){this._context.set(e,s)}remove(e){this._context.delete(e)}clear(){this._context.clear()}}const G={createContext:(t,e)=>{const s=pe.get(t)??new $l(t);if(e){if(!pe.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return pe.set(t,s),s},getContext:t=>pe.get(t),deleteContext:t=>{pe.delete(t)},setParentContext:(t,e)=>{var s;if(!pe.has(e))throw new Error(`Parent context ${e} does not exist`);(s=pe.get(t))==null||s.setParent(e)},rootContext:()=>pe.get("root")};G.createContext("root");const qm=t=>G.getContext(t.id),Je=m.createLogger({name:"kos-data-container"});class An{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"idx");l(this,"_maxCapacity");l(this,"_evictionStrategy");l(this,"_evictionBatchSize");l(this,"_insertionOrder",[]);l(this,"_accessTimes");l(this,"_customEvictionFilter");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1,this._optionsMap=(e==null?void 0:e.indexMap)||{};const s=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((r,o)=>(r[o]=void 0,r),{}):{};this._index=M.observable.map(s),this.idx=Ie(),this._maxCapacity=e==null?void 0:e.maxCapacity,this._evictionStrategy=(e==null?void 0:e.evictionStrategy)||"fifo",this._evictionBatchSize=(e==null?void 0:e.evictionBatchSize)??Math.max(10,Math.ceil(((e==null?void 0:e.maxCapacity)??100)*.1)),this._customEvictionFilter=e==null?void 0:e.customEvictionFilter,this._evictionStrategy==="lru"&&this._maxCapacity&&(this._accessTimes=M.observable.map(new Map)),M.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new Sn({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}get revision(){return this._revision}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s))})}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s))})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addModel(e,s){const r=this._ensureObservable(e);this._cleanupExistingDisposer(e.id),this._persistData(r),this._trackDataMetadata(r),this._enforceCapacityLimits(),this._configureDataMonitoring(r),s||this.increment()}_ensureObservable(e){return M.isObservable(e)?e:M.observable.object(e)}_cleanupExistingDisposer(e){if(!e)return;const s=this._disposerMap.get(e);s&&(s(),this._disposerMap.delete(e))}_persistData(e){this._data.set(e.id||"",e)}_trackDataMetadata(e){this._maxCapacity&&(this._insertionOrder.push(e.id||""),this._accessTimes&&this._accessTimes.set(e.id||"",Date.now()))}_enforceCapacityLimits(){this._maxCapacity&&this._data.size>this._maxCapacity&&this._evictModels()}_configureDataMonitoring(e){const s=M.observe(e,r=>{Object.values(this._optionsMap||{}).includes(r.name)&&this.increment()});this._disposerMap.set(e.id||"",s)}removeModel(e){this._data.delete(e);const s=this._insertionOrder.indexOf(e);s!==-1&&this._insertionOrder.splice(s,1),this._accessTimes&&this._accessTimes.delete(e),this.increment();const r=this._disposerMap.get(e);r&&(r(),this._disposerMap.delete(e))}updateModel(e){const s=M.observable.object(e);this._data.set(s.id||"",s),this.increment()}getModel(e){const s=this._data.get(e);return s&&this._accessTimes&&this._accessTimes.set(e,Date.now()),s}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(Je.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(e,s){if(this.index.has(e)){const r=this.index.get(e);return r.index.has(s)?r.getByKey(s):(Je.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return Je.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}_evictModels(){if(!this._maxCapacity)return;const e=this._data.size-this._maxCapacity;if(e<=0)return;const s=Math.min(this._evictionBatchSize,e);this._logDataCapacityWarning(s);const r=this._selectDataForEviction(s);this._removeEvictedData(r),this._logDataEvictionComplete(r.length)}_logDataCapacityWarning(e){Je.info(`Data container capacity exceeded (${this._data.size}/${this._maxCapacity}). Evicting ${e} items using ${this._evictionStrategy} strategy. This may indicate missing cleanup handlers or data inconsistency.`)}_selectDataForEviction(e){switch(this._evictionStrategy){case"fifo":return this._selectFifoData(e);case"lru":return this._selectLruData(e);case"custom":return this._selectCustomData(e);default:return this._selectFifoData(e)}}_selectFifoData(e){const s=[];for(let r=0;r<e&&this._insertionOrder.length>0;r++){const o=this._insertionOrder.shift();o&&this._data.has(o)&&s.push(o)}return s}_selectLruData(e){const s=[];return this._accessTimes&&Array.from(this._accessTimes.entries()).sort((o,n)=>o[1]-n[1]).slice(0,e).forEach(([o])=>{this._data.has(o)&&s.push(o)}),s}_selectCustomData(e){return this._customEvictionFilter?this._customEvictionFilter(this.data).slice(0,e).map(r=>r.id):(Je.error("Custom eviction strategy specified but no customEvictionFilter provided. Falling back to FIFO."),this._selectFifoData(e))}_removeEvictedData(e){e.forEach(s=>{var o;const r=this._data.get(s);Je.info(`Evicting data item: ${s}`,{itemId:s,itemType:r?(o=r.constructor)==null?void 0:o.name:"unknown",strategy:this._evictionStrategy}),this.removeModel(s)})}_logDataEvictionComplete(e){Je.info(`Evicted ${e} data items. Current size: ${this._data.size}/${this._maxCapacity}`)}async clear(){this._data.clear(),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id}))}}}class zm{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"childRegistration");l(this,"model");this.type=e,this.model=s,this.childRegistration=r}get factory(){return ae.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return _e(this.type)}}class Vm{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"model");l(this,"childRegistration");this.type=e,this.model=s,this.childRegistration=r}get factory(){return ae.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return _e(this.type)}}class Cl{constructor(){l(this,"_token");M.makeAutoObservable(this),C("token",e=>{this.token=e==null?void 0:e.body})}get token(){return this._token}set token(e){this._token=e}}class Dl{constructor(){l(this,"routes",[]);l(this,"openApiRoutes",[])}use(e,s,...r){this.routes.push({method:e,path:s,middlewares:r});const o=this.extractOpenApiParams(s);this.openApiRoutes.push({method:e,path:s,parameters:o})}remove(e,s){const r=this.routes.length;return this.routes=this.routes.filter(o=>!(o.method===e&&o.path===s)),this.openApiRoutes=this.openApiRoutes.filter(o=>!(o.method===e&&o.path===s)),r-this.routes.length}removeAllForPath(e){const s=this.routes.length;return this.routes=this.routes.filter(r=>r.path!==e),this.openApiRoutes=this.openApiRoutes.filter(r=>r.path!==e),s-this.routes.length}getRoutes(){return this.routes.map(e=>({method:e.method,path:e.path}))}async handle(e,s){var a;const{path:r,query:o,params:n}=this.extractPathParams(e.path),i={...e,params:n,query:o};for(const c of this.routes){const u=this.matchRoute(c.path,r);if(c.method===e.method&&u){i.params=u;let d=0;const h=async()=>{if(d<c.middlewares.length){const f=c.middlewares[d++];await f(i,s,h)}};await h();return}}(a=s.status)==null||a.call(s,404).send({error:"Route not found"})}extractOpenApiParams(e){return e.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const e={};for(const s of this.openApiRoutes)e[s.path]||(e[s.path]={}),e[s.path][s.method.toLowerCase()]={summary:s.description||`Handles ${s.method} ${s.path}`,parameters:s.parameters||[],responses:{200:{description:"Successful response"}}};return{openapi:"3.0.0",info:{title:"Kos Router API",version:"1.0.0",description:"Dynamically generated OpenAPI documentation"},paths:e}}extractPathParams(e){const[s,r]=e.split("?"),o=this.parseQueryParams(r);for(const n of this.routes){const i=this.matchRoute(n.path,s);if(i)return{path:s,query:o,params:i}}return{path:s,query:o,params:{}}}matchRoute(e,s){const r=e.split("/").filter(Boolean),o=s.split("/").filter(Boolean);if(r.length!==o.length)return null;const n={};for(let i=0;i<r.length;i++)if(r[i].startsWith(":"))n[r[i].slice(1)]=decodeURIComponent(o[i]);else if(r[i]!==o[i])return null;return n}parseQueryParams(e){return e?e.split("&").reduce((s,r)=>{const[o,n]=r.split("=").map(decodeURIComponent);return s[o]=n??"",s},{}):{}}}const xl=m.createLogger({name:"intent-service"}),Gm=t=>{cn(`/kos/intent/${t.type}`)?q(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):xl.info(`No subscribers for intent ${t.type}. Intent not sent.`)},Ym=async t=>new Promise(e=>{const{type:s,options:r}=t;if(cn(`/kos/intent/${t.type}`)){const o=ut(),{unsubscribe:n}=C(o,a=>{clearTimeout(i),n(),a&&(a.headers=a.headers||{},a.headers["kos.intent.type"]=s,a.headers.responseId=o),e([null,{body:a==null?void 0:a.body,payload:a}])}),i=setTimeout(()=>{n(),e([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);q(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else xl.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),Pe=m.createLogger({name:"app-startup-service"});async function Al(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=e;if(t.length===0)return Pe.warn("No app IDs provided to waitForAppsToStart"),!0;Pe.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const n=t.map(c=>`/kos/app/started/${c}`),i=await dn(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>al),[u,d]=await c.get("/api/kos/apps/started");return u?(Pe.error("Error fetching started apps:",u),[]):d}catch(c){Pe.error("Failed to fetch app startup status:",c)}return[]},shouldUseFetchedState:c=>t.every(u=>{const d=c.find(h=>h.appId===u);return!(!d||!d.started||o&&!d.postStarted)}),timeout:s}),a=t.filter(c=>{const u=i.find(d=>d.appId===c);return!!(!u||!u.started||o&&!u.postStarted)});if(a.length>0){const c=`Apps not started: ${a.join(", ")}`;if(Pe.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return Pe.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(Pe.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function Wm(t,e={}){return Al([t],e)}async function Qm(t,e=!1){const s={};try{const r=await exports.kosFetch("kos:///api/kos/apps/started");if(!r.ok)return t.forEach(i=>s[i]=!1),s;const o=await r.json(),n=(o==null?void 0:o.data)??[];t.forEach(i=>{const a=n.find(c=>c.appId===i);s[i]=(a==null?void 0:a.started)===!0&&(!e||(a==null?void 0:a.postStarted)===!0)})}catch(r){Pe.error("Failed to check app startup status:",r),t.forEach(o=>s[o]=!1)}return s}async function Zm(){try{const t=await exports.kosFetch("kos:///api/kos/apps/started");if(!t.ok)return[];const e=await t.json();return(e==null?void 0:e.data)??[]}catch(t){return Pe.error("Failed to fetch started apps:",t),[]}}const Bo=M.when,Rn=M.computed,X=M.runInAction,Y=M.autorun,Rl=M.reaction,Pn=M.observable,kn="Not Assigned",Xm="kos.trouble.added",Jm="kos.trouble.removed";var Ee=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t))(Ee||{}),Ts=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(Ts||{});const Pl=m.createLogger({name:"config-bean-service",group:"Services"}),Ln=exports.BASE_URL,kl=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:ey,getOne:ty}=oe.build({destinationAddress:"",basePath:`${Ln}/kos/config/`}),Ll=async(t,e,s="/api/kos/config")=>(Pl.debug(`sending modify request for ConfigBean: ${t}`),ey({model:e,urlOverride:`${Ln}${s}/${t}`})),Fl=async(t,e="/api/kos/config")=>(Pl.debug(`sending get request for ConfigBean: ${t}`),await ty({urlOverride:`${Ln}${e}/details/${t}/15`})),Fn=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",Jr=t=>{try{const e=Number(t);return!isNaN(e)}catch{return!1}};function Nl(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function Ul(t,e="",s={}){for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=e?`${e}.${r}`:r;typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])?Ul(t[r],o,s):s[o]=t[r]}return s}const jl=(t,e)=>{const s=t.details[0].bean||Nl(t.details[0].scopes),r=Ul(s);M.runInAction(()=>{const o={...r};e.props.setValues(o)})},Bl=(t,e)=>{M.runInAction(()=>{t.changes.forEach(s=>{const r=s.attr;let o=s.currentValue,n=s.previousValue;typeof o=="string"&&Fn(o)&&(o=o.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof o=="string"&&Jr(o)&&(o=Number(o),n=Number(n)),e.props[r]=o,e.prevProps[r]=n})})},Hl=t=>Object.fromEntries(t.props.entries),sy=t=>e=>s=>t.build(e,s);var ry=Object.defineProperty,oy=Object.getOwnPropertyDescriptor,Kl=(t,e,s,r)=>{for(var o=r>1?void 0:r?oy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ry(e,s,o),o};function ny(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const Nn="config-bean-model",sr=m.getLogger(Nn),iy=dt("path");let vr=class{constructor(t,e){l(this,"_modifyConfigBean");l(this,"_getConfigBean");l(this,"_schema");l(this,"id");l(this,"path");l(this,"props");l(this,"prevProps");l(this,"serviceBasePath");Object.assign(this,e),this.id=t,this.path=e.path,this.serviceBasePath=e.serviceBasePath;const{modifyConfigBean:s=Ll,getConfigBean:r=Fl}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=Ie(),this.prevProps=Ie()}get values(){return this.props.values}async ready(){sr.debug(`readying config bean ${this.path}`),sr.debug(`complete readying config bean ${this.path}`)}async load(){sr.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;jl(e,this),sr.debug(this.values);const s=t==null?void 0:t.data.details[0].schema;X(()=>{s&&(this._schema=s)})}}get schemaKeys(){var t;return Object.keys(((t=this._schema)==null?void 0:t.schema)||{})}getSchemaForProperty(t){var s,r;if(this.schemaKeys.includes(t))return(s=this._schema)==null?void 0:s.schema[t];const e=ny(this.schemaKeys,t);if(e)return(r=this._schema)==null?void 0:r.schema[e]}async updateProperty(t,e){this.props[t]=e,await this.updateConfigBean()}async updateConfigBean(){const t=Hl(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){Bl(t,this)}};Kl([B({topic:`/kos/config/${iy}`,websocket:!0})],vr.prototype,"handleConfigBeanUpdated",1);vr=Kl([R(Nn)],vr);const Os=new ve({class:vr,type:Nn}),eo=({path:t,lazy:e,serviceBasePath:s})=>(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:Os.type,id:`${Os.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:x.INIT,lazy:e}},{URL:ql}=ce(),{getOne:ay,getAll:cy}=oe.build({basePath:`${ql}/api/kos/regions/info`}),zl=async()=>{try{return await ay({})}catch{return}},Vl=async()=>{try{return await cy({urlOverride:`${ql}/api/kos/regions`})}catch{return}},ly=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:zl,getRegions:Vl},Symbol.toStringTag,{value:"Module"}));var de=(t=>(t[t.family=0]="family",t[t.scale=1]="scale",t[t.offset=2]="offset",t[t.decimals=3]="decimals",t[t.alias=4]="alias",t[t.system=5]="system",t))(de||{});const Gl={s:["time",1,0,0],second:["time",1,0,0],m:["time",1/60,0,0],minute:["time",1/60,0,0],h:["time",1/3600,0,0],hour:["time",1/3600,0,0],day:["time",1/86400,0,0],week:["time",1/604800,0,0],month:["time",1/2628e3,0,0],year:["time",1/31536e3,0,0],default:["time",1/.001,0,0],ms:["time",1/.001,0,0],millisecond:["time",1/.001,0,0],microsecond:["time",1/1e-6,0,0],nanosecond:["time",1/1e-9,0,0],picosecond:["time",1/1e-12,0,0]};function uy(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return o[n.name]=i,n.alias&&(o[n.alias]=i),o},{...Gl});return{...t,...r}}function dy(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{},a=i[s]||{};i[s]=a;const c=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return a[n.name]=c,n.alias&&(a[n.alias]=c),Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,o},{time:{[s]:{...Gl}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function hy(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{};return Object.hasOwn(n,"default")&&(i[s]=n.name),o[n.measure]=i,o},{time:{[s]:"millisecond"}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}var fy=Object.defineProperty,py=Object.getOwnPropertyDescriptor,Un=(t,e,s,r)=>{for(var o=r>1?void 0:r?py(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&fy(e,s,o),o};const hr="region-info-model",es=m.createLogger({name:"region-info-model"});let Is=class{constructor(t){l(this,"id");l(this,"unitSystemMap");l(this,"measureMap");l(this,"defaultMeasureMap");l(this,"regionMap");l(this,"timeFormats");l(this,"dateFormats");l(this,"unitSystems");l(this,"regionSource");l(this,"region");l(this,"regions",[]);l(this,"timeZoneMap",{});this.id=t,this.unitSystems={},this.unitSystemMap={},this.measureMap={},this.defaultMeasureMap={},this.timeFormats={},this.regions=[],this.dateFormats={},this.timeZoneMap={},this.regionMap={}}get availableRegions(){return this.regions}get defaultUnitSystem(){return String(this.regionSource.props.unitSystemId).toLowerCase()||""}get unitSystemId(){return this.defaultUnitSystem}get timeFormatId(){const t=this.regionSource.props.timeFormatId;if(!t)return"";const e=String(t),s=this.timeFormats[e];return s?String(s.id):""}get selectedTimeFormat(){const t=this.timeFormatId;return t?String(this.timeFormats[t].format):"HH:mm:ss"}get is12HourTimeFormat(){const t=this.timeFormatId;return t?this.timeFormats[t].ampm:!0}get dateFormatId(){const t=this.regionSource.props.dateFormatId;if(!t)return"";const e=String(t);return e?this.dateFormats[e].id:""}get selectedDateFormat(){const t=this.dateFormatId;return t?this.dateFormats[t].format:""}get selectedDateOrder(){const t=this.dateFormatId;return t?this.dateFormats[t].order.toLowerCase():"dmy"}get selectedCountry(){return this.regionSource.props.country||"en"}get selectedTimeZone(){return this.regionSource.props.timeZone||""}get timeZones(){return this.regionId?this.timeZoneMap[this.regionId]||[]:[]}get allTimeZones(){return Intl.supportedValuesOf("timeZone")}get regionId(){return this.region.props.regionId||""}get selectedRegion(){return this.regionMap[this.regionId]}get selectedUnitSystem(){return String(this.regionSource.props.unitSystemId)||""}get timeFormatOptions(){return Object.keys(this.timeFormats).map(t=>({id:t,format:this.timeFormats[t].format,ampm:this.timeFormats[t].ampm}))}get dateFormatOptions(){return Object.keys(this.dateFormats).map(t=>({id:t,format:this.dateFormats[t].format,order:this.dateFormats[t].order}))}get unitSystemOptions(){return Object.keys(this.unitSystems).map(t=>({id:t,name:t}))}setSelectedTimeFormat(t){if(!this.timeFormatOptions.find(e=>e.id===t))throw Error(`Invalid time format id. Must be one of ${this.timeFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("timeFormatId",t)}setSelectedDateFormat(t){if(!this.dateFormatOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.dateFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("dateFormatId",t)}setSelectedUnitSystem(t){if(!this.unitSystemOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.unitSystemOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("unitSystemId",t)}getUnitSystem(t){if(!t)return this.defaultUnitSystem;const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[de.system]}getUnitMeasure(t){const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[de.family]}getDefaultUnitDecimalPlaces(t,e,s){if(!t||!e)throw Error("Measure and unit system are required");const r=s==="drt"?"second":s,o=this.measureMap[t];if(!o)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const n=o[e.toLowerCase()];if(!n)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(o).join(", ")}`);const i=n[r||"default"];if(!i)throw Error(`No unit "${r||"default"}" found for measure: ${t} and unit system: ${e}. Unit should come from list of units: ${Object.keys(n).join(", ")}`);return i[de.decimals]}getDefaultUnitForMeasure(t,e){if(!t||!e)throw Error("Measure and unit system are required");const s=this.defaultMeasureMap[t];if(!s)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const r=s[e.toLowerCase()];if(!r)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(s).join(", ")}`);return r}convertByUnit(t,e,s){if(e[de.family]!==s[de.family])throw new Error(`Cannot convert between units of different families: ${e[de.family]} and ${s[de.family]}`);const r=e[de.offset],o=e[de.scale],n=s[de.scale],i=s[de.offset],a=s[de.decimals];return((t-r)/(o/n)+i).toFixed(a)}convertByUnitName(t,e,s){const r=this.unitSystemMap[e],o=this.unitSystemMap[s];if(!r||!o)throw new Error(`No unit found with name: ${e} or ${s}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return this.convertByUnit(t,r,o)}convert(t,e,s){var a,c;if(e.unit&&s.unit)return this.convertByUnitName(t,e.unit,s.unit);const r=e.unit||"",o=s.unit||"";let n=this.unitSystemMap[r],i=this.unitSystemMap[o];if(!i&&s.measure&&s.system){const u=this.measureMap[s.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(a=u[s.system])==null?void 0:a.default,i||es.info("Could not find default unit for measure",s.measure)}if(!n&&e.measure&&e.system){const u=this.measureMap[e.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(c=u[e.system])==null?void 0:c.default,n||es.info("Could not find default unit for measure",e.measure)}return!n||!i?(es.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,n,i)}async init(){es.debug("initializing region info")}async load(){es.debug("loading region info");const t=await Vl();t&&(this.regions=t.data.map(s=>s.id),this.timeZoneMap=t.data.reduce((s,r)=>({...s,[r.id]:r.timeZones}),this.timeZoneMap),this.regionMap=t.data.reduce((s,r)=>({...s,[r.id]:r}),{}));const e=await zl();e&&(this.unitSystems=e.data.unitSystems.reduce((s,r)=>{const o={id:r.id,name:r.id};return s[r.id]=o,s},this.unitSystems),this.unitSystemMap=e.data.unitSystems.reduce(uy,{}),this.measureMap=e.data.unitSystems.reduce(dy,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(hy,{}),this.timeFormats=e.data.timeFormats.reduce((s,r)=>({...s,[r.id]:r}),{}),this.dateFormats=e.data.dateFormats.reduce((s,r)=>({...s,[r.id]:r}),{}))}async ready(){var t,e;await((e=(t=this.regionSource).ready)==null?void 0:e.call(t))}};Un([eo({path:"kos:service:region:settings"})],Is.prototype,"regionSource",2);Un([eo({path:"kos:service:region"})],Is.prototype,"region",2);Is=Un([R(hr)],Is);const re={registration:{[hr]:{class:Is,singleton:!0}},type:hr,factory:ae.Singleton.create(hr)},wr=({source:t,defaultSystem:e="si",defaultMeasure:s})=>{let r={system:e,measure:s};return typeof t=="string"?r={...r,unit:t}:r={...r,...t},r},jn=(t,e,s)=>{const{model:r}=$e(re.type);if(!r)throw new Error("RegionInfo model not found");if(!br(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=wr({source:e}),i=wr({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(t,n,i)};function Yi(t,e,s){const r=e.toLowerCase().replace(/_/g,"-").replace(/s$/,""),o=new Intl.NumberFormat().resolvedOptions().locale??"en-US";try{const n=(s==null?void 0:s.mode)||"long",i=(s==null?void 0:s.maxDecimals)??2,a=(s==null?void 0:s.minDecimals)??0;return new Intl.NumberFormat(o,{style:"unit",unit:r,unitDisplay:n,minimumFractionDigits:a,maximumFractionDigits:i}).format(t)}catch{return e}}const gy=(t,e,s,r)=>{const o=jn(t,e,s),n=wr({source:e}),{model:i}=$e(re.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},u=wr({source:s||c,defaultMeasure:i.getUnitMeasure(n.unit||"")}),d=i.getDefaultUnitForMeasure(a,u.system),h=i.getDefaultUnitDecimalPlaces(a,u.system),f={...r,minDecimals:(r==null?void 0:r.minDecimals)??h,maxDecimals:(r==null?void 0:r.maxDecimals)??h};return{value:o,unit:d||n.unit||"",display:Yi(o,d||n.unit||"",{...f,mode:"long"}),shortDisplay:Yi(o,d||n.unit||"",{...f,mode:"short"})}};function Wi({start:t,end:e,count:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<2)throw new Error("Count should be at least 2 for distribution.");if(t>=e)throw new Error("Start should be less than end.");const o=(e-t)/(s-1),n=[];for(let i=0;i<s;i++){const a=Math.round(t+i*o);n.push(a.toFixed(r))}return n}function Qi({start:t,end:e,interval:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<=0)throw new Error("Interval should be a positive number.");if(t>=e)throw new Error("Start should be less than end.");const o=[];let n=t;for(;n<=e;)o.push(n.toFixed(r)),n+=s;return o[o.length-1]!==e.toString()&&o.push(e.toString()),o}const vt=(t,e)=>s=>!t||!e?s:Jr(s)?jn(Number(s),t,e):s,my=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return Wi(t.options).map(vt(s,r));if(t.options.type==="rangeInterval")return Qi(t.options).map(vt(s,r));if(t.options.type==="list"){const{list:o}=t.options;return o.map(vt(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return Wi(t.options.unitSystems[e]).map(vt(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return Qi(t.options.unitSystems[e]).map(vt(s,r));if(t.options.type==="unitSystemList"&&e){const{list:o}=t.options.unitSystems[e];return o.map(vt(s,r))}}return[]},yy=(t,e)=>{if(!((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options)))return t.options.type==="unitSystemRangeCount"&&e?{type:"rangeCount",...t.options.unitSystems[e]}:t.options.type==="unitSystemRangeInterval"&&e?{type:"rangeInterval",...t.options.unitSystems[e]}:t.options.type==="unitSystemList"&&e?{type:"list",...t.options.unitSystems[e]}:t.options.type==="unitSystemKeypad"&&e?{type:"keypad",...t.options.unitSystems[e]}:t.options};var by=Object.defineProperty,vy=Object.getOwnPropertyDescriptor,Bn=(t,e,s,r)=>{for(var o=r>1?void 0:r?vy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&by(e,s,o),o};function wy(t){return(t==null?void 0:t.type)==="enum"}function Ey(t){switch(t){case"s":return"second";case"ms":return"millisecond";case"min":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"m":return"month";case"y":return"year";case"ml":return"milliliter";default:return t}}function My(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return Ke.format(r,e)}const fr="config-bean-prop-model",wt=m.createLogger({name:"config-bean-prop-model"}),Ty=dt("path"),_y=dt("serviceBasePath");let $s=class{constructor(t,e){l(this,"id");l(this,"path");l(this,"attribute");l(this,"converter");l(this,"formatter");l(this,"optionsExpander");l(this,"serviceBasePath");l(this,"regionInfo");l(this,"bean");this.id=t,this.path=e.path,this.attribute=e.attribute,this.converter=e.converter,this.formatter=e.formatter,this.serviceBasePath=e.serviceBasePath,this.optionsExpander=e.optionsExpander}getDefaultUnitDecimalPlaces(t,e,s){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return kl(this.displayOptions)?this.displayOptions.decimals:this.regionInfo.getDefaultUnitDecimalPlaces(t,e,s)}getDefaultUnitForMeasure(t,e){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return this.regionInfo.getDefaultUnitForMeasure(t,e)}get schemaType(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.type?t.type:"String"}get schemaFormat(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.format?Ey(t.format):""}get options(){var i;const t=this.regionInfo.defaultUnitSystem,e=this.getConverter(),s=((i=e==null?void 0:e.to)==null?void 0:i.system)??t,r=this.bean.getSchemaForProperty(this.attribute),o=wy(r)?r.values:my(r,s,e==null?void 0:e.from,e==null?void 0:e.to),n=o.length>0?o.map(a=>({label:a,value:a})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,o):this.optionsExpander:n}convertUnit(t,e,s){const r=(t==null?void 0:t.measure)||s,o=(t==null?void 0:t.system)||e,n=t==null?void 0:t.unit;return{measure:r,system:o,unit:n}}getConverterUnits(){const t=this.regionInfo.defaultUnitSystem,e=this.getConverter();if(!e)throw Error("No converter defined");const s=e.measure,r=this.convertUnit(e.from,"si",s),o=this.convertUnit(e.to,t,s);return{backend:r,display:o}}set value(t){this.updateProperty(t)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var o,n;const t=this.value,e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=(s==null?void 0:s.measure)||((o=s==null?void 0:s.to)==null?void 0:o.measure);if(!isNaN(t)&&s&&r){const i=this.getDefaultUnitDecimalPlaces(r,e,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const c=this.getFormatterOptions(s);if(c){let u=String(t);return u=c.formatToParts(Number(t))[0].value,Number(u)}}catch(c){wt.info(`error formatting value ${t}`,c)}return Number(t).toFixed(i)}return t}get previousValue(){return this.getValue(!1)}getValue(t){const e=this.bean[t?"props":"prevProps"][this.attribute];if(typeof e=="boolean")return e;if(this.getConverter()&&!isNaN(e)){const{backend:r,display:o}=this.getConverterUnits();return this.regionInfo.convert(Number(e),r,o)}return e||""}async activate(){wt.debug(`activating config bean ${this.id}`)}get displayValue(){const t=this.value;if(typeof t=="boolean")return String(t);if(this.schemaFormat==="drt"){const s=this.regionInfo.is12HourTimeFormat?"h:mm:ss a":"HH:mm:ss";return My(t,s)}if(!isNaN(t))try{const e=this.getConverter(),s=this.getFormatterOptions(e);if(s){let r=String(t);return r=s.format(Number(t)),r}}catch(e){wt.error(`error formatting value ${t}`,e)}return String(t)}get unit(){const t=this.getConverter();if(!isNaN(this.value)){const e=this.getFormatterOptions(t);if(e){const r=e.formatToParts(Number(this.value)).find(o=>o.type==="unit");return(r==null?void 0:r.value)??this.getDefaultUnit(t)}}return this.getDefaultUnit(t)}get displayOptions(){var o;const t=this.bean.getSchemaForProperty(this.attribute),e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=((o=s==null?void 0:s.to)==null?void 0:o.system)??e;return yy(t,r)}getMeasureFromFormat(){const t=this.schemaFormat;return t?this.regionInfo.getUnitMeasure(t):""}getConverterFromFormat(){const t=this.getMeasureFromFormat();if(t){const e=this.regionInfo.selectedUnitSystem;return{unit:this.schemaFormat||this.regionInfo.getDefaultUnitForMeasure(t,e),measure:t}}return{}}getDefaultUnit(t){var r,o;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure;return s?((r=t==null?void 0:t.to)==null?void 0:r.unit)||this.getDefaultUnitForMeasure(s,((o=t==null?void 0:t.to)==null?void 0:o.system)||e):this.getConverterFromFormat().unit}getFormatterOptions(t){var n,i,a;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure,r=new Intl.NumberFormat().resolvedOptions().locale;let o=null;if(s||this.formatter){const c=s?{style:"unit",unit:this.getDefaultUnit(t)}:null,u=this.formatter||c;if(u){let d=typeof u=="function"?u(((n=t==null?void 0:t.to)==null?void 0:n.system)||e):u;s&&(d={unit:this.getDefaultUnit(t),...d},d.style==="unit"&&(d.maximumFractionDigits=d.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=t==null?void 0:t.to)==null?void 0:i.system)||e,(a=t==null?void 0:t.to)==null?void 0:a.unit)));try{o=new Intl.NumberFormat(r,{...d})}catch(h){wt.error(`error creating formatter ${d}. Returning the raw value`,h)}}else wt.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return o}getConverter(){var r,o,n,i,a,c,u,d,h,f,p;const{unit:t,measure:e}=this.getConverterFromFormat(),s=t==="drt"?"second":t;if(this.converter){const y=(r=this.converter)==null?void 0:r.measure,w=(n=(o=this.converter)==null?void 0:o.to)==null?void 0:n.measure,E=(a=(i=this.converter)==null?void 0:i.from)==null?void 0:a.measure,_=y||w||E||e,L=((u=(c=this.converter)==null?void 0:c.to)==null?void 0:u.unit)||this.regionInfo.getDefaultUnitForMeasure(_,((h=(d=this.converter)==null?void 0:d.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),U=((p=(f=this.converter)==null?void 0:f.to)==null?void 0:p.system)??this.regionInfo.getUnitSystem(L),I=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:I,...this.converter.from},to:{...this.converter.to,unit:L,system:U},measure:_}}if(s&&e){const y=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),w=this.regionInfo.getUnitSystem(s),E=this.regionInfo.getUnitSystem(y);return{measure:e,to:{unit:w===E?s:y}}}}async updateProperty(t){wt.debug(`updating property ${this.attribute} with value ${t}`);let e=t;if(this.getConverter()&&!isNaN(e)){const{backend:o,display:n}=this.getConverterUnits();e=this.regionInfo.convert(Number(e),n,o)}const r=Array.isArray(e)?JSON.stringify(e):String(e);await this.bean.updateProperty(this.attribute,r)}};Bn([Ht({modelType:re.type})],$s.prototype,"regionInfo",2);Bn([eo({path:Ty,serviceBasePath:_y})],$s.prototype,"bean",2);$s=Bn([R(fr)],$s);const ft={registration:{[fr]:{class:$s,singleton:!1}},type:fr,factory:ae.Factory.create(fr)};function Sy(t){const{path:e,attribute:s,converter:r,formatter:o,lazy:n,optionsExpander:i,serviceBasePath:a}=t,c=r;return c&&(typeof c!="function"&&typeof c.from=="string"&&(c.from={unit:c.from}),typeof c!="function"&&typeof c.to=="string"&&(c.to={unit:c.to})),(u,d)=>{u[F]=u[F]||{},u[F][d]={modelType:ft.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:x.INIT,lazy:n}}}const Yl="future-model",zt=Kt(Yl),to=m.createLogger({name:"future-service",group:"Services"}),{isMock:Oy,URL:qs}=ce();var Ge=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(Ge||{});const{getAll:Iy,modifyModel:$y,addModel:Cy,deleteModel:Dy,postModel:xy}=oe.build({destinationAddress:"",basePath:`${qs}/api/future`,mock:Oy}),Ay=async()=>await Iy({}),Wl=async(t,e="/api/kos/future")=>(to.info(`sending delete request for Future: ${t}`),await Dy({id:t,urlOverride:`${qs}${e}/${t}`})),Ql=async(t,e="/api/kos/future")=>(to.info("sending add request for Future"),await Cy({model:t,urlOverride:`${qs}${e}`})),Ry=async(t,e,s="/api/kos/future")=>(to.info(`sending modify request for Future: ${t}`),$y({model:e,id:t,urlOverride:`${qs}${s}/${t}`})),Zl=async(t,e="/api/kos/future")=>(to.info(`sending cancel request for Future: ${t}`),xy({urlOverride:`${qs}${e}/${t}/cancel`,ordered:!0,model:{}})),Hn=t=>({id:String(t.id),progress:t.progress,remainingTimeMs:t.remainingTimeMs,endState:t.endState,reason:t.reason,clientData:t.clientData,reasonData:t.reasonData,note:t.note,tracker:t.tracker}),Kn=(t,e)=>{m.debug(`future dto ${t.id} end state ${t.endState}`),m.debug(`future model ${e.id} end state ${e.endState}`),e.endState?m.debug(`future model ${e.id} is already complete`):(m.debug(`updating future model ${e.id}`),M.runInAction(()=>{const s=Hn(t);X(()=>{Object.keys(s).forEach(r=>{r==="id"?(e.futureId=s.id,s.tracker||(e.id=s.id)):r==="tracker"?e.id=s.tracker:e[r]=s[r]})})}))},Xl=t=>e=>s=>t.build(String(e),s),qn=t=>e=>Ol(Hn,Xl(t)(e.tracker||e.id))(e);var Py=Object.defineProperty,ky=Object.getOwnPropertyDescriptor,Jl=(t,e,s,r)=>{for(var o=r>1?void 0:r?ky(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Py(e,s,o),o};const Oo=m.getLogger(zt.type);let Er=class{constructor(t,e,s){l(this,"logger");l(this,"_cancelFuture");l(this,"futureId");Object.assign(this,e),this.logger=s.logger,this.id=t,this.futureId=e.id,this.namespace=e.namespace||"kos",this._cancelFuture=Zl,Bo(()=>this.status===Ge.Success||this.status===Ge.Fail,()=>{Oo.info(`Future ${this.id} has completed with status ${this.status}`),Oe(this)})}async load(){Oo.debug(`loading Future ${this.id}`)}unload(){Oo.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await Bo(()=>this.futureId!==kn),await this._cancelFuture(this.futureId,t)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,c;const t=this.remainingTimeMs||-1;if(t<0)return"";const e={year:1e3*60*60*24*365,month:1e3*60*60*24*30,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60,second:1e3};let s="second",r=0;for(const[u,d]of Object.entries(e))if(Math.abs(t)>=d){s=u,r=Math.round(t/d);break}const n=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(r,s);return n.length===3?`${((a=n[1])==null?void 0:a.value)??0} ${((c=n[2])==null?void 0:c.value)??""}`:"0 seconds"}handleFutureUpdated(t){this.logger.debug(`Future ${this.id} updated. future: ${t.id} endState: ${t.endState} progress: ${t.progress} remainingTimeMs: ${t.remainingTimeMs}`),Kn(t,this)}};Jl([B({topic:`kos.future/${gr}`})],Er.prototype,"handleFutureUpdated",1);Er=Jl([R(zt.type)],Er);const eu=Er,tu=Be();var Ly=Object.defineProperty,Fy=Object.getOwnPropertyDescriptor,su=(t,e,s,r)=>{for(var o=r>1?void 0:r?Fy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ly(e,s,o),o};const ru="browser-router-model",Ny="kos.http.request",Uy="kos.http.response";let Mr=class{constructor(t,e,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=t,this.logger=s.logger,this.router=new Dl}get id(){return this._id}async handleRequest(t,e){const s=e.headers["src-addr"],r=e.headers["dst-addr"],o=e.headers.url,n=e.headers.method,i=e.headers["request-id"],a={id:i,method:n,path:o,body:t};let c=200;const u={send:d=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(d),vl({msg:d,options:{responseId:i,destinationAddress:s,type:Uy,sourceAddress:r,status:c}})},status:function(d){return c=d,this}};if(a.path==="/openapi.json"){u.send(this.router.generateOpenApiSpec());return}await this.router.handle(a,u)}use(t,e,...s){this.router.use(t,e,...s)}remove(t,e){return this.router.remove(t,e)}removeAllForPath(t){return this.router.removeAllForPath(t)}getRoutes(){return this.router.getRoutes()}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};su([B({topic:Ny})],Mr.prototype,"handleRequest",1);Mr=su([R(ru)],Mr);const zn=new Se({class:Mr,type:ru}),ou="future-container-model",Ye=Kt(ou),nu=t=>qn(zt)(t),jy=t=>{const e=nu(t);return Ye.build(Ye.type,{}).addFutureModel(e),e},By=t=>Ye.build(Ye.type,{}).getFuture(String(t)),ct={buildFutureModel:nu,initiateFuture:jy,getFuture:By};var Hy=Object.defineProperty,Ky=Object.getOwnPropertyDescriptor,Vn=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ky(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Hy(e,s,o),o};const rr=m.getLogger(Ye.type);let Cs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_deleteFuture");l(this,"_addFuture");l(this,"_futures");l(this,"createModel");l(this,"deleteModel");const{deleteFuture:r=Wl,addFuture:o=Ql}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=t,this._futures=new xe,this.createModel=this.createFuture,this.deleteModel=this.removeFuture}get futures(){return this._futures.data}get models(){return this.futures}getFuture(t){return this._futures.getModel(t)}addFutureModel(t){this._futures.addModel(t)}removeFutureModel(t){this._futures.removeModel(t)}async removeFuture(t){try{await this._deleteFuture(t)}catch(e){rr.error("error deleting a Future"),rr.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=qn(zt)(s);return this.addFutureModel(r),r}}catch(e){throw rr.error("error creating a Future"),rr.error(e),e}}handleFutureUpdated(t,e){const s=ct.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),q(r,e.body,e.headers)}};Vn([De],Cs.prototype,"_futures",2);Vn([B({topic:"kos.future"})],Cs.prototype,"handleFutureUpdated",1);Cs=Vn([R(Ye.type)],Cs);const iu=Cs,{URL:zs}=ce(),{getOne:qy,postModel:zy,deleteModel:au}=oe.build({basePath:`${zs}/api/keyVal`}),Ho=m.createLogger({name:"key-value-service",group:"Services"}),cu=async(t,e)=>{await au({urlOverride:`${zs}/api/keyVal/${t}/${e}`,id:e})},lu=async(t,e,s)=>{const r=await zy({urlOverride:`${zs}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw Ho.error("Failed to update key-value data",r),new Error(`Failed to update key-value data for namespace ${t}`);return r.data},uu=async(t="studio")=>{Ho.debug(`Retrieving all key-value data for namespace: ${t}`);const e=await qy({urlOverride:`${zs}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw Ho.error("Failed to retrieve key-value data",e),new Error(`Failed to retrieve key-value data for namespace ${t}`);return e.data},Vy=async t=>{await au({urlOverride:`${zs}/api/keyVal/${t}`,id:""})},Gy=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:cu,deleteKeyValueNamespace:Vy,getKeyValue:uu,updateKeyValue:lu},Symbol.toStringTag,{value:"Module"}));var Yy=Object.defineProperty,Wy=Object.getOwnPropertyDescriptor,Gn=(t,e,s,r)=>{for(var o=r>1?void 0:r?Wy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Yy(e,s,o),o};const du="key-value-model";let Ds=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"namespace");l(this,"data");this.id=t,this.logger=s.logger,this.data=Ie(),this.namespace=e.namespace||"studio"}async init(){this.logger.debug(`initializing studio-state ${this.id}`)}async updateState(t,e){this.logger.debug(`updating studio-state ${t} with value ${e}`),e!==void 0?(await lu(this.namespace,t,e),this.data[t]=e):(await cu(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await uu(this.namespace);this.data.setValues(t)}handleStateUpdate(t){t.namespace===this.namespace&&(this.data[t.key]=t.value)}handleStateDelete(t){t.namespace===this.namespace&&(this.data[t.key]=void 0)}};Gn([B({topic:"/keyVal/set"})],Ds.prototype,"handleStateUpdate",1);Gn([B({topic:"/keyVal/remove"})],Ds.prototype,"handleStateDelete",1);Ds=Gn([R(du)],Ds);const Yn=new ve({class:Ds,type:du});var ge="INUMBER",Vt="IOP1",Gt="IOP2",Yt="IOP3",Le="IVAR",lt="IVARNAME",Dt="IFUNCALL",so="IFUNDEF",ie="IEXPR",Wn="IEXPREVAL",pt="IMEMBER",ro="IENDSTATEMENT",xt="IARRAY";function P(t,e){this.type=t,this.value=e??0}P.prototype.toString=function(){switch(this.type){case ge:case Vt:case Gt:case Yt:case Le:case lt:case ro:return this.value;case Dt:return"CALL "+this.value;case so:return"DEF "+this.value;case xt:return"ARRAY "+this.value;case pt:return"."+this.value;default:return"Invalid Instruction"}};function oo(t){return new P(Vt,t)}function He(t){return new P(Gt,t)}function hu(t){return new P(Yt,t)}function Ko(t,e,s,r,o){for(var n=[],i=[],a,c,u,d,h=0;h<t.length;h++){var f=t[h],p=f.type;if(p===ge||p===lt)Array.isArray(f.value)?n.push.apply(n,Ko(f.value.map(function(y){return new P(ge,y)}).concat(new P(xt,f.value.length)),e,s,r,o)):n.push(f);else if(p===Le&&o.hasOwnProperty(f.value))f=new P(ge,o[f.value]),n.push(f);else if(p===Gt&&n.length>1)c=n.pop(),a=n.pop(),d=s[f.value],f=new P(ge,d(a.value,c.value)),n.push(f);else if(p===Yt&&n.length>2)u=n.pop(),c=n.pop(),a=n.pop(),f.value==="?"?n.push(a.value?c.value:u.value):(d=r[f.value],f=new P(ge,d(a.value,c.value,u.value)),n.push(f));else if(p===Vt&&n.length>0)a=n.pop(),d=e[f.value],f=new P(ge,d(a.value)),n.push(f);else if(p===ie){for(;n.length>0;)i.push(n.shift());i.push(new P(ie,Ko(f.value,e,s,r,o)))}else if(p===pt&&n.length>0)a=n.pop(),n.push(new P(ge,a.value[f.value]));else{for(;n.length>0;)i.push(n.shift());i.push(f)}}for(;n.length>0;)i.push(n.shift());return i}function fu(t,e,s){for(var r=[],o=0;o<t.length;o++){var n=t[o],i=n.type;if(i===Le&&n.value===e)for(var a=0;a<s.tokens.length;a++){var c=s.tokens[a],u;c.type===Vt?u=oo(c.value):c.type===Gt?u=He(c.value):c.type===Yt?u=hu(c.value):u=new P(c.type,c.value),r.push(u)}else i===ie?r.push(new P(ie,fu(n.value,e,s))):r.push(n)}return r}function rt(t,e,s){var r=[],o,n,i,a,c,u;if(Qn(t))return Re(t,s);for(var d=t.length,h=0;h<d;h++){var f=t[h],p=f.type;if(p===ge||p===lt)r.push(f.value);else if(p===Gt)n=r.pop(),o=r.pop(),f.value==="and"?r.push(o?!!rt(n,e,s):!1):f.value==="or"?r.push(o?!0:!!rt(n,e,s)):f.value==="="?(a=e.binaryOps[f.value],r.push(a(o,rt(n,e,s),s))):(a=e.binaryOps[f.value],r.push(a(Re(o,s),Re(n,s))));else if(p===Yt)i=r.pop(),n=r.pop(),o=r.pop(),f.value==="?"?r.push(rt(o?n:i,e,s)):(a=e.ternaryOps[f.value],r.push(a(Re(o,s),Re(n,s),Re(i,s))));else if(p===Le)if(f.value in e.functions)r.push(e.functions[f.value]);else if(f.value in e.unaryOps&&e.parser.isOperatorEnabled(f.value))r.push(e.unaryOps[f.value]);else{var y=s[f.value];if(y!==void 0)r.push(y);else throw new Error("undefined variable: "+f.value)}else if(p===Vt)o=r.pop(),a=e.unaryOps[f.value],r.push(a(Re(o,s)));else if(p===Dt){for(u=f.value,c=[];u-- >0;)c.unshift(Re(r.pop(),s));if(a=r.pop(),a.apply&&a.call)r.push(a.apply(void 0,c));else throw new Error(a+" is not a function")}else if(p===so)r.push(function(){for(var w=r.pop(),E=[],_=f.value;_-- >0;)E.unshift(r.pop());var L=r.pop(),U=function(){for(var I=Object.assign({},s),S=0,Z=E.length;S<Z;S++)I[E[S]]=arguments[S];return rt(w,e,I)};return Object.defineProperty(U,"name",{value:L,writable:!1}),s[L]=U,U}());else if(p===ie)r.push(Qy(f,e));else if(p===Wn)r.push(f);else if(p===pt)o=r.pop(),r.push(o[f.value]);else if(p===ro)r.pop();else if(p===xt){for(u=f.value,c=[];u-- >0;)c.unshift(r.pop());r.push(c)}else throw new Error("invalid Expression")}if(r.length>1)throw new Error("invalid Expression (parity)");return r[0]===0?0:Re(r[0],s)}function Qy(t,e,s){return Qn(t)?t:{type:Wn,value:function(r){return rt(t.value,e,r)}}}function Qn(t){return t&&t.type===Wn}function Re(t,e){return Qn(t)?t.value(e):t}function Zn(t,e){for(var s=[],r,o,n,i,a,c,u=0;u<t.length;u++){var d=t[u],h=d.type;if(h===ge)typeof d.value=="number"&&d.value<0?s.push("("+d.value+")"):Array.isArray(d.value)?s.push("["+d.value.map(Zi).join(", ")+"]"):s.push(Zi(d.value));else if(h===Gt)o=s.pop(),r=s.pop(),i=d.value,e?i==="^"?s.push("Math.pow("+r+", "+o+")"):i==="and"?s.push("(!!"+r+" && !!"+o+")"):i==="or"?s.push("(!!"+r+" || !!"+o+")"):i==="||"?s.push("(function(a,b){ return Array.isArray(a) && Array.isArray(b) ? a.concat(b) : String(a) + String(b); }(("+r+"),("+o+")))"):i==="=="?s.push("("+r+" === "+o+")"):i==="!="?s.push("("+r+" !== "+o+")"):i==="["?s.push(r+"[("+o+") | 0]"):s.push("("+r+" "+i+" "+o+")"):i==="["?s.push(r+"["+o+"]"):s.push("("+r+" "+i+" "+o+")");else if(h===Yt)if(n=s.pop(),o=s.pop(),r=s.pop(),i=d.value,i==="?")s.push("("+r+" ? "+o+" : "+n+")");else throw new Error("invalid Expression");else if(h===Le||h===lt)s.push(d.value);else if(h===Vt)r=s.pop(),i=d.value,i==="-"||i==="+"?s.push("("+i+r+")"):e?i==="not"?s.push("(!"+r+")"):i==="!"?s.push("fac("+r+")"):s.push(i+"("+r+")"):i==="!"?s.push("("+r+"!)"):s.push("("+i+" "+r+")");else if(h===Dt){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());i=s.pop(),s.push(i+"("+a.join(", ")+")")}else if(h===so){for(o=s.pop(),c=d.value,a=[];c-- >0;)a.unshift(s.pop());r=s.pop(),e?s.push("("+r+" = function("+a.join(", ")+") { return "+o+" })"):s.push("("+r+"("+a.join(", ")+") = "+o+")")}else if(h===pt)r=s.pop(),s.push(r+"."+d.value);else if(h===xt){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());s.push("["+a.join(", ")+"]")}else if(h===ie)s.push("("+Zn(d.value,e)+")");else if(h!==ro)throw new Error("invalid Expression")}return s.length>1&&(e?s=[s.join(",")]:s=[s.join(";")]),String(s[0])}function Zi(t){return typeof t=="string"?JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"):t}function _t(t,e){for(var s=0;s<t.length;s++)if(t[s]===e)return!0;return!1}function Xn(t,e,s){s=s||{};for(var r=!!s.withMembers,o=null,n=0;n<t.length;n++){var i=t[n];i.type===Le||i.type===lt?!r&&!_t(e,i.value)?e.push(i.value):(o!==null&&(_t(e,o)||e.push(o)),o=i.value):i.type===pt&&r&&o!==null?o+="."+i.value:i.type===ie?Xn(i.value,e,s):o!==null&&(_t(e,o)||e.push(o),o=null)}o!==null&&!_t(e,o)&&e.push(o)}function Me(t,e){this.tokens=t,this.parser=e,this.unaryOps=e.unaryOps,this.binaryOps=e.binaryOps,this.ternaryOps=e.ternaryOps,this.functions=e.functions}Me.prototype.simplify=function(t){return t=t||{},new Me(Ko(this.tokens,this.unaryOps,this.binaryOps,this.ternaryOps,t),this.parser)};Me.prototype.substitute=function(t,e){return e instanceof Me||(e=this.parser.parse(String(e))),new Me(fu(this.tokens,t,e),this.parser)};Me.prototype.evaluate=function(t){return t=t||{},rt(this.tokens,this,t)};Me.prototype.toString=function(){return Zn(this.tokens,!1)};Me.prototype.symbols=function(t){t=t||{};var e=[];return Xn(this.tokens,e,t),e};Me.prototype.variables=function(t){t=t||{};var e=[];Xn(this.tokens,e,t);var s=this.functions;return e.filter(function(r){return!(r in s)})};Me.prototype.toJSFunction=function(t,e){var s=this,r=new Function(t,"with(this.functions) with (this.ternaryOps) with (this.binaryOps) with (this.unaryOps) { return "+Zn(this.simplify(e).tokens,!0)+"; }");return function(){return r.apply(s,arguments)}};var xs="TEOF",j="TOP",no="TNUMBER",pu="TSTRING",Fe="TPAREN",At="TBRACKET",io="TCOMMA",Jn="TNAME",ei="TSEMICOLON";function gu(t,e,s){this.type=t,this.value=e,this.index=s}gu.prototype.toString=function(){return this.type+": "+this.value};function z(t,e){this.pos=0,this.current=null,this.unaryOps=t.unaryOps,this.binaryOps=t.binaryOps,this.ternaryOps=t.ternaryOps,this.consts=t.consts,this.expression=e,this.savedPosition=0,this.savedCurrent=null,this.options=t.options,this.parser=t}z.prototype.newToken=function(t,e,s){return new gu(t,e,s??this.pos)};z.prototype.save=function(){this.savedPosition=this.pos,this.savedCurrent=this.current};z.prototype.restore=function(){this.pos=this.savedPosition,this.current=this.savedCurrent};z.prototype.next=function(){if(this.pos>=this.expression.length)return this.newToken(xs,"EOF");if(this.isWhitespace()||this.isComment())return this.next();if(this.isRadixInteger()||this.isNumber()||this.isOperator()||this.isString()||this.isParen()||this.isBracket()||this.isComma()||this.isSemicolon()||this.isNamedOp()||this.isConst()||this.isName())return this.current;this.parseError('Unknown character "'+this.expression.charAt(this.pos)+'"')};z.prototype.isString=function(){var t=!1,e=this.pos,s=this.expression.charAt(e);if(s==="'"||s==='"')for(var r=this.expression.indexOf(s,e+1);r>=0&&this.pos<this.expression.length;){if(this.pos=r+1,this.expression.charAt(r-1)!=="\\"){var o=this.expression.substring(e+1,r);this.current=this.newToken(pu,this.unescape(o),e),t=!0;break}r=this.expression.indexOf(s,r+1)}return t};z.prototype.isParen=function(){var t=this.expression.charAt(this.pos);return t==="("||t===")"?(this.current=this.newToken(Fe,t),this.pos++,!0):!1};z.prototype.isBracket=function(){var t=this.expression.charAt(this.pos);return(t==="["||t==="]")&&this.isOperatorEnabled("[")?(this.current=this.newToken(At,t),this.pos++,!0):!1};z.prototype.isComma=function(){var t=this.expression.charAt(this.pos);return t===","?(this.current=this.newToken(io,","),this.pos++,!0):!1};z.prototype.isSemicolon=function(){var t=this.expression.charAt(this.pos);return t===";"?(this.current=this.newToken(ei,";"),this.pos++,!0):!1};z.prototype.isConst=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&s!=="."&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(r in this.consts)return this.current=this.newToken(no,this.consts[r]),this.pos+=r.length,!0}return!1};z.prototype.isNamedOp=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(this.isOperatorEnabled(r)&&(r in this.binaryOps||r in this.unaryOps||r in this.ternaryOps))return this.current=this.newToken(j,r),this.pos+=r.length,!0}return!1};z.prototype.isName=function(){for(var t=this.pos,e=t,s=!1;e<this.expression.length;e++){var r=this.expression.charAt(e);if(r.toUpperCase()===r.toLowerCase()){if(e===this.pos&&(r==="$"||r==="_")){r==="_"&&(s=!0);continue}else if(e===this.pos||!s||r!=="_"&&(r<"0"||r>"9"))break}else s=!0}if(s){var o=this.expression.substring(t,e);return this.current=this.newToken(Jn,o),this.pos+=o.length,!0}return!1};z.prototype.isWhitespace=function(){for(var t=!1,e=this.expression.charAt(this.pos);(e===" "||e===" "||e===`
108
108
  `||e==="\r")&&(t=!0,this.pos++,!(this.pos>=this.expression.length));)e=this.expression.charAt(this.pos);return t};var Zy=/^[0-9a-f]{4}$/i;z.prototype.unescape=function(t){var e=t.indexOf("\\");if(e<0)return t;for(var s=t.substring(0,e);e>=0;){var r=t.charAt(++e);switch(r){case"'":s+="'";break;case'"':s+='"';break;case"\\":s+="\\";break;case"/":s+="/";break;case"b":s+="\b";break;case"f":s+="\f";break;case"n":s+=`
109
109
  `;break;case"r":s+="\r";break;case"t":s+=" ";break;case"u":var o=t.substring(e+1,e+5);Zy.test(o)||this.parseError("Illegal escape sequence: \\u"+o),s+=String.fromCharCode(parseInt(o,16)),e+=4;break;default:throw this.parseError('Illegal escape sequence: "\\'+r+'"')}++e;var n=t.indexOf("\\",e);s+=t.substring(e,n<0?t.length:n),e=n}return s};z.prototype.isComment=function(){var t=this.expression.charAt(this.pos);return t==="/"&&this.expression.charAt(this.pos+1)==="*"?(this.pos=this.expression.indexOf("*/",this.pos)+2,this.pos===1&&(this.pos=this.expression.length),!0):!1};z.prototype.isRadixInteger=function(){var t=this.pos;if(t>=this.expression.length-2||this.expression.charAt(t)!=="0")return!1;++t;var e,s;if(this.expression.charAt(t)==="x")e=16,s=/^[0-9a-f]$/i,++t;else if(this.expression.charAt(t)==="b")e=2,s=/^[01]$/i,++t;else return!1;for(var r=!1,o=t;t<this.expression.length;){var n=this.expression.charAt(t);if(s.test(n))t++,r=!0;else break}return r&&(this.current=this.newToken(no,parseInt(this.expression.substring(o,t),e)),this.pos=t),r};z.prototype.isNumber=function(){for(var t=!1,e=this.pos,s=e,r=e,o=!1,n=!1,i;e<this.expression.length&&(i=this.expression.charAt(e),i>="0"&&i<="9"||!o&&i===".");)i==="."?o=!0:n=!0,e++,t=n;if(t&&(r=e),i==="e"||i==="E"){e++;for(var a=!0,c=!1;e<this.expression.length;){if(i=this.expression.charAt(e),a&&(i==="+"||i==="-"))a=!1;else if(i>="0"&&i<="9")c=!0,a=!1;else break;e++}c||(e=r)}return t?(this.current=this.newToken(no,parseFloat(this.expression.substring(s,e))),this.pos=e):this.pos=r,t};z.prototype.isOperator=function(){var t=this.pos,e=this.expression.charAt(this.pos);if(e==="+"||e==="-"||e==="*"||e==="/"||e==="%"||e==="^"||e==="?"||e===":"||e===".")this.current=this.newToken(j,e);else if(e==="∙"||e==="•")this.current=this.newToken(j,"*");else if(e===">")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,">="),this.pos++):this.current=this.newToken(j,">");else if(e==="<")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,"<="),this.pos++):this.current=this.newToken(j,"<");else if(e==="|")if(this.expression.charAt(this.pos+1)==="|")this.current=this.newToken(j,"||"),this.pos++;else return!1;else if(e==="=")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,"=="),this.pos++):this.current=this.newToken(j,e);else if(e==="!")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,"!="),this.pos++):this.current=this.newToken(j,e);else return!1;return this.pos++,this.isOperatorEnabled(this.current.value)?!0:(this.pos=t,!1)};z.prototype.isOperatorEnabled=function(t){return this.parser.isOperatorEnabled(t)};z.prototype.getCoordinates=function(){var t=0,e,s=-1;do t++,e=this.pos-s,s=this.expression.indexOf(`
110
- `,s+1);while(s>=0&&s<this.pos);return{line:t,column:e}};z.prototype.parseError=function(t){var e=this.getCoordinates();throw new Error("parse error ["+e.line+":"+e.column+"]: "+t)};function H(t,e,s){this.parser=t,this.tokens=e,this.current=null,this.nextToken=null,this.next(),this.savedCurrent=null,this.savedNextToken=null,this.allowMemberAccess=s.allowMemberAccess!==!1}H.prototype.next=function(){return this.current=this.nextToken,this.nextToken=this.tokens.next()};H.prototype.tokenMatches=function(t,e){return typeof e>"u"?!0:Array.isArray(e)?_t(e,t.value):typeof e=="function"?e(t):t.value===e};H.prototype.save=function(){this.savedCurrent=this.current,this.savedNextToken=this.nextToken,this.tokens.save()};H.prototype.restore=function(){this.tokens.restore(),this.current=this.savedCurrent,this.nextToken=this.savedNextToken};H.prototype.accept=function(t,e){return this.nextToken.type===t&&this.tokenMatches(this.nextToken,e)?(this.next(),!0):!1};H.prototype.expect=function(t,e){if(!this.accept(t,e)){var s=this.tokens.getCoordinates();throw new Error("parse error ["+s.line+":"+s.column+"]: Expected "+(e||t))}};H.prototype.parseAtom=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.accept(Jn)||this.accept(j,s))t.push(new P(Le,this.current.value));else if(this.accept(no))t.push(new P(ge,this.current.value));else if(this.accept(pu))t.push(new P(ge,this.current.value));else if(this.accept(Fe,"("))this.parseExpression(t),this.expect(Fe,")");else if(this.accept(At,"["))if(this.accept(At,"]"))t.push(new P(xt,0));else{var r=this.parseArrayList(t);t.push(new P(xt,r))}else throw new Error("unexpected "+this.nextToken)};H.prototype.parseExpression=function(t){var e=[];this.parseUntilEndStatement(t,e)||(this.parseVariableAssignmentExpression(e),!this.parseUntilEndStatement(t,e)&&this.pushExpression(t,e))};H.prototype.pushExpression=function(t,e){for(var s=0,r=e.length;s<r;s++)t.push(e[s])};H.prototype.parseUntilEndStatement=function(t,e){return this.accept(ei)?(this.nextToken&&this.nextToken.type!==xs&&!(this.nextToken.type===Fe&&this.nextToken.value===")")&&e.push(new P(ro)),this.nextToken.type!==xs&&this.parseExpression(e),t.push(new P(ie,e)),!0):!1};H.prototype.parseArrayList=function(t){for(var e=0;!this.accept(At,"]");)for(this.parseExpression(t),++e;this.accept(io);)this.parseExpression(t),++e;return e};H.prototype.parseVariableAssignmentExpression=function(t){for(this.parseConditionalExpression(t);this.accept(j,"=");){var e=t.pop(),s=[],r=t.length-1;if(e.type===Dt){if(!this.tokens.isOperatorEnabled("()="))throw new Error("function definition is not permitted");for(var o=0,n=e.value+1;o<n;o++){var i=r-o;t[i].type===Le&&(t[i]=new P(ct,t[i].value))}this.parseVariableAssignmentExpression(s),t.push(new P(ie,s)),t.push(new P(so,e.value));continue}if(e.type!==Le&&e.type!==ft)throw new Error("expected variable for assignment");this.parseVariableAssignmentExpression(s),t.push(new P(ct,e.value)),t.push(new P(ie,s)),t.push(He("="))}};H.prototype.parseConditionalExpression=function(t){for(this.parseOrExpression(t);this.accept(j,"?");){var e=[],s=[];this.parseConditionalExpression(e),this.expect(j,":"),this.parseConditionalExpression(s),t.push(new P(ie,e)),t.push(new P(ie,s)),t.push(hu("?"))}};H.prototype.parseOrExpression=function(t){for(this.parseAndExpression(t);this.accept(j,"or");){var e=[];this.parseAndExpression(e),t.push(new P(ie,e)),t.push(He("or"))}};H.prototype.parseAndExpression=function(t){for(this.parseComparison(t);this.accept(j,"and");){var e=[];this.parseComparison(e),t.push(new P(ie,e)),t.push(He("and"))}};var Xy=["==","!=","<","<=",">=",">","in"];H.prototype.parseComparison=function(t){for(this.parseAddSub(t);this.accept(j,Xy);){var e=this.current;this.parseAddSub(t),t.push(He(e.value))}};var Jy=["+","-","||"];H.prototype.parseAddSub=function(t){for(this.parseTerm(t);this.accept(j,Jy);){var e=this.current;this.parseTerm(t),t.push(He(e.value))}};var eb=["*","/","%"];H.prototype.parseTerm=function(t){for(this.parseFactor(t);this.accept(j,eb);){var e=this.current;this.parseFactor(t),t.push(He(e.value))}};H.prototype.parseFactor=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.save(),this.accept(j,s)){if(this.current.value!=="-"&&this.current.value!=="+"){if(this.nextToken.type===Fe&&this.nextToken.value==="("){this.restore(),this.parseExponential(t);return}else if(this.nextToken.type===ei||this.nextToken.type===io||this.nextToken.type===xs||this.nextToken.type===Fe&&this.nextToken.value===")"){this.restore(),this.parseAtom(t);return}}var r=this.current;this.parseFactor(t),t.push(oo(r.value))}else this.parseExponential(t)};H.prototype.parseExponential=function(t){for(this.parsePostfixExpression(t);this.accept(j,"^");)this.parseFactor(t),t.push(He("^"))};H.prototype.parsePostfixExpression=function(t){for(this.parseFunctionCall(t);this.accept(j,"!");)t.push(oo("!"))};H.prototype.parseFunctionCall=function(t){var e=this.tokens.unaryOps;function s(n){return n.value in e}if(this.accept(j,s)){var r=this.current;this.parseAtom(t),t.push(oo(r.value))}else for(this.parseMemberExpression(t);this.accept(Fe,"(");)if(this.accept(Fe,")"))t.push(new P(Dt,0));else{var o=this.parseArgumentList(t);t.push(new P(Dt,o))}};H.prototype.parseArgumentList=function(t){for(var e=0;!this.accept(Fe,")");)for(this.parseExpression(t),++e;this.accept(io);)this.parseExpression(t),++e;return e};H.prototype.parseMemberExpression=function(t){for(this.parseAtom(t);this.accept(j,".")||this.accept(At,"[");){var e=this.current;if(e.value==="."){if(!this.allowMemberAccess)throw new Error('unexpected ".", member access is not permitted');this.expect(Jn),t.push(new P(ft,this.current.value))}else if(e.value==="["){if(!this.tokens.isOperatorEnabled("["))throw new Error('unexpected "[]", arrays are disabled');this.parseExpression(t),this.expect(At,"]"),t.push(He("["))}else throw new Error("unexpected symbol: "+e.value)}};function tb(t,e){return Number(t)+Number(e)}function sb(t,e){return t-e}function rb(t,e){return t*e}function ob(t,e){return t/e}function nb(t,e){return t%e}function ib(t,e){return Array.isArray(t)&&Array.isArray(e)?t.concat(e):""+t+e}function ab(t,e){return t===e}function cb(t,e){return t!==e}function lb(t,e){return t>e}function ub(t,e){return t<e}function db(t,e){return t>=e}function hb(t,e){return t<=e}function fb(t,e){return!!(t&&e)}function pb(t,e){return!!(t||e)}function gb(t,e){return _t(e,t)}function mb(t){return(Math.exp(t)-Math.exp(-t))/2}function yb(t){return(Math.exp(t)+Math.exp(-t))/2}function bb(t){return t===1/0?1:t===-1/0?-1:(Math.exp(t)-Math.exp(-t))/(Math.exp(t)+Math.exp(-t))}function vb(t){return t===-1/0?t:Math.log(t+Math.sqrt(t*t+1))}function wb(t){return Math.log(t+Math.sqrt(t*t-1))}function Eb(t){return Math.log((1+t)/(1-t))/2}function Xi(t){return Math.log(t)*Math.LOG10E}function Mb(t){return-t}function Tb(t){return!t}function _b(t){return t<0?Math.ceil(t):Math.floor(t)}function Sb(t){return Math.random()*(t||1)}function Ji(t){return ti(t+1)}function Ob(t){return isFinite(t)&&t===Math.round(t)}var Ib=4.7421875,Io=[.9999999999999971,57.15623566586292,-59.59796035547549,14.136097974741746,-.4919138160976202,3399464998481189e-20,4652362892704858e-20,-9837447530487956e-20,.0001580887032249125,-.00021026444172410488,.00021743961811521265,-.0001643181065367639,8441822398385275e-20,-26190838401581408e-21,36899182659531625e-22];function ti(t){var e,s;if(Ob(t)){if(t<=0)return isFinite(t)?1/0:NaN;if(t>171)return 1/0;for(var r=t-2,o=t-1;r>1;)o*=r,r--;return o===0&&(o=1),o}if(t<.5)return Math.PI/(Math.sin(Math.PI*t)*ti(1-t));if(t>=171.35)return 1/0;if(t>85){var n=t*t,i=n*t,a=i*t,c=a*t;return Math.sqrt(2*Math.PI/t)*Math.pow(t/Math.E,t)*(1+1/(12*t)+1/(288*n)-139/(51840*i)-571/(2488320*a)+163879/(209018880*c)+5246819/(75246796800*c*t))}--t,s=Io[0];for(var u=1;u<Io.length;++u)s+=Io[u]/(t+u);return e=t+Ib+.5,Math.sqrt(2*Math.PI)*Math.pow(e,t+.5)*Math.exp(-e)*s}function $b(t){return Array.isArray(t)?t.length:String(t).length}function ea(){for(var t=0,e=0,s=0;s<arguments.length;s++){var r=Math.abs(arguments[s]),o;e<r?(o=e/r,t=t*o*o+1,e=r):r>0?(o=r/e,t+=o*o):t+=r}return e===1/0?1/0:e*Math.sqrt(t)}function ta(t,e,s){return t?e:s}function Cb(t,e){return typeof e>"u"||+e==0?Math.round(t):(t=+t,e=-+e,isNaN(t)||!(typeof e=="number"&&e%1===0)?NaN:(t=t.toString().split("e"),t=Math.round(+(t[0]+"e"+(t[1]?+t[1]-e:-e))),t=t.toString().split("e"),+(t[0]+"e"+(t[1]?+t[1]+e:e))))}function Db(t,e,s){return s&&(s[t]=e),e}function xb(t,e){return t[e|0]}function Ab(t){return arguments.length===1&&Array.isArray(t)?Math.max.apply(Math,t):Math.max.apply(Math,arguments)}function Rb(t){return arguments.length===1&&Array.isArray(t)?Math.min.apply(Math,t):Math.min.apply(Math,arguments)}function Pb(t,e){if(typeof t!="function")throw new Error("First argument to map is not a function");if(!Array.isArray(e))throw new Error("Second argument to map is not an array");return e.map(function(s,r){return t(s,r)})}function kb(t,e,s){if(typeof t!="function")throw new Error("First argument to fold is not a function");if(!Array.isArray(s))throw new Error("Second argument to fold is not an array");return s.reduce(function(r,o,n){return t(r,o,n)},e)}function Lb(t,e){if(typeof t!="function")throw new Error("First argument to filter is not a function");if(!Array.isArray(e))throw new Error("Second argument to filter is not an array");return e.filter(function(s,r){return t(s,r)})}function Fb(t,e){if(!(Array.isArray(e)||typeof e=="string"))throw new Error("Second argument to indexOf is not a string or array");return e.indexOf(t)}function Nb(t,e){if(!Array.isArray(e))throw new Error("Second argument to join is not an array");return e.join(t)}function Ub(t){return(t>0)-(t<0)||+t}var sa=1/3;function jb(t){return t<0?-Math.pow(-t,sa):Math.pow(t,sa)}function Bb(t){return Math.exp(t)-1}function Hb(t){return Math.log(1+t)}function Kb(t){return Math.log(t)/Math.LN2}function pt(t){this.options=t||{},this.unaryOps={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh||mb,cosh:Math.cosh||yb,tanh:Math.tanh||bb,asinh:Math.asinh||vb,acosh:Math.acosh||wb,atanh:Math.atanh||Eb,sqrt:Math.sqrt,cbrt:Math.cbrt||jb,log:Math.log,log2:Math.log2||Kb,ln:Math.log,lg:Math.log10||Xi,log10:Math.log10||Xi,expm1:Math.expm1||Bb,log1p:Math.log1p||Hb,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc||_b,"-":Mb,"+":Number,exp:Math.exp,not:Tb,length:$b,"!":Ji,sign:Math.sign||Ub},this.binaryOps={"+":tb,"-":sb,"*":rb,"/":ob,"%":nb,"^":Math.pow,"||":ib,"==":ab,"!=":cb,">":lb,"<":ub,">=":db,"<=":hb,and:fb,or:pb,in:gb,"=":Db,"[":xb},this.ternaryOps={"?":ta},this.functions={random:Sb,fac:Ji,min:Rb,max:Ab,hypot:Math.hypot||ea,pyt:Math.hypot||ea,pow:Math.pow,atan2:Math.atan2,if:ta,gamma:ti,roundTo:Cb,map:Pb,fold:kb,filter:Lb,indexOf:Fb,join:Nb},this.consts={E:Math.E,PI:Math.PI,true:!0,false:!1}}pt.prototype.parse=function(t){var e=[],s=new H(this,new z(this,t),{allowMemberAccess:this.options.allowMemberAccess});return s.parseExpression(e),s.expect(xs,"EOF"),new Me(e,this)};pt.prototype.evaluate=function(t,e){return this.parse(t).evaluate(e)};var mu=new pt;pt.parse=function(t){return mu.parse(t)};pt.evaluate=function(t,e){return mu.parse(t).evaluate(e)};var ra={"+":"add","-":"subtract","*":"multiply","/":"divide","%":"remainder","^":"power","!":"factorial","<":"comparison",">":"comparison","<=":"comparison",">=":"comparison","==":"comparison","!=":"comparison","||":"concatenate",and:"logical",or:"logical",not:"logical","?":"conditional",":":"conditional","=":"assignment","[":"array","()=":"fndef"};function qb(t){return ra.hasOwnProperty(t)?ra[t]:t}pt.prototype.isOperatorEnabled=function(t){var e=qb(t),s=this.options.operators||{};return!(e in s)||!!s[e]};var zb=Object.defineProperty,Vb=Object.getOwnPropertyDescriptor,Gb=(t,e,s)=>e in t?zb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Yb=(t,e,s,r)=>{for(var o=r>1?void 0:r?Vb(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o},Wb=(t,e,s)=>(Gb(t,e+"",s),s);const Qb="kos-expression-evaluator-model";class Zb{constructor(e,s,r,o){l(this,"name");l(this,"expression");l(this,"expr");l(this,"getContextData",null);l(this,"_lastResult",{value:void 0});this.name=e,this.expression=s,this.expr=r,this.getContextData=o,this._lastResult={value:void 0,error:void 0}}get result(){return this._lastResult}updateResult(e){this._lastResult=e}evaluate(e){try{return{value:this.expr.evaluate(e),error:void 0}}catch(s){return{value:void 0,error:s instanceof Error?s.message:String(s)}}}}let Tr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"parser");l(this,"_data");l(this,"_expressions",new Map);l(this,"_results");l(this,"_contextRevision",0);this.id=t,this.logger=s.logger,this._data=Ie(),this._results=Ie(),this.parser=new pt}get data(){return this._data}get contextRevision(){return this._contextRevision}setContextData(t){this._data.setValues(t),X(()=>{this._contextRevision++,this.logger.debug("Context revision incremented to:",this._contextRevision)})}updateContextValue(t,e){this._data[t]=e}updateNestedValue(t,e){const s=t.split("."),r=s.pop();if(!r){this.logger.error(`Invalid path "${t}" - cannot be empty`);return}let o=this._data;for(const n of s)(o[n]===void 0||o[n]===null)&&(o[n]={}),o=o[n];o[r]=e,this.logger.debug(`Updated nested context value "${t}" to:`,e)}addModelToContext(t,e){this._data[t]=e}addExpression(t,e){try{const s=this.parser.parse(e),r=new Zb(t,e,s,()=>this.data);this._expressions.set(t,r),this.evaluateExpression(t),this.logger.debug(`Added expression "${t}": ${e}`)}catch(s){throw this.logger.error(`Failed to parse expression "${t}"`,s),s}}removeExpression(t){const e=this._expressions.delete(t);return e?(delete this._results[t],this.logger.debug(`Removed expression "${t}"`)):this.logger.warn(`Attempted to remove non-existent expression "${t}". Available expressions: [${this.expressionNames.join(", ")}]`),e}getExpression(t){const e=this._expressions.get(t);return e||this.logger.warn(`Expression "${t}" not found. Available expressions: [${this.expressionNames.join(", ")}]`),e}getExpressionValue(t){const e=this._expressions.get(t);if(!e){this.logger.warn(`Expression "${t}" not found. Available expressions: [${this.expressionNames.join(", ")}]`);return}return e.result}getCachedExpressionValue(t){const e=this._expressions.get(t);if(e)return e.result}get expressions(){return Array.from(this._expressions.values())}get expressionNames(){return Array.from(this._expressions.keys())}get results(){return this.evaluateAllExpressions(),this._results}evaluateAllExpressions(){Array.from(this._expressions.keys()).forEach(e=>{this._expressions.get(e)&&this.evaluateExpression(e)})}evaluateExpression(t){this.logger.debug(`Evaluating expression: ${String(t)}`);const e=this._expressions.get(t);if(!e){this.logger.warn(`Expression "${String(t)}" not found`);return}const s=e.evaluate(this.data);this.logger.debug(`Expression "${String(t)}" evaluated to:`,s);const r=e.result;(s.value!==r.value||s.error!==r.error)&&(this.logger.debug(`Expression "${String(t)}" result changed from`,r,"to",s),e.updateResult(s),this.updateResult(t,s))}updateResult(t,e){this.logger.debug(`ExpressionEvaluator.updateResult called for "${t}":`,e),X(()=>{this._results[t]=e})}createExpression(t){const e=lt();return this.addExpression(e,t),e}};Wb(Tr,"Registration");Tr=Yb([R({modelTypeId:Qb,singleton:!1})],Tr);const yu=Tr.Registration,Xb=m.createLogger({name:"kos-log-manager-service",group:"Services"}),Jb="/api/kos/logs/overrides",bu=async()=>(Xb.debug("sending GET for kos-log-manager"),await Ae.get(Jb)),ev=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:bu},Symbol.toStringTag,{value:"Module"}));var tv=Object.defineProperty,sv=Object.getOwnPropertyDescriptor,ao=(t,e,s,r)=>{for(var o=r>1?void 0:r?sv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&tv(e,s,o),o};const vu="kos-log-manager-model",rv="/kos/logs/override/add/*",ov="/kos/logs/override/remove/*",nv=t=>{if(typeof t=="string")return t;if(typeof t=="number")switch(t){case 0:return"trace";case 1:return"debug";case 2:return"info";case 3:return"warn";case 4:return"error";default:return"info"}return"info"};let Rt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new An}updateModel(t){}resolveLoggers(){const t=m.getLoggers(),s=Object.entries(t).map(([r,o])=>({name:r,level:nv(o.getLevel())})).reduce((r,{name:o,level:n})=>(r[o]={name:o,level:n},r),{});return this.logger.debug("Resolved loggers",s),s}async getAllLoggers(t,e){const s=Object.values(this.resolveLoggers());return e==null||e.send(s),s}setLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=m.getLoggers()[r.name];if(!o){this.logger.debug(`Logger ${r.name} not found`);return}o.setLevel(t.level)});const s=m.getLoggers()[t.name];if(!s){this.logger.debug(`Logger ${t.name} not found`);return}s.setLevel(t.level),globalThis.kos.logOverrides=this._overrides.data}resetLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=m.getLoggers()[r.name];o||this.logger.debug(`Logger ${r.name} not found`),o==null||o.resetLevel()});const s=m.getLoggers()[t.name];s||this.logger.debug(`Logger ${t.name} not found`),s==null||s.resetLevel(),globalThis.kos.logOverrides=this._overrides.data}handleOverrideAdded(t,e){var s;this.logger.debug(`Override received for node type ${((s=e.wildcardCapture)==null?void 0:s.nodeType)??"unknown"}`),this._overrides.addModel({...t,id:t.name}),this.setLogLevels(t)}handleOverrideRemoved(t){this._overrides.removeModel(t.name),this.resetLogLevels(t)}async init(){this.logger.debug(`initializing kos-log-manager ${this.id}`)}async load(){this.logger.debug(`loading kos-log-manager ${this.id}`),this.resolveLoggers();const[t,e]=await bu();if(t){this.logger.error("Failed to load log overrides",t);return}const s=(e==null?void 0:e.filter(r=>{var o;return((o=r.type)==null?void 0:o.toUpperCase())==="UI"}).map(r=>({name:r.name??"",type:r.type??"",level:r.level??"info",id:r.name||""})))??[];this._overrides.addAll(s),s.forEach(r=>{this.setLogLevels(r)})}};ao([$c("/api/kos/ui/loggers")],Rt.prototype,"getAllLoggers",1);ao([B({topic:rv,websocket:!0,wildcardName:"nodeType"})],Rt.prototype,"handleOverrideAdded",1);ao([B({topic:ov,websocket:!0,wildcardName:"nodeType"})],Rt.prototype,"handleOverrideRemoved",1);Rt=ao([R(vu)],Rt);const wu=new Se({class:Rt,type:vu}),{URL:Vs}=ce(),{postModel:si,getOne:iv}=oe.build({basePath:`${Vs}/api/kos-time`});m.createLogger({name:"kos-time-service",group:"Services"});const Eu=async t=>{const e=await si({model:t,urlOverride:`${Vs}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Mu=async t=>{const e=await si({model:t,urlOverride:`${Vs}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Tu=async t=>{const e=await si({model:{},urlOverride:`${Vs}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},_u=async()=>{const t=await iv({urlOverride:`${Vs}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},av=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:_u,setDate:Mu,setTime:Eu,setTimezone:Tu},Symbol.toStringTag,{value:"Module"}));var cv=Object.defineProperty,lv=Object.getOwnPropertyDescriptor,co=(t,e,s,r)=>{for(var o=r>1?void 0:r?lv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&cv(e,s,o),o};const os="kos-time-model",uv="/kos/time/time",dv="/kos/time/day",hv="/kos/time/timezone";let Pt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"timezone");this.id=t,this.logger=s.logger,this.timezone=""}async updateSystemTime(t){await Eu(t)}async updateSystemDate(t){await Mu(t)}async updateSystemTimezone(t){await Tu(t)}handleTimeChange(){q(Ts.TIME_CHANGE,{})}handleDayChange(){q(Ts.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),q(Ts.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await _u();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};co([B({topic:uv,websocket:!0})],Pt.prototype,"handleTimeChange",1);co([B({topic:dv,websocket:!0})],Pt.prototype,"handleDayChange",1);co([B({topic:hv,websocket:!0})],Pt.prototype,"handleTimeZoneChange",1);Pt=co([R(os)],Pt);const _r={registration:{[os]:{class:Pt,singleton:!0}},type:os,predicate:_e(os),factory:ae.Singleton.create(os)};var fv=Object.defineProperty,pv=Object.getOwnPropertyDescriptor,Su=(t,e,s,r)=>{for(var o=r>1?void 0:r?pv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&fv(e,s,o),o};const Ou="log-block-container-model";let Sr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new xe({parentId:t,sortKey:"blockNum"})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing log-block-container container ${this.id}`)}async load(){this.logger.debug(`loading log-block-container container ${this.id}`)}};Su([De],Sr.prototype,"_models",2);Sr=Su([R(Ou)],Sr);const gv=m.createLogger({name:"log-stream-container-service",group:"Services"}),Iu=()=>{var r;const t=be(),s=(t==null?void 0:t.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return m.error(`getKosConnectionId: ${s}`),s},Wt=Iu(),mv="/api/kos/logs/node/{nodeId}/streams",$u=async()=>(gv.debug("sending GET for log-stream-container"),await Ae.get(mv,{path:{nodeId:"primary"}},{destinationAddress:Wt})),Cu=async(t,e="primary")=>{await Ae.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:Wt})},Du=async t=>{await Ae.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:Wt})},yv=async()=>{await Ae.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:Wt})},xu=async t=>await Ae.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:Wt}),Au=async(t,e)=>await Ae.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:Wt}),bv=Object.freeze(Object.defineProperty({__proto__:null,createOverride:yv,getKosConnectionId:Iu,getLogStreamBlock:Au,getLogStreamBlocks:xu,getLogStreams:$u,subscribeToLogStream:Cu,unsubscribeFromLogStream:Du},Symbol.toStringTag,{value:"Module"}));var vv=Object.getOwnPropertyDescriptor,wv=(t,e,s,r)=>{for(var o=r>1?void 0:r?vv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Ru="log-block-model";let qo=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"stream");l(this,"blockNum");l(this,"startLineNum");l(this,"endLineNum");l(this,"startTime");l(this,"endTime");l(this,"lineCount");l(this,"lines");l(this,"inc");this.id=t,this.logger=s.logger,this.nodeId=e.nodeId,this.stream=e.stream,this.blockNum=e.blockNum,this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount,this.lines=[],this.inc=0}async syncLines(){const[t,e]=await Au(this.stream,this.blockNum);if(t){this.logger.error(`Failed to get log block ${this.blockNum}`);return}e&&this.addLines(e.lines,!0)}updateModel(t){this.startLineNum=t.startLineNum,this.endLineNum=t.endLineNum,this.startTime=t.startTime,this.endTime=t.endTime,this.lineCount=t.lineCount}addLines(t,e){const s=e?[]:this.lines;this.lines=[...s,...t],this.inc+=1}async init(){this.logger.debug(`initializing log-block ${this.id}`)}async load(){this.logger.debug(`loading log-block ${this.id}`)}};qo=wv([R(Ru)],qo);const As=new ve({class:qo,type:Ru}),lo=new ve({class:Sr,type:Ou});lo.addRelatedModel(As);var Ev=Object.defineProperty,Mv=Object.getOwnPropertyDescriptor,Pu=(t,e,s,r)=>{for(var o=r>1?void 0:r?Mv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ev(e,s,o),o};const ku="log-stream-model";let Or=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"_blocks");l(this,"name");l(this,"currentBlockId");l(this,"isResetting");l(this,"generatorInstance");l(this,"shouldStop",!1);this.id=t,this.logger=s.logger,this.currentBlockId="",this.name=e.name,this.nodeId=e.nodeId,this.isResetting=!0,this._blocks=lo.instance(`${t}-blocks`).options({}).build()}get firstLineNum(){const t=this.populated[0];return t?t.startLineNum:0}get currentBlock(){const t=this.currentBlockId;return this._blocks.getModel(t)}get populated(){return this._blocks.data.filter(t=>t.lines.length>0)}get blocks(){return this._blocks.data}get totalLineCount(){return this.populated.reduce((t,e)=>t+e.lineCount,0)}accept(t){t.visit(this)}updateBlock(t){var r;let e=this._blocks.models.getModel(`${t.stream}-block-${t.blockNum}`);const s={nodeId:t.nodeId,blockNum:t.blockNum,endLineNum:t.endLineNum,lineCount:t.lineCount,startLineNum:t.startLineNum,stream:this.name,endTime:new Date(t.endTime),startTime:new Date(t.startTime)};e||(e=As.instance(`${t.stream}-block-${t.blockNum}`).options(s).build(),this._blocks.addModel(e)),e&&e.updateModel(s),(!this.currentBlock||t.blockNum>=((r=this.currentBlock)==null?void 0:r.blockNum))&&(this.currentBlockId=`${t.stream}-block-${t.blockNum}`)}addBlock(t){var s;const e=As.instance(`${t.stream}-block-${t.blockNum}`).options({nodeId:t.nodeId,blockNum:t.blockNum,endLineNum:t.endLineNum,lineCount:t.lineCount,startLineNum:t.startLineNum,stream:this.name,endTime:new Date(t.endTime),startTime:new Date(t.startTime)}).build();this._blocks.addModel(e),(!this.currentBlock||t.blockNum>=((s=this.currentBlock)==null?void 0:s.blockNum))&&(this.currentBlockId=`${t.stream}-block-${t.blockNum}`)}removeBlock(t){this._blocks.models.removeModel(`${this.name}-block-${t}`)}async subscribe(){await Cu(this.name)}async unsubscribe(){await Du(this.name)}async reset(){if(this.isResetting=!0,this.populated.length>0)return;this.logger.debug(`resetting log-stream ${this.id}`);for(const e of this._blocks.models.data)e.lines=[];const t=this._blocks.data[this._blocks.data.length-1];t&&await t.syncLines(),this.isResetting=!1}async init(){this.logger.debug(`initializing log-stream ${this.id}`)}async load(){this.logger.debug(`loading log-stream ${this.id}`);const[t,e]=await xu(this.name);if(t){this.logger.error(`Error loading log stream: ${t}`);return}if(e)for(const r of e)this.addBlock(r);const s=this._blocks.data[this._blocks.data.length-1];if(s&&await s.syncLines(),this._blocks.data.length>1){const r=this._blocks.data[this._blocks.data.length-2];r&&await r.syncLines()}}start(){return this.shouldStop=!1,this.generatorInstance=this.streamLogs(),this.generatorInstance}stop(){var t;this.shouldStop=!0,(t=this.generatorInstance)==null||t.next(),console.log("Requested generator stop.")}async*streamLogs(){const t=[];let e=null,s=0,r=this.currentBlockId;const o=Rl(()=>{const n=this.currentBlock;return n?{blockId:this.currentBlockId,lineCount:n.lines.length}:null},n=>{const i=this.currentBlock;if(i)if(r!==(n==null?void 0:n.blockId))r=n==null?void 0:n.blockId,s=0,t.push(...i.lines);else{const a=i.lines.slice(s);t.push(...a),s+=a.length}e&&(e(),e=null)},{fireImmediately:!0});try{for(const n of this.populated.filter(i=>i!==this.currentBlock))for(const i of n.lines)yield i;for(;;)for(t.length===0&&await new Promise(n=>e=n);t.length>0;)yield t.shift()}finally{o()}}};Pu([De],Or.prototype,"_blocks",2);Or=Pu([R(ku)],Or);const _s=new ve({class:Or,type:ku});var Tv=Object.defineProperty,_v=Object.getOwnPropertyDescriptor,gt=(t,e,s,r)=>{for(var o=r>1?void 0:r?_v(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Tv(e,s,o),o};const Lu="log-stream-container-model",Sv="/kos/logs/subscription/addBlock/*",Ov="/kos/logs/subscription/updateBlock/*",Iv="/kos/logs/subscription/removeBlock/*",$v="/kos/logs/subscription/lines/*",Fu="/kos/logs/streams/add/*";let Ne=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"selectedStream");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new xe({parentId:t}),this.selectedStream=void 0}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}updateModel(t){}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}updateSelectedStream(t){this.selectedStream=t}handleStreamAdded(t){this.logger.debug(`Received topic: ${Fu}`);const e=t.stream,s=_s.instance(e).options({name:e,nodeId:"primary"}).build();this.addModel(s)}handleAddBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.addBlock(t)}handleRemoveBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.removeBlock(t.blockNum)}handleUpdateBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.updateBlock(t)}handleLogLine(t,e){var o;this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&((o=r.currentBlock)==null||o.addLines(t.lines))}async init(){this.logger.debug(`initializing log-stream-container container ${this.id}`)}async subscribeToLogStream(t){const e=_s.instance(t).options({name:t,nodeId:"primary"}).build();this.addModel(e),await e.subscribe()}async load(){this.logger.debug(`loading log-stream-container container ${this.id}`);const[t,e]=await $u();if(t){this.logger.error(`Error loading log-streams: ${t}`);return}e&&e.forEach(s=>{const r=_s.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};gt([De],Ne.prototype,"_models",2);gt([B({topic:[Fu],websocket:!0})],Ne.prototype,"handleStreamAdded",1);gt([B({topic:[Sv],websocket:!0})],Ne.prototype,"handleAddBlock",1);gt([B({topic:[Iv],websocket:!0})],Ne.prototype,"handleRemoveBlock",1);gt([B({topic:[Ov],websocket:!0})],Ne.prototype,"handleUpdateBlock",1);gt([B({topic:[$v],websocket:!0})],Ne.prototype,"handleLogLine",1);Ne=gt([R(Lu)],Ne);const Gs=new Se({class:Ne,type:Lu});Gs.addRelatedModel(_s);Gs.addRelatedModel(lo);Gs.addRelatedModel(As);const Cv=t=>t.rank!==void 0,Dv=t=>t.visibleRole!==void 0,xv=t=>t.color!==void 0,Av=t=>{const e=t.info;return Cv(e)?e.rank:0},Rv=t=>{const e=t.info;return xv(e)?e.color:"orange"},Pv=t=>{const e=t.info;return Dv(e)?e.visibleRole:"TECHNICIAN"},{URL:uo}=ce(),{getAll:kv,postModel:Nu}=oe.build({basePath:`${uo}/api/kos/troubles`}),Uu=async t=>await kv({urlOverride:`${uo}${t}`}),ju=async(t,e="/api/kos/troubles",s)=>{try{const r=await Nu({model:{},urlOverride:`${uo}${e}/resolve/${t}`,tracker:s});return r!=null&&r.data&&at.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:Ge.Fail,tracker:s,reason:"Failed to resolve trouble"};return at.initiateFuture(o),o}},Lv=async(t,e="/api/kos/troubles",s)=>{try{const r=await Nu({model:t,urlOverride:`${uo}${e}/resolve/`,tracker:s});return r!=null&&r.data&&at.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:Ge.Fail,tracker:s,reason:"Failed to resolve troubles"};return at.initiateFuture(o),o}},Fv=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:Lv,getTroubles:Uu,resolveTrouble:ju},Symbol.toStringTag,{value:"Module"})),Ir="troubleDataMapper",or=new Map;js(Ir,{register:(t,e)=>{var s;or.has(t)||or.set(t,[]),(s=or.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=or.get(t);if(!s)return{...e.data};const r=s.map(i=>i(e));return(await Promise.allSettled(r)).reduce((i,a)=>(a.status==="fulfilled"?i={...i,...a.value}:m.info(`Trouble mapper ${t} failed: ${a.reason}`),i),{...e.data})}});const Ys="troubleMapper",nr=new Map;js(Ys,{register:(t,e)=>{var s;nr.has(t)||nr.set(t,[]),(s=nr.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=nr.get(t);if(!s)return[];const r=s.map(i=>i(e)),n=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(m.info(`Trouble mapper ${t} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});$[Ys].register("nozzle",async t=>[t.data.nozzlePath]);$[Ys].register("path",async t=>[t.data.path]);const Nv=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(n=>$[Ys].execute(n,t));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>e.add(i))}),Array.from(e)},Bu=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>$[Ir].execute(i,t)),r=$[Ir].execute(t.type,t);s.push(r);const n=(await Promise.allSettled(s)).reduce((i,a)=>(a.status==="fulfilled"&&(i={...i,...a.value}),i),{});return{...t.data,...n}};class Uv{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class jv{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class wt{static getHandler(e){switch(e){case"ResolvableTrouble":return new Uv;case"BlockPumpTrouble":return new jv;default:return}}}var Bv=Object.defineProperty,Hv=Object.getOwnPropertyDescriptor,Hu=(t,e,s,r)=>{for(var o=r>1?void 0:r?Hv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Bv(e,s,o),o};const ns="trouble-model";function ir(t){return typeof t.shouldDefer=="boolean"}let $r=class{constructor(t,{resolvable:e,tags:s,info:r,id:o,clientData:n,rank:i,ifaces:a,type:c,group:u,createTime:d,role:h,color:f,servicePath:p,...y},w){l(this,"id");l(this,"logger");l(this,"_troubleId");l(this,"_resolvable");l(this,"type");l(this,"futureHandler");l(this,"ifaces");l(this,"clientData");l(this,"info");l(this,"role");l(this,"color");l(this,"tags");l(this,"data");l(this,"rank");l(this,"servicePath");l(this,"group");l(this,"createTime");l(this,"_mapped",{});this.id=t,this.logger=w.logger,this.type=c,this._troubleId=o,this._resolvable=!!e,this.ifaces=a,this.rank=i,this.role=h,this.color=f,this.tags=s,this.info=r,this.group=u,this.servicePath=p??"/api/kos/troubles",this.createTime=d,this.clientData=n,this.data={},Object.assign(this.data,y),this.futureHandler=new Xr(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=wt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:wt.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=wt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:wt.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=wt.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=wt.getHandler(this.type))==null?void 0:t.subtitle)||"Trouble"}get troubleId(){return this._troubleId}get resolvable(){return this._resolvable}get future(){return this.futureHandler.future}async resolveMappedData(){return await Bu(this)}get deferredCompanion(){const t=Lo(this.id,e=>ir(e));if(t&&ir(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=Lo(this.id,e=>ir(e));return t&&ir(t.modelData)?t.modelData.shouldDefer:!1}clearDefer(){var t;(t=this.deferredCompanion)==null||t.clearDefer()}defer(){var t;(t=this.deferredCompanion)==null||t.defer()}getChildren(){return[...this.futureHandler.allFutures]}async resolve(t){var e;if(!this._resolvable)throw this.logger.error(`attempting to resolve an unresolvable trouble with id ${this._troubleId}`),new Error("Trouble is not resolvable");if(this.shouldDefer){(e=this.deferredCompanion)==null||e.defer();return}return await ju(this._troubleId,this.servicePath,t)}};Hu([wi()],$r.prototype,"resolve",1);$r=Hu([R(ns)],$r);const Rs={registration:{[ns]:{class:$r,singleton:!1}},type:ns,predicate:_e(ns),factory:ae.Factory.create(ns)};var Ku=Object.defineProperty,Kv=Object.getOwnPropertyDescriptor,qv=(t,e,s)=>e in t?Ku(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ri=(t,e,s,r)=>{for(var o=r>1?void 0:r?Kv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ku(e,s,o),o},zv=(t,e,s)=>(qv(t,e+"",s),s);function oa(t){return $.propertyMapper.hasMapper(Ee.TroubleRank)?$.propertyMapper.executeMapper(Ee.TroubleRank,t):Av(t)}function na(t){return($.propertyMapper.hasMapper(Ee.TroubleColor)?$.propertyMapper.executeMapper(Ee.TroubleColor,t):Rv(t)).toLowerCase()}function ia(t){return($.propertyMapper.hasMapper(Ee.TroubleRole)?$.propertyMapper.executeMapper(Ee.TroubleRole,t):Pv(t)).toLowerCase()}const Vv="trouble-container-model";class me{}l(me,"INDEX_TROUBLES_BY_IFACE","byIface"),l(me,"INDEX_TROUBLES_BY_TYPE","byType"),l(me,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(me,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(me,"SORT_KEY_RANK","rank"),l(me,"TROUBLES_DEFERRED","true");let kt=class{constructor(t,e){l(this,"id");l(this,"servicePath","/api/kos/troubles");this.id=t,this.servicePath=e.servicePath??this.servicePath}async load(){this.logger.debug("loading trouble container");const t=await Uu(this.servicePath);try{t==null||t.data.forEach(e=>{const s={...e,servicePath:this.servicePath,rank:oa(e),color:na(e),role:ia(e),id:String(e.id)},r=Rs.factory(`trouble-${e.id}`)(s);this.troubles.addModel(r)})}catch(e){throw this.logger.error(e),e}}handleTroubleRemoved(t){const e=`trouble-${t}`,s=this.troubles.getModel(e);this.troubles.removeModel(e),s&&Oe(s)}handleTroubleAdded(t){const e={...t,servicePath:this.servicePath,rank:oa(t),color:na(t),role:ia(t),id:String(t.id)};if(e.role==="NONE")return;const s=Rs.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};zv(kt,"Registration");ri([B({topic:"/kos/trouble/remove",websocket:!0,lifecycle:x.INIT})],kt.prototype,"handleTroubleRemoved",1);ri([B({topic:"/kos/trouble/add",websocket:!0})],kt.prototype,"handleTroubleAdded",1);kt=ri([R({modelTypeId:Vv,singleton:!0}),Ac(),Ic({containerProperty:"troubles",containerOptions:{indexMap:{[me.INDEX_TROUBLES_BY_IFACE]:Nv,[me.INDEX_TROUBLES_BY_TYPE]:"type",[me.INDEX_TROUBLES_BY_GROUP]:"group",[me.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:me.SORT_KEY_RANK}})],kt);const Lt=kt.Registration,{URL:qu}=ce(),{getAll:Gv}=oe.build({basePath:`${qu}/api/kos/ota`}),aa=m.createLogger({name:"ota-service",group:"Services"}),Yv=async()=>{aa.debug("sending GET request to /api/kos/ota/artifacts");const t=await Gv({urlOverride:`${qu}/api/kos/ota/artifacts`});return aa.debug("getArtifacts - response:",t),t==null?void 0:t.data};var Wv=Object.defineProperty,Qv=Object.getOwnPropertyDescriptor,ho=(t,e,s,r)=>{for(var o=r>1?void 0:r?Qv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Wv(e,s,o),o};const zu="ota-model",Zv=t=>{let e=null;for(const s in t){const r=t[s],o=r.lastUpdateTime;(!e||e.lastUpdateTime<o)&&(e=r)}return e},$o=t=>{const e=t.artifactInfo,s=Zv(t.requests),r=(e==null?void 0:e.identifier)||(s==null?void 0:s.kabId);if(!r)return;let o;switch(t.status){case"INSTALLED":o="ready";break;case"INVALID":o="error";break;case"MISSING":o=((s==null?void 0:s.currentSize)||0)>0?"downloading":"idle";break;case"STAGED":o="pending"}const n=e===void 0;return{id:r,manifest:n,label:e==null?void 0:e.version,name:e==null?void 0:e.name,status:o,error:o==="error"?s==null?void 0:s.lastErrorReason:void 0,errorCount:o==="error"?s==null?void 0:s.errorCount:0,progress:o==="downloading"&&s&&!n?s.currentSize/(e==null?void 0:e.size)*100:void 0,size:e==null?void 0:e.size}};let Ft=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"data",new An);l(this,"troubleContainer");this.id=t,this.logger=s.logger}get downloadInProgressTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTADownloadInProgressTrouble"))==null?void 0:e[0]}get updatePendingTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAUpdatePendingTrouble"))==null?void 0:e[0]}get pausedDueToErrorsTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAPausedDueToErrorsTrouble"))==null?void 0:e[0]}get updates(){return this.data}get status(){return this.pausedDueToErrorsTrouble?"error":this.downloadInProgressTrouble?"downloading":this.updatePendingTrouble?"pending":"idle"}installAndReboot(){var t;this.updatePendingTrouble||this.logger.error("installAndReboot - OTAUpdatePendingTrouble not present"),this.logger.debug("installAndReboot - resolve OTAUpdatePendingTrouble"),(t=this.updatePendingTrouble)==null||t.resolve()}async init(){this.logger.debug(`initializing ota ${this.id}`)}async load(){this.logger.debug(`loading ota ${this.id}`);try{const t=await Yv();t&&t.forEach(e=>{const s=$o(e);s&&this.data.addModel(s)})}catch(t){this.logger.error(`loading ota ${this.id} - error:`,t)}}async handleAllArtifacts(t){this.logger.debug("handleAllArtifacts:",t),await this.data.clear();try{t.forEach(e=>{const s=$o(e);s&&this.data.addModel(s)})}catch(e){this.logger.error(`handleAllArtifacts ${this.id} - error:`,e)}}handleChangedArtifacts(t){this.logger.debug("handleChangedArtifacts:",t);try{t.forEach(e=>{const s=$o(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};ho([Ht({modelType:Lt.type})],Ft.prototype,"troubleContainer",2);ho([B({topic:"/kos/ota/artifacts/all",websocket:!0})],Ft.prototype,"handleAllArtifacts",1);ho([B({topic:"/kos/ota/artifacts/changed",websocket:!0})],Ft.prototype,"handleChangedArtifacts",1);Ft=ho([R(zu)],Ft);const Cr=new Se({class:Ft,type:zu});function Xv(t){let e;const s=async(...r)=>{e&&e.abort(),e=new AbortController;const o=e;try{return await t(...r,o.signal)}finally{e===o&&(e=void 0)}};return s.cancel=()=>{e&&(e.abort(),e=void 0)},s.getController=()=>e,s.isActive=()=>!!e,s}const Co=m.createLogger({name:"software-info-service",group:"Services"}),oi=async t=>{Co.debug("sending GET for software-info");const[e,s]=await tu.get("/api/kos/manifest/info",void 0,{signal:t});if(!s)throw t!=null&&t.aborted?(Co.debug("Request was aborted"),new ye("Request was aborted")):(Co.error("Failed to fetch software-info",e),new ye("Failed to fetch software-info"));return s},Jv=Xv(oi),ew=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:oi,getSoftwareInfosWithCancel:Jv},Symbol.toStringTag,{value:"Module"}));var tw=Object.getOwnPropertyDescriptor,sw=(t,e,s,r)=>{for(var o=r>1?void 0:r?tw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const is="software-info-model";let zo=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodes");this.id=t,this.logger=s.logger,this.nodes=[]}async init(){this.logger.debug(`initializing software-info ${this.id}`)}groupBy(t,e){return t.reduce((s,r)=>(s[r[e]]=[...s[r[e]]||[],r],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const t=await oi(),e=(t==null?void 0:t.nodes)||{};X(()=>{const r=Object.keys(e).map(o=>e[o][0]).map(o=>({nodeName:o.nodeType,kosVersion:o.kosVersion,group:this.groupBy(o.artifacts,"group")}));this.nodes=r})}catch(t){t instanceof ye&&this.logger.error("Failed to fetch software-info",t)}}};zo=sw([R(is)],zo);const Dr={registration:{[is]:{class:zo,singleton:!1}},type:is,predicate:_e(is),factory:ae.Factory.create(is)},{URL:Vu}=ce(),{getOne:rw}=oe.build({basePath:`${Vu}/api/kos/state`}),ow=m.createLogger({name:"state-bean-service",group:"Services"}),Gu=async({path:t})=>(ow.debug("sending GET for state-bean"),await rw({urlOverride:`${Vu}/api/kos/state/${t}`})),nw=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:Gu},Symbol.toStringTag,{value:"Module"}));var iw=Object.defineProperty,aw=Object.getOwnPropertyDescriptor,Yu=(t,e,s,r)=>{for(var o=r>1?void 0:r?aw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&iw(e,s,o),o};const as="state-bean-model",cw=ut("path");let xr=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"props");l(this,"logger");this.id=t,this.logger=s.logger,this.props=Pn.map(new Map),ko(e,this)}updateModel(t){ko(t,this)}handleConfigBeanUpdated(t){Object.entries(t).forEach(([e,s])=>{let r=s;typeof r=="string"&&Fn(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&Jr(r)&&(r=Number(r)),this.props.set(e,r)})}async init(){this.logger.debug(`initializing state-bean ${this.id}`)}updateProps(t){Object.entries(t).forEach(([e,s])=>{this.props.set(e,s)})}async load(){this.logger.debug(`loading state-bean ${this.id}`);const t=await Gu({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};Yu([B({topic:`/kos/state/${cw}`,websocket:!0})],xr.prototype,"handleConfigBeanUpdated",1);xr=Yu([R(as)],xr);const Ps={registration:{[as]:{class:xr,singleton:!1}},type:as,predicate:_e(as),factory:ae.Factory.create(as)};var lw=Object.defineProperty,uw=Object.getOwnPropertyDescriptor,Wu=(t,e,s,r)=>{for(var o=r>1?void 0:r?uw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&lw(e,s,o),o};const cs="state-prop-model",ca=ut("path");let Ar=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"attribute");l(this,"logger");l(this,"stateBean");this.id=t,this.logger=s.logger,this.path=e.path,this.attribute=e.attribute}get value(){return this.stateBean.props.get(this.attribute)}async init(){this.logger.debug(`initializing state-prop ${this.id}`)}async load(){this.logger.debug(`loading state-prop ${this.id}`)}toString(){var t;return((t=this.value)==null?void 0:t.toString())??""}};Wu([Ht({modelType:Ps.type,id:`state-bean-${ca}`,options:{path:ca}})],Ar.prototype,"stateBean",2);Ar=Wu([R(cs)],Ar);const ni={registration:{[cs]:{class:Ar,singleton:!1}},type:cs,predicate:_e(cs),factory:ae.Factory.create(cs)},{URL:dw}=ce(),{getAll:hw}=oe.build({basePath:`${dw}/api/state-prop`}),fw=m.createLogger({name:"state-prop-service",group:"Services"}),pw=async()=>(fw.debug("sending GET for state-prop"),await hw({})),gw=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:pw},Symbol.toStringTag,{value:"Module"})),{URL:ii}=ce(),{getOne:Qu}=oe.build({basePath:`${ii}/api/translation`}),Ss=m.createLogger({name:"translation-service",group:"Services"}),mw=()=>{const t=window.location.origin,e=be();return(e==null?void 0:e.host)||t},Zu=async(t,e)=>{Ss.debug(`Loading translations from: ${t}`);const s=e??mw();try{const r=await fetch(`${s}${t}`);return r.status!==200?(Ss.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw Ss.error("Error fetching translations",r),r}},yw=async()=>{Ss.debug("Getting system localization descriptor");const t=await Qu({urlOverride:`${ii}/api/system/kos/localization`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get localization descriptor ${t==null?void 0:t.status}`);return t.data},Xu=t=>async()=>{Ss.debug(`Getting KOS localization descriptor for context: ${t}`);const e=await Qu({urlOverride:`${ii}/api/kos/localization/contexts`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get KOS localization descriptor ${e==null?void 0:e.status}`);return e.data[t]},Ju="langResolver";var bw=Object.getOwnPropertyDescriptor,vw=(t,e,s,r)=>{for(var o=r>1?void 0:r?bw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const ls="translation-model";function ww(t){const e=typeof t=="string",s=e?!1:!!(t!=null&&t.data)&&typeof(t==null?void 0:t.data)!="string",r=e?t:t==null?void 0:t.defaultValue,o=e||t==null?void 0:t.context,n=e?void 0:s?t==null?void 0:t.data:t;return{isBasicOptions:e,defaultValue:r,context:o,data:n}}function ed(t,e=""){return Object.keys(t).reduce((s,r)=>{const o=e?`${e}.${r}`:r;if(typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])){const n=ed(t[r],o);return{...s,...n}}else return{...s,[o]:t[r]}},{})}function td(t,e){const s={...t};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(typeof e[r]=="object"&&e[r]!==null&&typeof t[r]=="object"&&t[r]!==null?s[r]=td(t[r],e[r]):s[r]=e[r]);return s}const Vo=(t,e)=>{const s=/__(.*?)__/g,r=t.replace(s,(o,n)=>Object.prototype.hasOwnProperty.call(e||{},n.trim())?e==null?void 0:e[n.trim()]:o);return r===t?r:s.test(r)?Vo(r,e):r},ar=(t,e,s)=>{const r=/{{(.*?)}}/g,n=Vo(t,e).replace(r,(a,c)=>{const u=c.trim();if(Object.prototype.hasOwnProperty.call(s||{},u))return s==null?void 0:s[u];if(u.includes(".")){const d=u.split(".");let h=s;for(const f of d)if(h&&typeof h=="object"&&Object.prototype.hasOwnProperty.call(h,f))h=h[f];else return a;return h}return a});return Vo(n,e)},la=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let Go=class{constructor(t,e,s){l(this,"id");l(this,"namespace");l(this,"descriptor");l(this,"defaultLocale");l(this,"currentLocale");l(this,"bundleResolver");l(this,"data");l(this,"logger");l(this,"resolver");l(this,"disposer");l(this,"context");l(this,"rootUrl");this.id=t,this.defaultLocale=e.defaultLocale||"en",this.currentLocale=e.currentLocale||"en",this.namespace=e.namespace,this.descriptor=e.descriptor,this.rootUrl=e.rootUrl,this.data={},this.resolver=e.resolver||s.kosContext.get(Ju),this.bundleResolver=e.bundleResolver,this.logger=s.logger,this.context=s.kosContext.parentModel}getTranslationLocales(t){const e=this.descriptor[t];if(!t||!e)return[this.defaultLocale];if(!this.defaultLocale&&!e.fallbacks)return[t];let s=e.fallbacks||[this.defaultLocale];return s.includes(t)||(s=[t,...s]),s}async loadTranslations(){const t=this.getTranslationLocales(this.currentLocale).reverse(),e=t.map(r=>{if(this.bundleResolver){const o=V.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return Zu(o,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(e);X(()=>{const r=s.reduce((o,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${t[i]}`,n.value),n.value&&(o=td(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),o),{});this.data=ed(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=la(this.namespace,t);if(e!==this.namespace){const r=this.context.getModel(e);return r?r.exists(s):!1}return!!this.data[s]}resolveKey(t,e){if(!t)return this.logger.debug("key is empty"),"";const{defaultValue:s,context:r,data:o}=ww(e),{namespace:n,key:i}=la(this.namespace,t),a=`${i}_${r}`;if(n!==this.namespace){const c=this.context.getModel(n);return c?c.resolveKey(i,e):i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(u=>ar(u,this.data,o)):ar(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[i];return Array.isArray(c)?c.map(u=>ar(u,this.data,o)):ar(this.data[i],this.data,o)}return s??i}unload(){this.logger.debug(`unloading translation ${this.id}`),this.disposer&&this.disposer()}async load(){this.logger.debug(`loading translation ${this.id}`),await this.loadTranslations()}async ready(){this.logger.debug(`ready translation ${this.id}`),this.disposer=M.reaction(()=>this.currentLocale,(t,e)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${e} to ${t}`),this.loadTranslations()})}};Go=vw([Wr(),R(ls)],Go);const Rr={registration:{[ls]:{class:Go,singleton:!1}},type:ls,predicate:_e(ls),factory:ae.Factory.create(ls)};var Ew=Object.defineProperty,Mw=Object.getOwnPropertyDescriptor,sd=(t,e,s,r)=>{for(var o=r>1?void 0:r?Mw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ew(e,s,o),o};const us="translation-container-model",Tw=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function _w(t,e){const s=this.descriptor.namespaces[t];if(!s)throw new Error("namespace "+t+" not found in descriptor");const r=s.basePath,o=s.locales[e].file;return Tw([r,o])}let Pr=class{constructor(t,e,s){l(this,"id");l(this,"lang");l(this,"rootUrl");l(this,"descriptor");l(this,"_defaultNamespace");l(this,"resolver");l(this,"logger");l(this,"descriptorUrl");l(this,"namespaces",[]);l(this,"_models");this.id=t,this.lang=e.lang||"en",this.descriptor=e.descriptor,this._defaultNamespace=e.defaultNamespace,this.descriptorUrl=e.descriptorUrl,this.rootUrl=e.rootUrl,this.resolver=e.resolver||_w.bind(this),s.kosContext.set(Ju,this.resolver),this.logger=s.logger,this._models=new xe({parentId:t})}set currentLocale(t){this.lang=t,this.models.data.forEach(e=>{e.currentLocale=t})}get defaultNamespace(){return this._defaultNamespace?this.getModel("translation-"+this._defaultNamespace):void 0}getModel(t){return this.logger.debug("getting model "+t),this._models.getModel("translation-"+t)}get models(){return this._models}get data(){return this._models.data}async reload(){for(const t of this.namespaces){const e=this.resolveNamespace(t);await fe(e)}}resolveNamespace(t){var s;if((s=this.descriptor.namespaces)==null?void 0:s[t]){const r=Object.keys(this.descriptor.namespaces[t].locales)[0],o=this.descriptor.namespaces[t].locales[r].defaultLocale,n=Rr.factory("translation-"+t)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:o,descriptor:this.descriptor.namespaces[t].locales,resolver:this.resolver});return this.addModel(n),this.namespaces.includes(t)||X(()=>{this.namespaces.push(t)}),n}else{this.logger.warn("namespace "+t+" not found in descriptor");const r=Rr.factory("translation-"+t)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(r),r}}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug("initializing translation-container container "+this.id)}async load(){this.logger.debug("loading translation-container container "+this.id)}};sd([De],Pr.prototype,"_models",2);Pr=sd([R(us)],Pr);const Ue={registration:{[us]:{class:Pr,singleton:!0}},type:us,predicate:_e(us),factory:ae.Singleton.create(us)},Sw={set(t,e){const s=V.getContext(Ue.type);s&&s.set(t,e)},get(t){const e=V.getContext(Ue.type);return e==null?void 0:e.get(t)}},rd={async init(t){const e=Ue.factory(t);return await fe(e),{translations:e}}};function Ow(t){return(t==null?void 0:t.troubles)!==void 0&&(t==null?void 0:t.troubles)instanceof Array&&(t==null?void 0:t.troublesByType)!==void 0&&typeof(t==null?void 0:t.troublesByType)=="object"}const od="kos-ws-event",ai=Kt(od);var Iw=Object.defineProperty,$w=Object.getOwnPropertyDescriptor,ci=(t,e,s,r)=>{for(var o=r>1?void 0:r?$w(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Iw(e,s,o),o};const Cw=({headers:t,body:e})=>Object.entries(t).map(([r,o])=>`${r}:${o}`).join("\\n")+"\\n\\n"+e;exports.WsEventModel=class{constructor(e){l(this,"id");l(this,"events");l(this,"_topicMap");this.id=e,this.events=M.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(e,s){this.processEvent(s,!0)}handleReceiveEvent(e,s){this.processEvent(s)}processEvent(e,s=!1){m.debug("kos event received");const{body:r,headers:o}=e.body,n=o["request-id"]||o["response-id"],i=o["request-id"]||o["response-id"]||o.topic||o.type;if(i){let a=i;if(n)a=`${a}-${s?"send":"receive"}`;else{const u=this._topicMap.get(i)||0;a=`${a}-${u+1}`,this._topicMap.set(i,u+1)}const c={msgId:a,content:r,headers:o,timestamp:Date.now(),raw:Cw({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),m.debug(`logged ${this.events.size} events`)}}};ci([B({topic:[Us.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);ci([B({topic:[Us.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=ci([R(ai.type)],exports.WsEventModel);const ua=be(),Dw=ua.debug==="true"||ua.debug===!0,xw="/api/system/canvas",nd=async(t,e)=>{const s=e||xw,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:Dw?"false":"true"},body:t})},Aw=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:nd},Symbol.toStringTag,{value:"Module"}));function da(t,e,s){{const r=t.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var Rw=Object.defineProperty,Pw=Object.getOwnPropertyDescriptor,id=(t,e,s,r)=>{for(var o=r>1?void 0:r?Pw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Rw(e,s,o),o};const ad="canvas-renderer-model";function Do(t){return typeof t.onDone=="function"}let kr=class{constructor(t,e,s){l(this,"id");l(this,"router");l(this,"logger");l(this,"_renderer",null);l(this,"_clearOnComplete");l(this,"isStreaming",!1);l(this,"renderLoopId",null);l(this,"sendIntervalId",null);l(this,"timeoutId",null);l(this,"apiPath");l(this,"endpointName");l(this,"width",50);l(this,"height",30);l(this,"fps",10);l(this,"durationMs",null);l(this,"_onFrame",null);this.id=t,this.logger=s.logger,this.width=e.width??50,this.height=e.height??30,this.fps=e.fps??10,this.durationMs=e.durationMs??null,this.apiPath=e.apiPath??"/api/system/canvas",this.endpointName=e.endpoint}set onFrame(t){this._onFrame=t}set renderer(t){var e,s;this._renderer&&(this.stopStreaming(),(s=(e=this._renderer).dispose)==null||s.call(e)),this._renderer=t,this.isStreaming&&this.startStreaming()}setClearOnComplete(t){this._clearOnComplete=t}sendDataFrame(t,e){nd(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const t=this.isOneShotDone();this.stopStreaming(!t)});return}}handleFrame(t){var s;const e=da(t);this.sendDataFrame(e,this.apiPath),(s=this._onFrame)==null||s.call(this,e)}stopStreaming(t=!0){var e,s;this.logger.debug(`stopStreaming called with clearCanvas=${t}`),this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(s=(e=this._renderer)==null?void 0:e.pause)==null||s.call(e),t&&(this.logger.debug("Clearing canvas..."),this.clearCanvas())}clearCanvas(){var s;const t=this.width>0?this.width:50,e=this.height>0?this.height:30;if(t>0&&e>0){const r=t*e*4,o=new Uint8ClampedArray(r);for(let i=3;i<r;i+=4)o[i]=255;const n=da(o);this.logger.debug(`Sending clear frame: ${t}x${e}, apiPath: ${this.apiPath}`),this.sendDataFrame(n,this.apiPath),(s=this._onFrame)==null||s.call(this,n)}}isOneShotDone(){var t,e;return Do(this._renderer)&&((e=(t=this._renderer).isOneShot)==null?void 0:e.call(t))===!0&&this._renderer.isOneShotDone}startStreaming(){var t,e,s,r;{if(!this._renderer)return;if(!this.apiPath){this.logger.error(`No endpoint configured for canvas renderer ${this.id}`);return}this.isStreaming=!0,this._renderer.reset(),(e=(t=this._renderer).play)==null||e.call(t);const o=Do(this._renderer);Do(this._renderer)&&this._renderer.onDone(()=>{var c,u,d;this.logger.debug(`Renderer completed for ${this.id}`),q("/canvas/renderer/completed",{endpoint:this.endpointName,rendererId:this.id,rendererType:(c=this._renderer)==null?void 0:c.constructor.name,timestamp:Date.now()});let a=!0;this._clearOnComplete!==void 0?a=this._clearOnComplete:a=!(((d=(u=this._renderer)==null?void 0:u.isOneShot)==null?void 0:d.call(u))??!1),this.stopStreaming(a)}),this._renderer.renderFrame(this.width,this.height);const n=(r=(s=this._renderer).readPixels)==null?void 0:r.call(s,this.width,this.height);if(n&&this._onFrame&&this.handleFrame(n),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming(!1)});return}const i=()=>{var a;(a=this._renderer)==null||a.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var c,u;const a=(u=(c=this._renderer)==null?void 0:c.readPixels)==null?void 0:u.call(c,this.width,this.height);a&&this._onFrame&&(this.handleFrame(a),this.checkStreaming())},1e3/this.fps),!o&&this.durationMs!=null&&(this.timeoutId=setTimeout(()=>{this.stopStreaming()},this.durationMs))}}async init(){this.logger.debug(`initializing canvas-renderer ${this.id}`)}async load(){this.logger.debug(`loading canvas-renderer ${this.id}`),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/stop`,async(t,e)=>{this.logger.debug(`HTTP stop endpoint called for ${this.endpointName}`),this.stopStreaming(),e.send({status:"OK"})}),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/start`,async(t,e)=>{this.startStreaming(),e.send({status:"OK"})})}};id([Ht({modelType:zn.type})],kr.prototype,"router",2);kr=id([R(ad)],kr);const li=new ve({class:kr,type:ad});class cd{constructor({src:e}){l(this,"video");l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);l(this,"doneCallback",null);this.video=document.createElement("video"),this.video.src=e,this.video.crossOrigin="anonymous",this.video.muted=!0,this.video.loop=!1,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");this.ctx=s,this.handleEnded=this.handleEnded.bind(this),this.video.addEventListener("ended",this.handleEnded)}handleEnded(){this.doneCallback&&this.doneCallback()}reset(){this.video.pause(),this.video.currentTime=0,this.lastUpdate=performance.now()}play(){this.video.play().catch(console.warn)}pause(){this.video.pause()}renderFrame(e,s){this.canvas.width=e,this.canvas.height=s,this.video.readyState>=2&&this.ctx.drawImage(this.video,0,0,e,s)}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}onDone(e){this.doneCallback=e}dispose(){this.video.pause(),this.video.removeAttribute("src"),this.video.load(),this.video.remove(),this.video.removeEventListener("ended",this.handleEnded),this.doneCallback=null}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}}class kw{constructor(){l(this,"canvas");l(this,"gl");l(this,"lastWidth",0);l(this,"lastHeight",0);l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl");if(!e)throw new Error("WebGL not supported");this.gl=e}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e=this.lastWidth,s=this.lastHeight){const r=new Uint8Array(e*s*4);this.gl.readPixels(0,0,e,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r);const o=new Uint8ClampedArray(r.length);for(let n=0;n<s;n++){const i=n*e*4,a=(s-1-n)*e*4;o.set(r.subarray(i,i+e*4),a)}return o}}class Lw extends kw{constructor({speedPx:s=1}={}){super();l(this,"program");l(this,"posBuffer");l(this,"aPosition");l(this,"uMinHue");l(this,"uMaxHue");l(this,"uHueOffset");l(this,"uGridHeight");l(this,"minHue",0);l(this,"maxHue",80);l(this,"hueOffset",0);l(this,"speedPx",1);this.speedPx=s;const r=this.gl,o=`
110
+ `,s+1);while(s>=0&&s<this.pos);return{line:t,column:e}};z.prototype.parseError=function(t){var e=this.getCoordinates();throw new Error("parse error ["+e.line+":"+e.column+"]: "+t)};function H(t,e,s){this.parser=t,this.tokens=e,this.current=null,this.nextToken=null,this.next(),this.savedCurrent=null,this.savedNextToken=null,this.allowMemberAccess=s.allowMemberAccess!==!1}H.prototype.next=function(){return this.current=this.nextToken,this.nextToken=this.tokens.next()};H.prototype.tokenMatches=function(t,e){return typeof e>"u"?!0:Array.isArray(e)?_t(e,t.value):typeof e=="function"?e(t):t.value===e};H.prototype.save=function(){this.savedCurrent=this.current,this.savedNextToken=this.nextToken,this.tokens.save()};H.prototype.restore=function(){this.tokens.restore(),this.current=this.savedCurrent,this.nextToken=this.savedNextToken};H.prototype.accept=function(t,e){return this.nextToken.type===t&&this.tokenMatches(this.nextToken,e)?(this.next(),!0):!1};H.prototype.expect=function(t,e){if(!this.accept(t,e)){var s=this.tokens.getCoordinates();throw new Error("parse error ["+s.line+":"+s.column+"]: Expected "+(e||t))}};H.prototype.parseAtom=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.accept(Jn)||this.accept(j,s))t.push(new P(Le,this.current.value));else if(this.accept(no))t.push(new P(ge,this.current.value));else if(this.accept(pu))t.push(new P(ge,this.current.value));else if(this.accept(Fe,"("))this.parseExpression(t),this.expect(Fe,")");else if(this.accept(At,"["))if(this.accept(At,"]"))t.push(new P(xt,0));else{var r=this.parseArrayList(t);t.push(new P(xt,r))}else throw new Error("unexpected "+this.nextToken)};H.prototype.parseExpression=function(t){var e=[];this.parseUntilEndStatement(t,e)||(this.parseVariableAssignmentExpression(e),!this.parseUntilEndStatement(t,e)&&this.pushExpression(t,e))};H.prototype.pushExpression=function(t,e){for(var s=0,r=e.length;s<r;s++)t.push(e[s])};H.prototype.parseUntilEndStatement=function(t,e){return this.accept(ei)?(this.nextToken&&this.nextToken.type!==xs&&!(this.nextToken.type===Fe&&this.nextToken.value===")")&&e.push(new P(ro)),this.nextToken.type!==xs&&this.parseExpression(e),t.push(new P(ie,e)),!0):!1};H.prototype.parseArrayList=function(t){for(var e=0;!this.accept(At,"]");)for(this.parseExpression(t),++e;this.accept(io);)this.parseExpression(t),++e;return e};H.prototype.parseVariableAssignmentExpression=function(t){for(this.parseConditionalExpression(t);this.accept(j,"=");){var e=t.pop(),s=[],r=t.length-1;if(e.type===Dt){if(!this.tokens.isOperatorEnabled("()="))throw new Error("function definition is not permitted");for(var o=0,n=e.value+1;o<n;o++){var i=r-o;t[i].type===Le&&(t[i]=new P(lt,t[i].value))}this.parseVariableAssignmentExpression(s),t.push(new P(ie,s)),t.push(new P(so,e.value));continue}if(e.type!==Le&&e.type!==pt)throw new Error("expected variable for assignment");this.parseVariableAssignmentExpression(s),t.push(new P(lt,e.value)),t.push(new P(ie,s)),t.push(He("="))}};H.prototype.parseConditionalExpression=function(t){for(this.parseOrExpression(t);this.accept(j,"?");){var e=[],s=[];this.parseConditionalExpression(e),this.expect(j,":"),this.parseConditionalExpression(s),t.push(new P(ie,e)),t.push(new P(ie,s)),t.push(hu("?"))}};H.prototype.parseOrExpression=function(t){for(this.parseAndExpression(t);this.accept(j,"or");){var e=[];this.parseAndExpression(e),t.push(new P(ie,e)),t.push(He("or"))}};H.prototype.parseAndExpression=function(t){for(this.parseComparison(t);this.accept(j,"and");){var e=[];this.parseComparison(e),t.push(new P(ie,e)),t.push(He("and"))}};var Xy=["==","!=","<","<=",">=",">","in"];H.prototype.parseComparison=function(t){for(this.parseAddSub(t);this.accept(j,Xy);){var e=this.current;this.parseAddSub(t),t.push(He(e.value))}};var Jy=["+","-","||"];H.prototype.parseAddSub=function(t){for(this.parseTerm(t);this.accept(j,Jy);){var e=this.current;this.parseTerm(t),t.push(He(e.value))}};var eb=["*","/","%"];H.prototype.parseTerm=function(t){for(this.parseFactor(t);this.accept(j,eb);){var e=this.current;this.parseFactor(t),t.push(He(e.value))}};H.prototype.parseFactor=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.save(),this.accept(j,s)){if(this.current.value!=="-"&&this.current.value!=="+"){if(this.nextToken.type===Fe&&this.nextToken.value==="("){this.restore(),this.parseExponential(t);return}else if(this.nextToken.type===ei||this.nextToken.type===io||this.nextToken.type===xs||this.nextToken.type===Fe&&this.nextToken.value===")"){this.restore(),this.parseAtom(t);return}}var r=this.current;this.parseFactor(t),t.push(oo(r.value))}else this.parseExponential(t)};H.prototype.parseExponential=function(t){for(this.parsePostfixExpression(t);this.accept(j,"^");)this.parseFactor(t),t.push(He("^"))};H.prototype.parsePostfixExpression=function(t){for(this.parseFunctionCall(t);this.accept(j,"!");)t.push(oo("!"))};H.prototype.parseFunctionCall=function(t){var e=this.tokens.unaryOps;function s(n){return n.value in e}if(this.accept(j,s)){var r=this.current;this.parseAtom(t),t.push(oo(r.value))}else for(this.parseMemberExpression(t);this.accept(Fe,"(");)if(this.accept(Fe,")"))t.push(new P(Dt,0));else{var o=this.parseArgumentList(t);t.push(new P(Dt,o))}};H.prototype.parseArgumentList=function(t){for(var e=0;!this.accept(Fe,")");)for(this.parseExpression(t),++e;this.accept(io);)this.parseExpression(t),++e;return e};H.prototype.parseMemberExpression=function(t){for(this.parseAtom(t);this.accept(j,".")||this.accept(At,"[");){var e=this.current;if(e.value==="."){if(!this.allowMemberAccess)throw new Error('unexpected ".", member access is not permitted');this.expect(Jn),t.push(new P(pt,this.current.value))}else if(e.value==="["){if(!this.tokens.isOperatorEnabled("["))throw new Error('unexpected "[]", arrays are disabled');this.parseExpression(t),this.expect(At,"]"),t.push(He("["))}else throw new Error("unexpected symbol: "+e.value)}};function tb(t,e){return Number(t)+Number(e)}function sb(t,e){return t-e}function rb(t,e){return t*e}function ob(t,e){return t/e}function nb(t,e){return t%e}function ib(t,e){return Array.isArray(t)&&Array.isArray(e)?t.concat(e):""+t+e}function ab(t,e){return t===e}function cb(t,e){return t!==e}function lb(t,e){return t>e}function ub(t,e){return t<e}function db(t,e){return t>=e}function hb(t,e){return t<=e}function fb(t,e){return!!(t&&e)}function pb(t,e){return!!(t||e)}function gb(t,e){return _t(e,t)}function mb(t){return(Math.exp(t)-Math.exp(-t))/2}function yb(t){return(Math.exp(t)+Math.exp(-t))/2}function bb(t){return t===1/0?1:t===-1/0?-1:(Math.exp(t)-Math.exp(-t))/(Math.exp(t)+Math.exp(-t))}function vb(t){return t===-1/0?t:Math.log(t+Math.sqrt(t*t+1))}function wb(t){return Math.log(t+Math.sqrt(t*t-1))}function Eb(t){return Math.log((1+t)/(1-t))/2}function Xi(t){return Math.log(t)*Math.LOG10E}function Mb(t){return-t}function Tb(t){return!t}function _b(t){return t<0?Math.ceil(t):Math.floor(t)}function Sb(t){return Math.random()*(t||1)}function Ji(t){return ti(t+1)}function Ob(t){return isFinite(t)&&t===Math.round(t)}var Ib=4.7421875,Io=[.9999999999999971,57.15623566586292,-59.59796035547549,14.136097974741746,-.4919138160976202,3399464998481189e-20,4652362892704858e-20,-9837447530487956e-20,.0001580887032249125,-.00021026444172410488,.00021743961811521265,-.0001643181065367639,8441822398385275e-20,-26190838401581408e-21,36899182659531625e-22];function ti(t){var e,s;if(Ob(t)){if(t<=0)return isFinite(t)?1/0:NaN;if(t>171)return 1/0;for(var r=t-2,o=t-1;r>1;)o*=r,r--;return o===0&&(o=1),o}if(t<.5)return Math.PI/(Math.sin(Math.PI*t)*ti(1-t));if(t>=171.35)return 1/0;if(t>85){var n=t*t,i=n*t,a=i*t,c=a*t;return Math.sqrt(2*Math.PI/t)*Math.pow(t/Math.E,t)*(1+1/(12*t)+1/(288*n)-139/(51840*i)-571/(2488320*a)+163879/(209018880*c)+5246819/(75246796800*c*t))}--t,s=Io[0];for(var u=1;u<Io.length;++u)s+=Io[u]/(t+u);return e=t+Ib+.5,Math.sqrt(2*Math.PI)*Math.pow(e,t+.5)*Math.exp(-e)*s}function $b(t){return Array.isArray(t)?t.length:String(t).length}function ea(){for(var t=0,e=0,s=0;s<arguments.length;s++){var r=Math.abs(arguments[s]),o;e<r?(o=e/r,t=t*o*o+1,e=r):r>0?(o=r/e,t+=o*o):t+=r}return e===1/0?1/0:e*Math.sqrt(t)}function ta(t,e,s){return t?e:s}function Cb(t,e){return typeof e>"u"||+e==0?Math.round(t):(t=+t,e=-+e,isNaN(t)||!(typeof e=="number"&&e%1===0)?NaN:(t=t.toString().split("e"),t=Math.round(+(t[0]+"e"+(t[1]?+t[1]-e:-e))),t=t.toString().split("e"),+(t[0]+"e"+(t[1]?+t[1]+e:e))))}function Db(t,e,s){return s&&(s[t]=e),e}function xb(t,e){return t[e|0]}function Ab(t){return arguments.length===1&&Array.isArray(t)?Math.max.apply(Math,t):Math.max.apply(Math,arguments)}function Rb(t){return arguments.length===1&&Array.isArray(t)?Math.min.apply(Math,t):Math.min.apply(Math,arguments)}function Pb(t,e){if(typeof t!="function")throw new Error("First argument to map is not a function");if(!Array.isArray(e))throw new Error("Second argument to map is not an array");return e.map(function(s,r){return t(s,r)})}function kb(t,e,s){if(typeof t!="function")throw new Error("First argument to fold is not a function");if(!Array.isArray(s))throw new Error("Second argument to fold is not an array");return s.reduce(function(r,o,n){return t(r,o,n)},e)}function Lb(t,e){if(typeof t!="function")throw new Error("First argument to filter is not a function");if(!Array.isArray(e))throw new Error("Second argument to filter is not an array");return e.filter(function(s,r){return t(s,r)})}function Fb(t,e){if(!(Array.isArray(e)||typeof e=="string"))throw new Error("Second argument to indexOf is not a string or array");return e.indexOf(t)}function Nb(t,e){if(!Array.isArray(e))throw new Error("Second argument to join is not an array");return e.join(t)}function Ub(t){return(t>0)-(t<0)||+t}var sa=1/3;function jb(t){return t<0?-Math.pow(-t,sa):Math.pow(t,sa)}function Bb(t){return Math.exp(t)-1}function Hb(t){return Math.log(1+t)}function Kb(t){return Math.log(t)/Math.LN2}function gt(t){this.options=t||{},this.unaryOps={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh||mb,cosh:Math.cosh||yb,tanh:Math.tanh||bb,asinh:Math.asinh||vb,acosh:Math.acosh||wb,atanh:Math.atanh||Eb,sqrt:Math.sqrt,cbrt:Math.cbrt||jb,log:Math.log,log2:Math.log2||Kb,ln:Math.log,lg:Math.log10||Xi,log10:Math.log10||Xi,expm1:Math.expm1||Bb,log1p:Math.log1p||Hb,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc||_b,"-":Mb,"+":Number,exp:Math.exp,not:Tb,length:$b,"!":Ji,sign:Math.sign||Ub},this.binaryOps={"+":tb,"-":sb,"*":rb,"/":ob,"%":nb,"^":Math.pow,"||":ib,"==":ab,"!=":cb,">":lb,"<":ub,">=":db,"<=":hb,and:fb,or:pb,in:gb,"=":Db,"[":xb},this.ternaryOps={"?":ta},this.functions={random:Sb,fac:Ji,min:Rb,max:Ab,hypot:Math.hypot||ea,pyt:Math.hypot||ea,pow:Math.pow,atan2:Math.atan2,if:ta,gamma:ti,roundTo:Cb,map:Pb,fold:kb,filter:Lb,indexOf:Fb,join:Nb},this.consts={E:Math.E,PI:Math.PI,true:!0,false:!1}}gt.prototype.parse=function(t){var e=[],s=new H(this,new z(this,t),{allowMemberAccess:this.options.allowMemberAccess});return s.parseExpression(e),s.expect(xs,"EOF"),new Me(e,this)};gt.prototype.evaluate=function(t,e){return this.parse(t).evaluate(e)};var mu=new gt;gt.parse=function(t){return mu.parse(t)};gt.evaluate=function(t,e){return mu.parse(t).evaluate(e)};var ra={"+":"add","-":"subtract","*":"multiply","/":"divide","%":"remainder","^":"power","!":"factorial","<":"comparison",">":"comparison","<=":"comparison",">=":"comparison","==":"comparison","!=":"comparison","||":"concatenate",and:"logical",or:"logical",not:"logical","?":"conditional",":":"conditional","=":"assignment","[":"array","()=":"fndef"};function qb(t){return ra.hasOwnProperty(t)?ra[t]:t}gt.prototype.isOperatorEnabled=function(t){var e=qb(t),s=this.options.operators||{};return!(e in s)||!!s[e]};var zb=Object.defineProperty,Vb=Object.getOwnPropertyDescriptor,Gb=(t,e,s)=>e in t?zb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Yb=(t,e,s,r)=>{for(var o=r>1?void 0:r?Vb(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o},Wb=(t,e,s)=>(Gb(t,e+"",s),s);const Qb="kos-expression-evaluator-model";class Zb{constructor(e,s,r,o){l(this,"name");l(this,"expression");l(this,"expr");l(this,"getContextData",null);l(this,"_lastResult",{value:void 0});this.name=e,this.expression=s,this.expr=r,this.getContextData=o,this._lastResult={value:void 0,error:void 0}}get result(){return this._lastResult}updateResult(e){this._lastResult=e}evaluate(e){try{return{value:this.expr.evaluate(e),error:void 0}}catch(s){return{value:void 0,error:s instanceof Error?s.message:String(s)}}}}let Tr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"parser");l(this,"_data");l(this,"_expressions",new Map);l(this,"_results");l(this,"_contextRevision",0);this.id=t,this.logger=s.logger,this._data=Ie(),this._results=Ie(),this.parser=new gt}get data(){return this._data}get contextRevision(){return this._contextRevision}setContextData(t){this._data.setValues(t),X(()=>{this._contextRevision++,this.logger.debug("Context revision incremented to:",this._contextRevision)})}updateContextValue(t,e){this._data[t]=e}updateNestedValue(t,e){const s=t.split("."),r=s.pop();if(!r){this.logger.error(`Invalid path "${t}" - cannot be empty`);return}let o=this._data;for(const n of s)(o[n]===void 0||o[n]===null)&&(o[n]={}),o=o[n];o[r]=e,this.logger.debug(`Updated nested context value "${t}" to:`,e)}addModelToContext(t,e){this._data[t]=e}addExpression(t,e){try{const s=this.parser.parse(e),r=new Zb(t,e,s,()=>this.data);this._expressions.set(t,r),this.evaluateExpression(t),this.logger.debug(`Added expression "${t}": ${e}`)}catch(s){throw this.logger.error(`Failed to parse expression "${t}"`,s),s}}removeExpression(t){const e=this._expressions.delete(t);return e?(delete this._results[t],this.logger.debug(`Removed expression "${t}"`)):this.logger.warn(`Attempted to remove non-existent expression "${t}". Available expressions: [${this.expressionNames.join(", ")}]`),e}getExpression(t){const e=this._expressions.get(t);return e||this.logger.warn(`Expression "${t}" not found. Available expressions: [${this.expressionNames.join(", ")}]`),e}getExpressionValue(t){const e=this._expressions.get(t);if(!e){this.logger.warn(`Expression "${t}" not found. Available expressions: [${this.expressionNames.join(", ")}]`);return}return e.result}getCachedExpressionValue(t){const e=this._expressions.get(t);if(e)return e.result}get expressions(){return Array.from(this._expressions.values())}get expressionNames(){return Array.from(this._expressions.keys())}get results(){return this.evaluateAllExpressions(),this._results}evaluateAllExpressions(){Array.from(this._expressions.keys()).forEach(e=>{this._expressions.get(e)&&this.evaluateExpression(e)})}evaluateExpression(t){this.logger.debug(`Evaluating expression: ${String(t)}`);const e=this._expressions.get(t);if(!e){this.logger.warn(`Expression "${String(t)}" not found`);return}const s=e.evaluate(this.data);this.logger.debug(`Expression "${String(t)}" evaluated to:`,s);const r=e.result;(s.value!==r.value||s.error!==r.error)&&(this.logger.debug(`Expression "${String(t)}" result changed from`,r,"to",s),e.updateResult(s),this.updateResult(t,s))}updateResult(t,e){this.logger.debug(`ExpressionEvaluator.updateResult called for "${t}":`,e),X(()=>{this._results[t]=e})}createExpression(t){const e=ut();return this.addExpression(e,t),e}};Wb(Tr,"Registration");Tr=Yb([R({modelTypeId:Qb,singleton:!1})],Tr);const yu=Tr.Registration,Xb=m.createLogger({name:"kos-log-manager-service",group:"Services"}),Jb="/api/kos/logs/overrides",bu=async()=>(Xb.debug("sending GET for kos-log-manager"),await Ae.get(Jb)),ev=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:bu},Symbol.toStringTag,{value:"Module"}));var tv=Object.defineProperty,sv=Object.getOwnPropertyDescriptor,ao=(t,e,s,r)=>{for(var o=r>1?void 0:r?sv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&tv(e,s,o),o};const vu="kos-log-manager-model",rv="/kos/logs/override/add/*",ov="/kos/logs/override/remove/*",nv=t=>{if(typeof t=="string")return t;if(typeof t=="number")switch(t){case 0:return"trace";case 1:return"debug";case 2:return"info";case 3:return"warn";case 4:return"error";default:return"info"}return"info"};let Rt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new An}updateModel(t){}resolveLoggers(){const t=m.getLoggers(),s=Object.entries(t).map(([r,o])=>({name:r,level:nv(o.getLevel())})).reduce((r,{name:o,level:n})=>(r[o]={name:o,level:n},r),{});return this.logger.debug("Resolved loggers",s),s}async getAllLoggers(t,e){const s=Object.values(this.resolveLoggers());return e==null||e.send(s),s}setLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=m.getLoggers()[r.name];if(!o){this.logger.debug(`Logger ${r.name} not found`);return}o.setLevel(t.level)});const s=m.getLoggers()[t.name];if(!s){this.logger.debug(`Logger ${t.name} not found`);return}s.setLevel(t.level),globalThis.kos.logOverrides=this._overrides.data}resetLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=m.getLoggers()[r.name];o||this.logger.debug(`Logger ${r.name} not found`),o==null||o.resetLevel()});const s=m.getLoggers()[t.name];s||this.logger.debug(`Logger ${t.name} not found`),s==null||s.resetLevel(),globalThis.kos.logOverrides=this._overrides.data}handleOverrideAdded(t,e){var s;this.logger.debug(`Override received for node type ${((s=e.wildcardCapture)==null?void 0:s.nodeType)??"unknown"}`),this._overrides.addModel({...t,id:t.name}),this.setLogLevels(t)}handleOverrideRemoved(t){this._overrides.removeModel(t.name),this.resetLogLevels(t)}async init(){this.logger.debug(`initializing kos-log-manager ${this.id}`)}async load(){this.logger.debug(`loading kos-log-manager ${this.id}`),this.resolveLoggers();const[t,e]=await bu();if(t){this.logger.error("Failed to load log overrides",t);return}const s=(e==null?void 0:e.filter(r=>{var o;return((o=r.type)==null?void 0:o.toUpperCase())==="UI"}).map(r=>({name:r.name??"",type:r.type??"",level:r.level??"info",id:r.name||""})))??[];this._overrides.addAll(s),s.forEach(r=>{this.setLogLevels(r)})}};ao([$c("/api/kos/ui/loggers")],Rt.prototype,"getAllLoggers",1);ao([B({topic:rv,websocket:!0,wildcardName:"nodeType"})],Rt.prototype,"handleOverrideAdded",1);ao([B({topic:ov,websocket:!0,wildcardName:"nodeType"})],Rt.prototype,"handleOverrideRemoved",1);Rt=ao([R(vu)],Rt);const wu=new Se({class:Rt,type:vu}),{URL:Vs}=ce(),{postModel:si,getOne:iv}=oe.build({basePath:`${Vs}/api/kos-time`});m.createLogger({name:"kos-time-service",group:"Services"});const Eu=async t=>{const e=await si({model:t,urlOverride:`${Vs}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Mu=async t=>{const e=await si({model:t,urlOverride:`${Vs}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Tu=async t=>{const e=await si({model:{},urlOverride:`${Vs}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},_u=async()=>{const t=await iv({urlOverride:`${Vs}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},av=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:_u,setDate:Mu,setTime:Eu,setTimezone:Tu},Symbol.toStringTag,{value:"Module"}));var cv=Object.defineProperty,lv=Object.getOwnPropertyDescriptor,co=(t,e,s,r)=>{for(var o=r>1?void 0:r?lv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&cv(e,s,o),o};const os="kos-time-model",uv="/kos/time/time",dv="/kos/time/day",hv="/kos/time/timezone";let Pt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"timezone");this.id=t,this.logger=s.logger,this.timezone=""}async updateSystemTime(t){await Eu(t)}async updateSystemDate(t){await Mu(t)}async updateSystemTimezone(t){await Tu(t)}handleTimeChange(){q(Ts.TIME_CHANGE,{})}handleDayChange(){q(Ts.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),q(Ts.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await _u();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};co([B({topic:uv,websocket:!0})],Pt.prototype,"handleTimeChange",1);co([B({topic:dv,websocket:!0})],Pt.prototype,"handleDayChange",1);co([B({topic:hv,websocket:!0})],Pt.prototype,"handleTimeZoneChange",1);Pt=co([R(os)],Pt);const _r={registration:{[os]:{class:Pt,singleton:!0}},type:os,predicate:_e(os),factory:ae.Singleton.create(os)};var fv=Object.defineProperty,pv=Object.getOwnPropertyDescriptor,Su=(t,e,s,r)=>{for(var o=r>1?void 0:r?pv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&fv(e,s,o),o};const Ou="log-block-container-model";let Sr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new xe({parentId:t,sortKey:"blockNum"})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing log-block-container container ${this.id}`)}async load(){this.logger.debug(`loading log-block-container container ${this.id}`)}};Su([De],Sr.prototype,"_models",2);Sr=Su([R(Ou)],Sr);const gv=m.createLogger({name:"log-stream-container-service",group:"Services"}),Iu=()=>{var r;const t=be(),s=(t==null?void 0:t.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return m.error(`getKosConnectionId: ${s}`),s},Wt=Iu(),mv="/api/kos/logs/node/{nodeId}/streams",$u=async()=>(gv.debug("sending GET for log-stream-container"),await Ae.get(mv,{path:{nodeId:"primary"}},{destinationAddress:Wt})),Cu=async(t,e="primary")=>{await Ae.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:Wt})},Du=async t=>{await Ae.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:Wt})},yv=async()=>{await Ae.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:Wt})},xu=async t=>await Ae.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:Wt}),Au=async(t,e)=>await Ae.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:Wt}),bv=Object.freeze(Object.defineProperty({__proto__:null,createOverride:yv,getKosConnectionId:Iu,getLogStreamBlock:Au,getLogStreamBlocks:xu,getLogStreams:$u,subscribeToLogStream:Cu,unsubscribeFromLogStream:Du},Symbol.toStringTag,{value:"Module"}));var vv=Object.getOwnPropertyDescriptor,wv=(t,e,s,r)=>{for(var o=r>1?void 0:r?vv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Ru="log-block-model";let qo=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"stream");l(this,"blockNum");l(this,"startLineNum");l(this,"endLineNum");l(this,"startTime");l(this,"endTime");l(this,"lineCount");l(this,"lines");l(this,"inc");this.id=t,this.logger=s.logger,this.nodeId=e.nodeId,this.stream=e.stream,this.blockNum=e.blockNum,this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount,this.lines=[],this.inc=0}async syncLines(){const[t,e]=await Au(this.stream,this.blockNum);if(t){this.logger.error(`Failed to get log block ${this.blockNum}`);return}e&&this.addLines(e.lines,!0)}updateModel(t){this.startLineNum=t.startLineNum,this.endLineNum=t.endLineNum,this.startTime=t.startTime,this.endTime=t.endTime,this.lineCount=t.lineCount}addLines(t,e){const s=e?[]:this.lines;this.lines=[...s,...t],this.inc+=1}async init(){this.logger.debug(`initializing log-block ${this.id}`)}async load(){this.logger.debug(`loading log-block ${this.id}`)}};qo=wv([R(Ru)],qo);const As=new ve({class:qo,type:Ru}),lo=new ve({class:Sr,type:Ou});lo.addRelatedModel(As);var Ev=Object.defineProperty,Mv=Object.getOwnPropertyDescriptor,Pu=(t,e,s,r)=>{for(var o=r>1?void 0:r?Mv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ev(e,s,o),o};const ku="log-stream-model";let Or=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"_blocks");l(this,"name");l(this,"currentBlockId");l(this,"isResetting");l(this,"generatorInstance");l(this,"shouldStop",!1);this.id=t,this.logger=s.logger,this.currentBlockId="",this.name=e.name,this.nodeId=e.nodeId,this.isResetting=!0,this._blocks=lo.instance(`${t}-blocks`).options({}).build()}get firstLineNum(){const t=this.populated[0];return t?t.startLineNum:0}get currentBlock(){const t=this.currentBlockId;return this._blocks.getModel(t)}get populated(){return this._blocks.data.filter(t=>t.lines.length>0)}get blocks(){return this._blocks.data}get totalLineCount(){return this.populated.reduce((t,e)=>t+e.lineCount,0)}accept(t){t.visit(this)}updateBlock(t){var r;let e=this._blocks.models.getModel(`${t.stream}-block-${t.blockNum}`);const s={nodeId:t.nodeId,blockNum:t.blockNum,endLineNum:t.endLineNum,lineCount:t.lineCount,startLineNum:t.startLineNum,stream:this.name,endTime:new Date(t.endTime),startTime:new Date(t.startTime)};e||(e=As.instance(`${t.stream}-block-${t.blockNum}`).options(s).build(),this._blocks.addModel(e)),e&&e.updateModel(s),(!this.currentBlock||t.blockNum>=((r=this.currentBlock)==null?void 0:r.blockNum))&&(this.currentBlockId=`${t.stream}-block-${t.blockNum}`)}addBlock(t){var s;const e=As.instance(`${t.stream}-block-${t.blockNum}`).options({nodeId:t.nodeId,blockNum:t.blockNum,endLineNum:t.endLineNum,lineCount:t.lineCount,startLineNum:t.startLineNum,stream:this.name,endTime:new Date(t.endTime),startTime:new Date(t.startTime)}).build();this._blocks.addModel(e),(!this.currentBlock||t.blockNum>=((s=this.currentBlock)==null?void 0:s.blockNum))&&(this.currentBlockId=`${t.stream}-block-${t.blockNum}`)}removeBlock(t){this._blocks.models.removeModel(`${this.name}-block-${t}`)}async subscribe(){await Cu(this.name)}async unsubscribe(){await Du(this.name)}async reset(){if(this.isResetting=!0,this.populated.length>0)return;this.logger.debug(`resetting log-stream ${this.id}`);for(const e of this._blocks.models.data)e.lines=[];const t=this._blocks.data[this._blocks.data.length-1];t&&await t.syncLines(),this.isResetting=!1}async init(){this.logger.debug(`initializing log-stream ${this.id}`)}async load(){this.logger.debug(`loading log-stream ${this.id}`);const[t,e]=await xu(this.name);if(t){this.logger.error(`Error loading log stream: ${t}`);return}if(e)for(const r of e)this.addBlock(r);const s=this._blocks.data[this._blocks.data.length-1];if(s&&await s.syncLines(),this._blocks.data.length>1){const r=this._blocks.data[this._blocks.data.length-2];r&&await r.syncLines()}}start(){return this.shouldStop=!1,this.generatorInstance=this.streamLogs(),this.generatorInstance}stop(){var t;this.shouldStop=!0,(t=this.generatorInstance)==null||t.next(),console.log("Requested generator stop.")}async*streamLogs(){const t=[];let e=null,s=0,r=this.currentBlockId;const o=Rl(()=>{const n=this.currentBlock;return n?{blockId:this.currentBlockId,lineCount:n.lines.length}:null},n=>{const i=this.currentBlock;if(i)if(r!==(n==null?void 0:n.blockId))r=n==null?void 0:n.blockId,s=0,t.push(...i.lines);else{const a=i.lines.slice(s);t.push(...a),s+=a.length}e&&(e(),e=null)},{fireImmediately:!0});try{for(const n of this.populated.filter(i=>i!==this.currentBlock))for(const i of n.lines)yield i;for(;;)for(t.length===0&&await new Promise(n=>e=n);t.length>0;)yield t.shift()}finally{o()}}};Pu([De],Or.prototype,"_blocks",2);Or=Pu([R(ku)],Or);const _s=new ve({class:Or,type:ku});var Tv=Object.defineProperty,_v=Object.getOwnPropertyDescriptor,mt=(t,e,s,r)=>{for(var o=r>1?void 0:r?_v(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Tv(e,s,o),o};const Lu="log-stream-container-model",Sv="/kos/logs/subscription/addBlock/*",Ov="/kos/logs/subscription/updateBlock/*",Iv="/kos/logs/subscription/removeBlock/*",$v="/kos/logs/subscription/lines/*",Fu="/kos/logs/streams/add/*";let Ne=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"selectedStream");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new xe({parentId:t}),this.selectedStream=void 0}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}updateModel(t){}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}updateSelectedStream(t){this.selectedStream=t}handleStreamAdded(t){this.logger.debug(`Received topic: ${Fu}`);const e=t.stream,s=_s.instance(e).options({name:e,nodeId:"primary"}).build();this.addModel(s)}handleAddBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.addBlock(t)}handleRemoveBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.removeBlock(t.blockNum)}handleUpdateBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.updateBlock(t)}handleLogLine(t,e){var o;this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&((o=r.currentBlock)==null||o.addLines(t.lines))}async init(){this.logger.debug(`initializing log-stream-container container ${this.id}`)}async subscribeToLogStream(t){const e=_s.instance(t).options({name:t,nodeId:"primary"}).build();this.addModel(e),await e.subscribe()}async load(){this.logger.debug(`loading log-stream-container container ${this.id}`);const[t,e]=await $u();if(t){this.logger.error(`Error loading log-streams: ${t}`);return}e&&e.forEach(s=>{const r=_s.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};mt([De],Ne.prototype,"_models",2);mt([B({topic:[Fu],websocket:!0})],Ne.prototype,"handleStreamAdded",1);mt([B({topic:[Sv],websocket:!0})],Ne.prototype,"handleAddBlock",1);mt([B({topic:[Iv],websocket:!0})],Ne.prototype,"handleRemoveBlock",1);mt([B({topic:[Ov],websocket:!0})],Ne.prototype,"handleUpdateBlock",1);mt([B({topic:[$v],websocket:!0})],Ne.prototype,"handleLogLine",1);Ne=mt([R(Lu)],Ne);const Gs=new Se({class:Ne,type:Lu});Gs.addRelatedModel(_s);Gs.addRelatedModel(lo);Gs.addRelatedModel(As);const Cv=t=>t.rank!==void 0,Dv=t=>t.visibleRole!==void 0,xv=t=>t.color!==void 0,Av=t=>{const e=t.info;return Cv(e)?e.rank:0},Rv=t=>{const e=t.info;return xv(e)?e.color:"orange"},Pv=t=>{const e=t.info;return Dv(e)?e.visibleRole:"TECHNICIAN"},{URL:uo}=ce(),{getAll:kv,postModel:Nu}=oe.build({basePath:`${uo}/api/kos/troubles`}),Uu=async t=>await kv({urlOverride:`${uo}${t}`}),ju=async(t,e="/api/kos/troubles",s)=>{try{const r=await Nu({model:{},urlOverride:`${uo}${e}/resolve/${t}`,tracker:s});return r!=null&&r.data&&ct.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:Ge.Fail,tracker:s,reason:"Failed to resolve trouble"};return ct.initiateFuture(o),o}},Lv=async(t,e="/api/kos/troubles",s)=>{try{const r=await Nu({model:t,urlOverride:`${uo}${e}/resolve/`,tracker:s});return r!=null&&r.data&&ct.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:Ge.Fail,tracker:s,reason:"Failed to resolve troubles"};return ct.initiateFuture(o),o}},Fv=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:Lv,getTroubles:Uu,resolveTrouble:ju},Symbol.toStringTag,{value:"Module"})),Ir="troubleDataMapper",or=new Map;js(Ir,{register:(t,e)=>{var s;or.has(t)||or.set(t,[]),(s=or.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=or.get(t);if(!s)return{...e.data};const r=s.map(i=>i(e));return(await Promise.allSettled(r)).reduce((i,a)=>(a.status==="fulfilled"?i={...i,...a.value}:m.info(`Trouble mapper ${t} failed: ${a.reason}`),i),{...e.data})}});const Ys="troubleMapper",nr=new Map;js(Ys,{register:(t,e)=>{var s;nr.has(t)||nr.set(t,[]),(s=nr.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=nr.get(t);if(!s)return[];const r=s.map(i=>i(e)),n=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(m.info(`Trouble mapper ${t} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});$[Ys].register("nozzle",async t=>[t.data.nozzlePath]);$[Ys].register("path",async t=>[t.data.path]);const Nv=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(n=>$[Ys].execute(n,t));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>e.add(i))}),Array.from(e)},Bu=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>$[Ir].execute(i,t)),r=$[Ir].execute(t.type,t);s.push(r);const n=(await Promise.allSettled(s)).reduce((i,a)=>(a.status==="fulfilled"&&(i={...i,...a.value}),i),{});return{...t.data,...n}};class Uv{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class jv{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class Et{static getHandler(e){switch(e){case"ResolvableTrouble":return new Uv;case"BlockPumpTrouble":return new jv;default:return}}}var Bv=Object.defineProperty,Hv=Object.getOwnPropertyDescriptor,Hu=(t,e,s,r)=>{for(var o=r>1?void 0:r?Hv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Bv(e,s,o),o};const ns="trouble-model";function ir(t){return typeof t.shouldDefer=="boolean"}let $r=class{constructor(t,{resolvable:e,tags:s,info:r,id:o,clientData:n,rank:i,ifaces:a,type:c,group:u,createTime:d,role:h,color:f,servicePath:p,...y},w){l(this,"id");l(this,"logger");l(this,"_troubleId");l(this,"_resolvable");l(this,"type");l(this,"futureHandler");l(this,"ifaces");l(this,"clientData");l(this,"info");l(this,"role");l(this,"color");l(this,"tags");l(this,"data");l(this,"rank");l(this,"servicePath");l(this,"group");l(this,"createTime");l(this,"_mapped",{});this.id=t,this.logger=w.logger,this.type=c,this._troubleId=o,this._resolvable=!!e,this.ifaces=a,this.rank=i,this.role=h,this.color=f,this.tags=s,this.info=r,this.group=u,this.servicePath=p??"/api/kos/troubles",this.createTime=d,this.clientData=n,this.data={},Object.assign(this.data,y),this.futureHandler=new Xr(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=Et.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Et.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=Et.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Et.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=Et.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=Et.getHandler(this.type))==null?void 0:t.subtitle)||"Trouble"}get troubleId(){return this._troubleId}get resolvable(){return this._resolvable}get future(){return this.futureHandler.future}async resolveMappedData(){return await Bu(this)}get deferredCompanion(){const t=Lo(this.id,e=>ir(e));if(t&&ir(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=Lo(this.id,e=>ir(e));return t&&ir(t.modelData)?t.modelData.shouldDefer:!1}clearDefer(){var t;(t=this.deferredCompanion)==null||t.clearDefer()}defer(){var t;(t=this.deferredCompanion)==null||t.defer()}getChildren(){return[...this.futureHandler.allFutures]}async resolve(t){var e;if(!this._resolvable)throw this.logger.error(`attempting to resolve an unresolvable trouble with id ${this._troubleId}`),new Error("Trouble is not resolvable");if(this.shouldDefer){(e=this.deferredCompanion)==null||e.defer();return}return await ju(this._troubleId,this.servicePath,t)}};Hu([wi()],$r.prototype,"resolve",1);$r=Hu([R(ns)],$r);const Rs={registration:{[ns]:{class:$r,singleton:!1}},type:ns,predicate:_e(ns),factory:ae.Factory.create(ns)};var Ku=Object.defineProperty,Kv=Object.getOwnPropertyDescriptor,qv=(t,e,s)=>e in t?Ku(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ri=(t,e,s,r)=>{for(var o=r>1?void 0:r?Kv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ku(e,s,o),o},zv=(t,e,s)=>(qv(t,e+"",s),s);function oa(t){return $.propertyMapper.hasMapper(Ee.TroubleRank)?$.propertyMapper.executeMapper(Ee.TroubleRank,t):Av(t)}function na(t){return($.propertyMapper.hasMapper(Ee.TroubleColor)?$.propertyMapper.executeMapper(Ee.TroubleColor,t):Rv(t)).toLowerCase()}function ia(t){return($.propertyMapper.hasMapper(Ee.TroubleRole)?$.propertyMapper.executeMapper(Ee.TroubleRole,t):Pv(t)).toLowerCase()}const Vv="trouble-container-model";class me{}l(me,"INDEX_TROUBLES_BY_IFACE","byIface"),l(me,"INDEX_TROUBLES_BY_TYPE","byType"),l(me,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(me,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(me,"SORT_KEY_RANK","rank"),l(me,"TROUBLES_DEFERRED","true");let kt=class{constructor(t,e){l(this,"id");l(this,"servicePath","/api/kos/troubles");this.id=t,this.servicePath=e.servicePath??this.servicePath}async load(){this.logger.debug("loading trouble container");const t=await Uu(this.servicePath);try{t==null||t.data.forEach(e=>{const s={...e,servicePath:this.servicePath,rank:oa(e),color:na(e),role:ia(e),id:String(e.id)},r=Rs.factory(`trouble-${e.id}`)(s);this.troubles.addModel(r)})}catch(e){throw this.logger.error(e),e}}handleTroubleRemoved(t){const e=`trouble-${t}`,s=this.troubles.getModel(e);this.troubles.removeModel(e),s&&Oe(s)}handleTroubleAdded(t){const e={...t,servicePath:this.servicePath,rank:oa(t),color:na(t),role:ia(t),id:String(t.id)};if(e.role==="NONE")return;const s=Rs.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};zv(kt,"Registration");ri([B({topic:"/kos/trouble/remove",websocket:!0,lifecycle:x.INIT})],kt.prototype,"handleTroubleRemoved",1);ri([B({topic:"/kos/trouble/add",websocket:!0})],kt.prototype,"handleTroubleAdded",1);kt=ri([R({modelTypeId:Vv,singleton:!0}),Ac(),Ic({containerProperty:"troubles",containerOptions:{indexMap:{[me.INDEX_TROUBLES_BY_IFACE]:Nv,[me.INDEX_TROUBLES_BY_TYPE]:"type",[me.INDEX_TROUBLES_BY_GROUP]:"group",[me.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:me.SORT_KEY_RANK}})],kt);const Lt=kt.Registration,{URL:qu}=ce(),{getAll:Gv}=oe.build({basePath:`${qu}/api/kos/ota`}),aa=m.createLogger({name:"ota-service",group:"Services"}),Yv=async()=>{aa.debug("sending GET request to /api/kos/ota/artifacts");const t=await Gv({urlOverride:`${qu}/api/kos/ota/artifacts`});return aa.debug("getArtifacts - response:",t),t==null?void 0:t.data};var Wv=Object.defineProperty,Qv=Object.getOwnPropertyDescriptor,ho=(t,e,s,r)=>{for(var o=r>1?void 0:r?Qv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Wv(e,s,o),o};const zu="ota-model",Zv=t=>{let e=null;for(const s in t){const r=t[s],o=r.lastUpdateTime;(!e||e.lastUpdateTime<o)&&(e=r)}return e},$o=t=>{const e=t.artifactInfo,s=Zv(t.requests),r=(e==null?void 0:e.identifier)||(s==null?void 0:s.kabId);if(!r)return;let o;switch(t.status){case"INSTALLED":o="ready";break;case"INVALID":o="error";break;case"MISSING":o=((s==null?void 0:s.currentSize)||0)>0?"downloading":"idle";break;case"STAGED":o="pending"}const n=e===void 0;return{id:r,manifest:n,label:e==null?void 0:e.version,name:e==null?void 0:e.name,status:o,error:o==="error"?s==null?void 0:s.lastErrorReason:void 0,errorCount:o==="error"?s==null?void 0:s.errorCount:0,progress:o==="downloading"&&s&&!n?s.currentSize/(e==null?void 0:e.size)*100:void 0,size:e==null?void 0:e.size}};let Ft=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"data",new An);l(this,"troubleContainer");this.id=t,this.logger=s.logger}get downloadInProgressTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTADownloadInProgressTrouble"))==null?void 0:e[0]}get updatePendingTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAUpdatePendingTrouble"))==null?void 0:e[0]}get pausedDueToErrorsTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAPausedDueToErrorsTrouble"))==null?void 0:e[0]}get updates(){return this.data}get status(){return this.pausedDueToErrorsTrouble?"error":this.downloadInProgressTrouble?"downloading":this.updatePendingTrouble?"pending":"idle"}installAndReboot(){var t;this.updatePendingTrouble||this.logger.error("installAndReboot - OTAUpdatePendingTrouble not present"),this.logger.debug("installAndReboot - resolve OTAUpdatePendingTrouble"),(t=this.updatePendingTrouble)==null||t.resolve()}async init(){this.logger.debug(`initializing ota ${this.id}`)}async load(){this.logger.debug(`loading ota ${this.id}`);try{const t=await Yv();t&&t.forEach(e=>{const s=$o(e);s&&this.data.addModel(s)})}catch(t){this.logger.error(`loading ota ${this.id} - error:`,t)}}async handleAllArtifacts(t){this.logger.debug("handleAllArtifacts:",t),await this.data.clear();try{t.forEach(e=>{const s=$o(e);s&&this.data.addModel(s)})}catch(e){this.logger.error(`handleAllArtifacts ${this.id} - error:`,e)}}handleChangedArtifacts(t){this.logger.debug("handleChangedArtifacts:",t);try{t.forEach(e=>{const s=$o(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};ho([Ht({modelType:Lt.type})],Ft.prototype,"troubleContainer",2);ho([B({topic:"/kos/ota/artifacts/all",websocket:!0})],Ft.prototype,"handleAllArtifacts",1);ho([B({topic:"/kos/ota/artifacts/changed",websocket:!0})],Ft.prototype,"handleChangedArtifacts",1);Ft=ho([R(zu)],Ft);const Cr=new Se({class:Ft,type:zu});function Xv(t){let e;const s=async(...r)=>{e&&e.abort(),e=new AbortController;const o=e;try{return await t(...r,o.signal)}finally{e===o&&(e=void 0)}};return s.cancel=()=>{e&&(e.abort(),e=void 0)},s.getController=()=>e,s.isActive=()=>!!e,s}const Co=m.createLogger({name:"software-info-service",group:"Services"}),oi=async t=>{Co.debug("sending GET for software-info");const[e,s]=await tu.get("/api/kos/manifest/info",void 0,{signal:t});if(!s)throw t!=null&&t.aborted?(Co.debug("Request was aborted"),new ye("Request was aborted")):(Co.error("Failed to fetch software-info",e),new ye("Failed to fetch software-info"));return s},Jv=Xv(oi),ew=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:oi,getSoftwareInfosWithCancel:Jv},Symbol.toStringTag,{value:"Module"}));var tw=Object.getOwnPropertyDescriptor,sw=(t,e,s,r)=>{for(var o=r>1?void 0:r?tw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const is="software-info-model";let zo=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodes");this.id=t,this.logger=s.logger,this.nodes=[]}async init(){this.logger.debug(`initializing software-info ${this.id}`)}groupBy(t,e){return t.reduce((s,r)=>(s[r[e]]=[...s[r[e]]||[],r],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const t=await oi(),e=(t==null?void 0:t.nodes)||{};X(()=>{const r=Object.keys(e).map(o=>e[o][0]).map(o=>({nodeName:o.nodeType,kosVersion:o.kosVersion,group:this.groupBy(o.artifacts,"group")}));this.nodes=r})}catch(t){t instanceof ye&&this.logger.error("Failed to fetch software-info",t)}}};zo=sw([R(is)],zo);const Dr={registration:{[is]:{class:zo,singleton:!1}},type:is,predicate:_e(is),factory:ae.Factory.create(is)},{URL:Vu}=ce(),{getOne:rw}=oe.build({basePath:`${Vu}/api/kos/state`}),ow=m.createLogger({name:"state-bean-service",group:"Services"}),Gu=async({path:t})=>(ow.debug("sending GET for state-bean"),await rw({urlOverride:`${Vu}/api/kos/state/${t}`})),nw=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:Gu},Symbol.toStringTag,{value:"Module"}));var iw=Object.defineProperty,aw=Object.getOwnPropertyDescriptor,Yu=(t,e,s,r)=>{for(var o=r>1?void 0:r?aw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&iw(e,s,o),o};const as="state-bean-model",cw=dt("path");let xr=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"props");l(this,"logger");this.id=t,this.logger=s.logger,this.props=Pn.map(new Map),ko(e,this)}updateModel(t){ko(t,this)}handleConfigBeanUpdated(t){Object.entries(t).forEach(([e,s])=>{let r=s;typeof r=="string"&&Fn(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&Jr(r)&&(r=Number(r)),this.props.set(e,r)})}async init(){this.logger.debug(`initializing state-bean ${this.id}`)}updateProps(t){Object.entries(t).forEach(([e,s])=>{this.props.set(e,s)})}async load(){this.logger.debug(`loading state-bean ${this.id}`);const t=await Gu({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};Yu([B({topic:`/kos/state/${cw}`,websocket:!0})],xr.prototype,"handleConfigBeanUpdated",1);xr=Yu([R(as)],xr);const Ps={registration:{[as]:{class:xr,singleton:!1}},type:as,predicate:_e(as),factory:ae.Factory.create(as)};var lw=Object.defineProperty,uw=Object.getOwnPropertyDescriptor,Wu=(t,e,s,r)=>{for(var o=r>1?void 0:r?uw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&lw(e,s,o),o};const cs="state-prop-model",ca=dt("path");let Ar=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"attribute");l(this,"logger");l(this,"stateBean");this.id=t,this.logger=s.logger,this.path=e.path,this.attribute=e.attribute}get value(){return this.stateBean.props.get(this.attribute)}async init(){this.logger.debug(`initializing state-prop ${this.id}`)}async load(){this.logger.debug(`loading state-prop ${this.id}`)}toString(){var t;return((t=this.value)==null?void 0:t.toString())??""}};Wu([Ht({modelType:Ps.type,id:`state-bean-${ca}`,options:{path:ca}})],Ar.prototype,"stateBean",2);Ar=Wu([R(cs)],Ar);const ni={registration:{[cs]:{class:Ar,singleton:!1}},type:cs,predicate:_e(cs),factory:ae.Factory.create(cs)},{URL:dw}=ce(),{getAll:hw}=oe.build({basePath:`${dw}/api/state-prop`}),fw=m.createLogger({name:"state-prop-service",group:"Services"}),pw=async()=>(fw.debug("sending GET for state-prop"),await hw({})),gw=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:pw},Symbol.toStringTag,{value:"Module"})),{URL:ii}=ce(),{getOne:Qu}=oe.build({basePath:`${ii}/api/translation`}),Ss=m.createLogger({name:"translation-service",group:"Services"}),mw=()=>{const t=window.location.origin,e=be();return(e==null?void 0:e.host)||t},Zu=async(t,e)=>{Ss.debug(`Loading translations from: ${t}`);const s=e??mw();try{const r=await fetch(`${s}${t}`);return r.status!==200?(Ss.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw Ss.error("Error fetching translations",r),r}},yw=async()=>{Ss.debug("Getting system localization descriptor");const t=await Qu({urlOverride:`${ii}/api/system/kos/localization`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get localization descriptor ${t==null?void 0:t.status}`);return t.data},Xu=t=>async()=>{Ss.debug(`Getting KOS localization descriptor for context: ${t}`);const e=await Qu({urlOverride:`${ii}/api/kos/localization/contexts`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get KOS localization descriptor ${e==null?void 0:e.status}`);return e.data[t]},Ju="langResolver";var bw=Object.getOwnPropertyDescriptor,vw=(t,e,s,r)=>{for(var o=r>1?void 0:r?bw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const ls="translation-model";function ww(t){const e=typeof t=="string",s=e?!1:!!(t!=null&&t.data)&&typeof(t==null?void 0:t.data)!="string",r=e?t:t==null?void 0:t.defaultValue,o=e||t==null?void 0:t.context,n=e?void 0:s?t==null?void 0:t.data:t;return{isBasicOptions:e,defaultValue:r,context:o,data:n}}function ed(t,e=""){return Object.keys(t).reduce((s,r)=>{const o=e?`${e}.${r}`:r;if(typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])){const n=ed(t[r],o);return{...s,...n}}else return{...s,[o]:t[r]}},{})}function td(t,e){const s={...t};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(typeof e[r]=="object"&&e[r]!==null&&typeof t[r]=="object"&&t[r]!==null?s[r]=td(t[r],e[r]):s[r]=e[r]);return s}const Vo=(t,e)=>{const s=/__(.*?)__/g,r=t.replace(s,(o,n)=>Object.prototype.hasOwnProperty.call(e||{},n.trim())?e==null?void 0:e[n.trim()]:o);return r===t?r:s.test(r)?Vo(r,e):r},ar=(t,e,s)=>{const r=/{{(.*?)}}/g,n=Vo(t,e).replace(r,(a,c)=>{const u=c.trim();if(Object.prototype.hasOwnProperty.call(s||{},u))return s==null?void 0:s[u];if(u.includes(".")){const d=u.split(".");let h=s;for(const f of d)if(h&&typeof h=="object"&&Object.prototype.hasOwnProperty.call(h,f))h=h[f];else return a;return h}return a});return Vo(n,e)},la=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let Go=class{constructor(t,e,s){l(this,"id");l(this,"namespace");l(this,"descriptor");l(this,"defaultLocale");l(this,"currentLocale");l(this,"bundleResolver");l(this,"data");l(this,"logger");l(this,"resolver");l(this,"disposer");l(this,"context");l(this,"rootUrl");this.id=t,this.defaultLocale=e.defaultLocale||"en",this.currentLocale=e.currentLocale||"en",this.namespace=e.namespace,this.descriptor=e.descriptor,this.rootUrl=e.rootUrl,this.data={},this.resolver=e.resolver||s.kosContext.get(Ju),this.bundleResolver=e.bundleResolver,this.logger=s.logger,this.context=s.kosContext.parentModel}getTranslationLocales(t){const e=this.descriptor[t];if(!t||!e)return[this.defaultLocale];if(!this.defaultLocale&&!e.fallbacks)return[t];let s=e.fallbacks||[this.defaultLocale];return s.includes(t)||(s=[t,...s]),s}async loadTranslations(){const t=this.getTranslationLocales(this.currentLocale).reverse(),e=t.map(r=>{if(this.bundleResolver){const o=G.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return Zu(o,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(e);X(()=>{const r=s.reduce((o,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${t[i]}`,n.value),n.value&&(o=td(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),o),{});this.data=ed(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=la(this.namespace,t);if(e!==this.namespace){const r=this.context.getModel(e);return r?r.exists(s):!1}return!!this.data[s]}resolveKey(t,e){if(!t)return this.logger.debug("key is empty"),"";const{defaultValue:s,context:r,data:o}=ww(e),{namespace:n,key:i}=la(this.namespace,t),a=`${i}_${r}`;if(n!==this.namespace){const c=this.context.getModel(n);return c?c.resolveKey(i,e):s??i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(u=>ar(u,this.data,o)):ar(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[i];return Array.isArray(c)?c.map(u=>ar(u,this.data,o)):ar(this.data[i],this.data,o)}return s??i}unload(){this.logger.debug(`unloading translation ${this.id}`),this.disposer&&this.disposer()}async load(){this.logger.debug(`loading translation ${this.id}`),await this.loadTranslations()}async ready(){this.logger.debug(`ready translation ${this.id}`),this.disposer=M.reaction(()=>this.currentLocale,(t,e)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${e} to ${t}`),this.loadTranslations()})}};Go=vw([Wr(),R(ls)],Go);const Rr={registration:{[ls]:{class:Go,singleton:!1}},type:ls,predicate:_e(ls),factory:ae.Factory.create(ls)};var Ew=Object.defineProperty,Mw=Object.getOwnPropertyDescriptor,sd=(t,e,s,r)=>{for(var o=r>1?void 0:r?Mw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ew(e,s,o),o};const us="translation-container-model",Tw=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function _w(t,e){const s=this.descriptor.namespaces[t];if(!s)throw new Error("namespace "+t+" not found in descriptor");const r=s.basePath,o=s.locales[e].file;return Tw([r,o])}let Pr=class{constructor(t,e,s){l(this,"id");l(this,"lang");l(this,"rootUrl");l(this,"descriptor");l(this,"_defaultNamespace");l(this,"resolver");l(this,"logger");l(this,"descriptorUrl");l(this,"namespaces",[]);l(this,"_models");this.id=t,this.lang=e.lang||"en",this.descriptor=e.descriptor,this._defaultNamespace=e.defaultNamespace,this.descriptorUrl=e.descriptorUrl,this.rootUrl=e.rootUrl,this.resolver=e.resolver||_w.bind(this),s.kosContext.set(Ju,this.resolver),this.logger=s.logger,this._models=new xe({parentId:t})}set currentLocale(t){this.lang=t,this.models.data.forEach(e=>{e.currentLocale=t})}get defaultNamespace(){return this._defaultNamespace?this.getModel("translation-"+this._defaultNamespace):void 0}getModel(t){return this.logger.debug("getting model "+t),this._models.getModel("translation-"+t)}get models(){return this._models}get data(){return this._models.data}async reload(){for(const t of this.namespaces){const e=this.resolveNamespace(t);await fe(e)}}resolveNamespace(t){var s;if((s=this.descriptor.namespaces)==null?void 0:s[t]){const r=Object.keys(this.descriptor.namespaces[t].locales)[0],o=this.descriptor.namespaces[t].locales[r].defaultLocale,n=Rr.factory("translation-"+t)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:o,descriptor:this.descriptor.namespaces[t].locales,resolver:this.resolver});return this.addModel(n),this.namespaces.includes(t)||X(()=>{this.namespaces.push(t)}),n}else{this.logger.warn("namespace "+t+" not found in descriptor");const r=Rr.factory("translation-"+t)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(r),r}}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug("initializing translation-container container "+this.id)}async load(){this.logger.debug("loading translation-container container "+this.id)}};sd([De],Pr.prototype,"_models",2);Pr=sd([R(us)],Pr);const Ue={registration:{[us]:{class:Pr,singleton:!0}},type:us,predicate:_e(us),factory:ae.Singleton.create(us)},Sw={set(t,e){const s=G.getContext(Ue.type);s&&s.set(t,e)},get(t){const e=G.getContext(Ue.type);return e==null?void 0:e.get(t)}},rd={async init(t){const e=Ue.factory(t);return await fe(e),{translations:e}}};function Ow(t){return(t==null?void 0:t.troubles)!==void 0&&(t==null?void 0:t.troubles)instanceof Array&&(t==null?void 0:t.troublesByType)!==void 0&&typeof(t==null?void 0:t.troublesByType)=="object"}const od="kos-ws-event",ai=Kt(od);var Iw=Object.defineProperty,$w=Object.getOwnPropertyDescriptor,ci=(t,e,s,r)=>{for(var o=r>1?void 0:r?$w(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Iw(e,s,o),o};const Cw=({headers:t,body:e})=>Object.entries(t).map(([r,o])=>`${r}:${o}`).join("\\n")+"\\n\\n"+e;exports.WsEventModel=class{constructor(e){l(this,"id");l(this,"events");l(this,"_topicMap");this.id=e,this.events=M.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(e,s){this.processEvent(s,!0)}handleReceiveEvent(e,s){this.processEvent(s)}processEvent(e,s=!1){m.debug("kos event received");const{body:r,headers:o}=e.body,n=o["request-id"]||o["response-id"],i=o["request-id"]||o["response-id"]||o.topic||o.type;if(i){let a=i;if(n)a=`${a}-${s?"send":"receive"}`;else{const u=this._topicMap.get(i)||0;a=`${a}-${u+1}`,this._topicMap.set(i,u+1)}const c={msgId:a,content:r,headers:o,timestamp:Date.now(),raw:Cw({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),m.debug(`logged ${this.events.size} events`)}}};ci([B({topic:[Us.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);ci([B({topic:[Us.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=ci([R(ai.type)],exports.WsEventModel);const ua=be(),Dw=ua.debug==="true"||ua.debug===!0,xw="/api/system/canvas",nd=async(t,e)=>{const s=e||xw,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:Dw?"false":"true"},body:t})},Aw=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:nd},Symbol.toStringTag,{value:"Module"}));function da(t,e,s){{const r=t.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var Rw=Object.defineProperty,Pw=Object.getOwnPropertyDescriptor,id=(t,e,s,r)=>{for(var o=r>1?void 0:r?Pw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Rw(e,s,o),o};const ad="canvas-renderer-model";function Do(t){return typeof t.onDone=="function"}let kr=class{constructor(t,e,s){l(this,"id");l(this,"router");l(this,"logger");l(this,"_renderer",null);l(this,"_clearOnComplete");l(this,"isStreaming",!1);l(this,"renderLoopId",null);l(this,"sendIntervalId",null);l(this,"timeoutId",null);l(this,"apiPath");l(this,"endpointName");l(this,"width",50);l(this,"height",30);l(this,"fps",10);l(this,"durationMs",null);l(this,"_onFrame",null);this.id=t,this.logger=s.logger,this.width=e.width??50,this.height=e.height??30,this.fps=e.fps??10,this.durationMs=e.durationMs??null,this.apiPath=e.apiPath??"/api/system/canvas",this.endpointName=e.endpoint}set onFrame(t){this._onFrame=t}set renderer(t){var e,s;this._renderer&&(this.stopStreaming(),(s=(e=this._renderer).dispose)==null||s.call(e)),this._renderer=t,this.isStreaming&&this.startStreaming()}setClearOnComplete(t){this._clearOnComplete=t}sendDataFrame(t,e){nd(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const t=this.isOneShotDone();this.stopStreaming(!t)});return}}handleFrame(t){var s;const e=da(t);this.sendDataFrame(e,this.apiPath),(s=this._onFrame)==null||s.call(this,e)}stopStreaming(t=!0){var e,s;this.logger.debug(`stopStreaming called with clearCanvas=${t}`),this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(s=(e=this._renderer)==null?void 0:e.pause)==null||s.call(e),t&&(this.logger.debug("Clearing canvas..."),this.clearCanvas())}clearCanvas(){var s;const t=this.width>0?this.width:50,e=this.height>0?this.height:30;if(t>0&&e>0){const r=t*e*4,o=new Uint8ClampedArray(r);for(let i=3;i<r;i+=4)o[i]=255;const n=da(o);this.logger.debug(`Sending clear frame: ${t}x${e}, apiPath: ${this.apiPath}`),this.sendDataFrame(n,this.apiPath),(s=this._onFrame)==null||s.call(this,n)}}isOneShotDone(){var t,e;return Do(this._renderer)&&((e=(t=this._renderer).isOneShot)==null?void 0:e.call(t))===!0&&this._renderer.isOneShotDone}startStreaming(){var t,e,s,r;{if(!this._renderer)return;if(!this.apiPath){this.logger.error(`No endpoint configured for canvas renderer ${this.id}`);return}this.isStreaming=!0,this._renderer.reset(),(e=(t=this._renderer).play)==null||e.call(t);const o=Do(this._renderer);Do(this._renderer)&&this._renderer.onDone(()=>{var c,u,d;this.logger.debug(`Renderer completed for ${this.id}`),q("/canvas/renderer/completed",{endpoint:this.endpointName,rendererId:this.id,rendererType:(c=this._renderer)==null?void 0:c.constructor.name,timestamp:Date.now()});let a=!0;this._clearOnComplete!==void 0?a=this._clearOnComplete:a=!(((d=(u=this._renderer)==null?void 0:u.isOneShot)==null?void 0:d.call(u))??!1),this.stopStreaming(a)}),this._renderer.renderFrame(this.width,this.height);const n=(r=(s=this._renderer).readPixels)==null?void 0:r.call(s,this.width,this.height);if(n&&this._onFrame&&this.handleFrame(n),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming(!1)});return}const i=()=>{var a;(a=this._renderer)==null||a.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var c,u;const a=(u=(c=this._renderer)==null?void 0:c.readPixels)==null?void 0:u.call(c,this.width,this.height);a&&this._onFrame&&(this.handleFrame(a),this.checkStreaming())},1e3/this.fps),!o&&this.durationMs!=null&&(this.timeoutId=setTimeout(()=>{this.stopStreaming()},this.durationMs))}}async init(){this.logger.debug(`initializing canvas-renderer ${this.id}`)}async load(){this.logger.debug(`loading canvas-renderer ${this.id}`),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/stop`,async(t,e)=>{this.logger.debug(`HTTP stop endpoint called for ${this.endpointName}`),this.stopStreaming(),e.send({status:"OK"})}),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/start`,async(t,e)=>{this.startStreaming(),e.send({status:"OK"})})}};id([Ht({modelType:zn.type})],kr.prototype,"router",2);kr=id([R(ad)],kr);const li=new ve({class:kr,type:ad});class cd{constructor({src:e}){l(this,"video");l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);l(this,"doneCallback",null);this.video=document.createElement("video"),this.video.src=e,this.video.crossOrigin="anonymous",this.video.muted=!0,this.video.loop=!1,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");this.ctx=s,this.handleEnded=this.handleEnded.bind(this),this.video.addEventListener("ended",this.handleEnded)}handleEnded(){this.doneCallback&&this.doneCallback()}reset(){this.video.pause(),this.video.currentTime=0,this.lastUpdate=performance.now()}play(){this.video.play().catch(console.warn)}pause(){this.video.pause()}renderFrame(e,s){this.canvas.width=e,this.canvas.height=s,this.video.readyState>=2&&this.ctx.drawImage(this.video,0,0,e,s)}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}onDone(e){this.doneCallback=e}dispose(){this.video.pause(),this.video.removeAttribute("src"),this.video.load(),this.video.remove(),this.video.removeEventListener("ended",this.handleEnded),this.doneCallback=null}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}}class kw{constructor(){l(this,"canvas");l(this,"gl");l(this,"lastWidth",0);l(this,"lastHeight",0);l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl");if(!e)throw new Error("WebGL not supported");this.gl=e}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e=this.lastWidth,s=this.lastHeight){const r=new Uint8Array(e*s*4);this.gl.readPixels(0,0,e,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r);const o=new Uint8ClampedArray(r.length);for(let n=0;n<s;n++){const i=n*e*4,a=(s-1-n)*e*4;o.set(r.subarray(i,i+e*4),a)}return o}}class Lw extends kw{constructor({speedPx:s=1}={}){super();l(this,"program");l(this,"posBuffer");l(this,"aPosition");l(this,"uMinHue");l(this,"uMaxHue");l(this,"uHueOffset");l(this,"uGridHeight");l(this,"minHue",0);l(this,"maxHue",80);l(this,"hueOffset",0);l(this,"speedPx",1);this.speedPx=s;const r=this.gl,o=`
111
111
  attribute vec2 a_position;
112
112
  void main() {
113
113
  gl_Position = vec4(a_position, 0, 1);
@@ -141,8 +141,8 @@ ${u}topics:${e}
141
141
  vec3 rgb = hslToRgb(hue, 1.0, 0.5);
142
142
  gl_FragColor = vec4(rgb, 1.0);
143
143
  }
144
- `,i=this.compileShader(r.VERTEX_SHADER,o),a=this.compileShader(r.FRAGMENT_SHADER,n);this.program=this.createProgram(i,a),this.posBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.posBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),r.STATIC_DRAW),this.aPosition=r.getAttribLocation(this.program,"a_position"),this.uMinHue=r.getUniformLocation(this.program,"minHue"),this.uMaxHue=r.getUniformLocation(this.program,"maxHue"),this.uHueOffset=r.getUniformLocation(this.program,"hueOffset"),this.uGridHeight=r.getUniformLocation(this.program,"gridHeight")}reset(){this.hueOffset=0,this.lastUpdate=performance.now()}renderFrame(s,r){const o=this.gl;if(this.canvas.width=s,this.canvas.height=r,this.shouldStep(50)){const n=this.speedPx/r;this.hueOffset=(this.hueOffset+n)%1}o.viewport(0,0,s,r),o.clear(o.COLOR_BUFFER_BIT),o.useProgram(this.program),o.enableVertexAttribArray(this.aPosition),o.bindBuffer(o.ARRAY_BUFFER,this.posBuffer),o.vertexAttribPointer(this.aPosition,2,o.FLOAT,!1,0,0),o.uniform1f(this.uMinHue,this.minHue/360),o.uniform1f(this.uMaxHue,this.maxHue/360),o.uniform1f(this.uHueOffset,this.hueOffset),o.uniform1f(this.uGridHeight,r),o.drawArrays(o.TRIANGLES,0,6)}compileShader(s,r){const o=this.gl.createShader(s);if(this.gl.shaderSource(o,r),this.gl.compileShader(o),!this.gl.getShaderParameter(o,this.gl.COMPILE_STATUS))throw new Error(this.gl.getShaderInfoLog(o)||"Shader compile failed");return o}createProgram(s,r){const o=this.gl.createProgram();if(this.gl.attachShader(o,s),this.gl.attachShader(o,r),this.gl.linkProgram(o),!this.gl.getProgramParameter(o,this.gl.LINK_STATUS))throw new Error("Program linking failed");return o}}class mt{constructor(){l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("2d");if(!e)throw new Error("2D canvas not supported");this.ctx=e}dispose(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove()}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}}function ui(t){class e extends t{constructor(){super(...arguments);l(this,"doneCallback",null);l(this,"oneShotDone",!1)}isOneShot(){return!0}onDone(o){this.doneCallback=o}signalDoneIfNeeded(){var o;this.oneShotDone||((o=this.doneCallback)==null||o.call(this),this.oneShotDone=!0)}resetOneShot(){this.doneCallback=null,this.oneShotDone=!1}get isOneShotDone(){return this.oneShotDone}}return e}const Fw=ui(mt);class Nw extends Fw{constructor({colors:s=["red","yellow","green"],direction:r="horizontal",speed:o=2,loop:n=!0}={}){super();l(this,"offset",0);l(this,"speed");l(this,"colors");l(this,"direction");l(this,"loop");this.colors=s,this.direction=r,this.speed=o,this.loop=n}reset(){this.offset=0,this.lastUpdate=performance.now(),this.loop||this.resetOneShot()}renderFrame(s,r){if(!this.loop&&this.isOneShotDone)return;this.loop&&this.shouldStep(50)&&(this.offset+=this.speed);const o=this.loop?-this.offset:0,n=this.loop?s*2-this.offset:s,i=this.ctx.createLinearGradient(o,0,n,0),a=1/(this.colors.length-1);this.colors.forEach((c,u)=>{i.addColorStop(u*a,c)}),this.ctx.fillStyle=i,this.ctx.fillRect(0,0,s,r),!this.loop&&!this.isOneShotDone&&this.signalDoneIfNeeded()}}const Uw=ui(mt);class ld extends Uw{constructor({src:s}){super();l(this,"img");l(this,"loaded",!1);this.img=new Image,this.img.src=s,this.img.crossOrigin="anonymous",this.img.onload=()=>{this.loaded=!0}}reset(){this.resetOneShot()}renderFrame(s,r){!this.loaded||this.isOneShotDone||(this.canvas.width=s,this.canvas.height=r,this.ctx.drawImage(this.img,0,0,s,r),this.signalDoneIfNeeded())}}class jw extends cd{constructor(s){super(s);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"startTime");l(this,"endTime");l(this,"completionCallback",null);this.loopConfig=s.loop??!1,this.startTime=s.startTime??0,this.endTime=s.endTime??null,this.video.removeEventListener("ended",this.handleEnded),this.video.addEventListener("ended",this.handleVideoEnd.bind(this)),this.startTime>0&&(this.video.currentTime=this.startTime),this.endTime!==null&&this.video.addEventListener("timeupdate",this.handleTimeUpdate.bind(this))}handleTimeUpdate(){this.endTime!==null&&this.video.currentTime>=this.endTime&&this.handleVideoEnd()}handleVideoEnd(){this.loopConfig===!0?(this.video.currentTime=this.startTime,this.video.play().catch(console.warn)):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.video.currentTime=this.startTime,this.video.play().catch(console.warn)):(this.video.pause(),this.completionCallback&&this.completionCallback())}reset(){super.reset(),this.currentLoopCount=0,this.video.currentTime=this.startTime}onDone(s){this.completionCallback=s}isOneShot(){return this.loopConfig===!1||this.loopConfig===1}dispose(){this.video.removeEventListener("ended",this.handleVideoEnd),this.video.removeEventListener("timeupdate",this.handleTimeUpdate),this.completionCallback=null,super.dispose()}}function Bw(t){const e=t.replace("#","");if(!/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(e))throw new Error(`Invalid hex color: ${t}`);let s,r,o;return e.length===3?(s=parseInt(e[0]+e[0],16),r=parseInt(e[1]+e[1],16),o=parseInt(e[2]+e[2],16)):(s=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),o=parseInt(e.substring(4,6),16)),{r:s,g:r,b:o}}function ud(t){return typeof t=="string"?Bw(t):t}function Lr(t){const e=ud(t);return`rgb(${e.r},${e.g},${e.b})`}class Hw extends mt{constructor(s={}){super();l(this,"columns",[]);l(this,"fallChance");l(this,"speed");l(this,"baseColor");l(this,"trailColors");this.speed=s.speed??1,this.fallChance=s.fallChance??.7,s.baseColor?this.baseColor=ud(s.baseColor):this.baseColor={r:0,g:255,b:255},this.trailColors=this.calculateTrailColors()}calculateTrailColors(){const r=[];for(let o=0;o<=5;o++){const n=1-o/5*.6;r.push({r:Math.floor(this.baseColor.r*n),g:Math.floor(this.baseColor.g*n),b:Math.floor(this.baseColor.b*n)})}return r}reset(){this.columns=[],this.lastUpdate=performance.now()}renderFrame(s,r){this.columns.length!==s&&(this.columns=Array(s).fill(0).map(()=>Math.floor(Math.random()*r))),this.shouldStep(50)&&(this.columns=this.columns.map(i=>i>r+5?0:i+(Math.random()<this.fallChance?this.speed:0)));const o=this.ctx.createImageData(s,r),n=o.data;n.fill(0);for(let i=0;i<r;i++)for(let a=0;a<s;a++){const c=this.columns[a];let u=0,d=0,h=0;if(i===c)u=this.baseColor.r,d=this.baseColor.g,h=this.baseColor.b;else if(i<c&&i>c-this.trailColors.length){const p=c-i;if(p<this.trailColors.length){const y=this.trailColors[p];u=y.r,d=y.g,h=y.b}}const f=(i*s+a)*4;n[f]=u,n[f+1]=d,n[f+2]=h,n[f+3]=255}this.ctx.putImageData(o,0,0)}}class Kw{constructor(e,s){l(this,"baseRenderer");l(this,"overlayIcons",new Map);l(this,"overlayConfigs");l(this,"loadedIcons",new Set);l(this,"canvas");l(this,"ctx");l(this,"persistOverlaysOnComplete");l(this,"baseRendererCompleted",!1);l(this,"completionCallback",null);l(this,"hasSignaledCompletion",!1);this.baseRenderer=s(e.baseRenderer.type,e.baseRenderer.data),this.overlayConfigs=e.overlays,this.persistOverlaysOnComplete=e.persistOverlaysOnComplete!==!1,this.canvas=document.createElement("canvas");const r=this.canvas.getContext("2d");if(!r)throw new Error("2D canvas not supported");this.ctx=r,this.loadOverlayImages(),"onDone"in this.baseRenderer&&typeof this.baseRenderer.onDone=="function"&&this.baseRenderer.onDone(()=>{this.baseRendererCompleted=!0,!this.persistOverlaysOnComplete&&this.completionCallback&&this.completionCallback()})}async loadOverlayImages(){for(const e of this.overlayConfigs){const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{this.loadedIcons.add(e.src)},s.onerror=r=>{console.error(`Failed to load overlay image: ${e.src}`,r)},s.src=e.src,this.overlayIcons.set(e.src,s)}}calculateOverlayPosition(e,s,r){let o,n;if(typeof e.position=="string")switch(e.position){case"top-left":o=0,n=0;break;case"top-center":o=(s-e.size)/2,n=0;break;case"top-right":o=s-e.size,n=0;break;case"center-left":o=0,n=(r-e.size)/2;break;case"center":o=(s-e.size)/2,n=(r-e.size)/2;break;case"center-right":o=s-e.size,n=(r-e.size)/2;break;case"bottom-left":o=0,n=r-e.size;break;case"bottom-center":o=(s-e.size)/2,n=r-e.size;break;case"bottom-right":o=s-e.size,n=r-e.size;break;default:o=0,n=0}else o=e.position.x,n=e.position.y;return e.offset&&(o+=e.offset.x||0,n+=e.offset.y||0),{x:o,y:n}}reset(){this.baseRenderer.reset(),this.baseRendererCompleted=!1,this.hasSignaledCompletion=!1}renderFrame(e,s){if(this.canvas.width=e,this.canvas.height=s,this.ctx.clearRect(0,0,e,s),this.baseRendererCompleted&&this.persistOverlaysOnComplete)this.renderOverlays(e,s);else{this.baseRenderer.renderFrame(e,s);const r=this.baseRenderer.readPixels(e,s);if(r&&r.length>0){const o=new ImageData(r,e,s);this.ctx.putImageData(o,0,0)}this.renderOverlays(e,s)}}renderOverlays(e,s){for(const r of this.overlayConfigs){if(!r.persistent&&r.persistent!==void 0)continue;const o=this.overlayIcons.get(r.src);if(!o||!this.loadedIcons.has(r.src))continue;const n=this.calculateOverlayPosition(r,e,s);this.ctx.save(),r.opacity!==void 0&&(this.ctx.globalAlpha=Math.max(0,Math.min(1,r.opacity))),this.ctx.drawImage(o,n.x,n.y,r.size,r.size),this.ctx.restore()}}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}play(){this.baseRenderer.play&&this.baseRenderer.play()}pause(){this.baseRenderer.pause&&this.baseRenderer.pause()}dispose(){this.overlayIcons.clear(),this.loadedIcons.clear(),this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove(),this.baseRenderer.dispose&&this.baseRenderer.dispose()}onDone(e){this.completionCallback=e,this.hasSignaledCompletion&&e()}isOneShot(){return this.persistOverlaysOnComplete?!1:"isOneShot"in this.baseRenderer&&typeof this.baseRenderer.isOneShot=="function"?this.baseRenderer.isOneShot():!1}}class dd extends mt{constructor(s){super();l(this,"img");l(this,"loaded",!1);l(this,"scrollConfig");l(this,"loopConfig");l(this,"duration");l(this,"pauseDuration");l(this,"colorOverride");l(this,"originalSvgData",null);l(this,"position",0);l(this,"startTime",0);l(this,"lastFrameTime",0);l(this,"currentLoopCount",0);l(this,"completionCallback",null);l(this,"isPlaying",!1);l(this,"completed",!1);l(this,"isPaused",!1);l(this,"pauseStartTime",0);this.img=new Image,this.img.crossOrigin="anonymous",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,this.colorOverride=s.colorOverride,this.colorOverride&&s.src.toLowerCase().includes(".svg")?this.loadAndProcessSvg(s.src):this.img.src=s.src,this.img.onload=()=>{this.loaded=!0},this.img.onerror=r=>{console.error("Failed to load image:",r)}}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(!this.loaded||this.completed)return;if(this.isPaused){this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.ctx.drawImage(this.img,0,0,s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const c=performance.now(),u=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const d=n*u;switch(o){case"left":this.position+=d;break;case"right":this.position+=d;break;case"up":this.position+=d;break;case"down":this.position+=d;break}}this.drawScrollingImage(s,r,o,i),this.checkScrollCompletion(s,r,o,i)}drawScrollingImage(s,r,o,n){var h,f,p,y,w,E,_,L,U;const i=this.img.width/this.img.height;let a,c;((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(f=this.scrollConfig)!=null&&f.height?(c=this.scrollConfig.height,a=c*i):(p=this.scrollConfig)!=null&&p.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,c=((w=this.scrollConfig)==null?void 0:w.height)||r);let u,d;switch(o==="left"||o==="right"?(u=0,((E=this.scrollConfig)==null?void 0:E.offsetY)==="center"||((_=this.scrollConfig)==null?void 0:_.offsetY)===void 0?d=(r-c)/2:d=this.scrollConfig.offsetY):(((L=this.scrollConfig)==null?void 0:L.offsetX)==="center"||((U=this.scrollConfig)==null?void 0:U.offsetX)===void 0?u=(s-a)/2:u=this.scrollConfig.offsetX,d=0),o){case"left":{const I=s-this.position;if(I<s&&I>-a&&this.ctx.drawImage(this.img,I,d,a,c),this.loopConfig&&this.pauseDuration===0&&this.position>n){const S=I+a+n;S<s&&this.ctx.drawImage(this.img,S,d,a,c)}break}case"right":{const I=-a+this.position;if(I>-a&&I<s&&this.ctx.drawImage(this.img,I,d,a,c),this.loopConfig&&this.pauseDuration===0&&I-n-a>-a){const S=I-a-n;S<s&&this.ctx.drawImage(this.img,S,d,a,c)}break}case"up":{const I=r-this.position;if(I>-c&&I<r&&this.ctx.drawImage(this.img,u,I,a,c),this.loopConfig&&this.pauseDuration===0&&I+c+n<r){const S=I+c+n;S>-c&&this.ctx.drawImage(this.img,u,S,a,c)}break}case"down":{const I=-c+this.position;if(I>-c&&I<r&&this.ctx.drawImage(this.img,u,I,a,c),this.loopConfig&&this.pauseDuration===0&&I-n-c>-c){const S=I-c-n;S<r&&this.ctx.drawImage(this.img,u,S,a,c)}break}}}checkScrollCompletion(s,r,o,n){var h,f,p,y,w;if(!this.isPlaying)return;const i=this.img.width/this.img.height;let a,c;switch(((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(f=this.scrollConfig)!=null&&f.height?(c=this.scrollConfig.height,a=c*i):(p=this.scrollConfig)!=null&&p.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,c=((w=this.scrollConfig)==null?void 0:w.height)||r),o){case"left":case"right":this.loopConfig;break;case"up":case"down":this.loopConfig;break}let u=!1;const d=1;switch(o){case"left":u=s-this.position<-a-d;break;case"right":u=-a+this.position>s+d;break;case"up":u=r-this.position<-c-d;break;case"down":u=-c+this.position>r+d;break}u&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}async loadAndProcessSvg(s){try{const o=await(await fetch(s)).text();this.originalSvgData=o;const n=this.applySvgColorOverride(o),i=`data:image/svg+xml;base64,${btoa(n)}`;this.img.src=i}catch(r){console.error("Failed to load and process SVG:",r),this.img.src=s}}applySvgColorOverride(s){if(!this.colorOverride)return s;const r=Lr(this.colorOverride);return s.replace(/fill\s*=\s*["'][^"']*["']/gi,`fill="${r}"`).replace(/fill\s*:\s*[^;"]*/gi,`fill:${r}`).replace(/stroke\s*=\s*["'][^"']*["']/gi,`stroke="${r}"`).replace(/stroke\s*:\s*[^;"]*/gi,`stroke:${r}`)}dispose(){this.img.removeAttribute("src"),this.completionCallback=null,this.originalSvgData=null}}class qw extends mt{constructor(s){super();l(this,"text");l(this,"lines");l(this,"fontSize");l(this,"fontFamily");l(this,"lineHeight");l(this,"textColor");l(this,"scrollConfig");l(this,"loopConfig");l(this,"duration");l(this,"pauseDuration");l(this,"position",0);l(this,"startTime",0);l(this,"lastFrameTime",0);l(this,"currentLoopCount",0);l(this,"completionCallback",null);l(this,"isPlaying",!1);l(this,"completed",!1);l(this,"isPaused",!1);l(this,"pauseStartTime",0);l(this,"textWidth",0);l(this,"textHeight",0);l(this,"lineWidths",[]);l(this,"textMeasured",!1);this.text=s.text,this.lines=s.text.split(`
145
- `),this.fontSize=s.fontSize??8,this.lineHeight=s.lineHeight??this.fontSize+2,this.fontFamily=s.fontFamily??"monospace, 'Lucida Console', 'Courier New', Courier",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,s.color?this.textColor=Lr(s.color):this.textColor="rgb(255,255,255)"}measureText(){if(this.textMeasured)return;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.lineWidths=[];let s=0;for(const r of this.lines){const n=this.ctx.measureText(r).width;this.lineWidths.push(n),s=Math.max(s,n)}this.textWidth=s,this.textHeight=this.lines.length*this.lineHeight,this.textMeasured=!0}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0,this.textMeasured=!1,this.lineWidths=[]}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(this.canvas.width=s,this.canvas.height=r,this.measureText(),this.completed)return;if(this.isPaused){this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.drawStaticText(s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const c=performance.now(),u=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const d=n*u;switch(o){case"left":case"right":case"up":case"down":this.position+=d;break}}this.drawScrollingText(s,r,o,i),this.checkScrollCompletion(s,r,o)}drawStaticText(s,r){this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";const o=this.textHeight;let n=(r-o)/2;for(let i=0;i<this.lines.length;i++){const a=this.lines[i],c=this.lineWidths[i],u=(s-c)/2,d=n+i*this.lineHeight;this.ctx.fillText(a,u,d)}}drawScrollingText(s,r,o,n){var c,u,d,h;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";let i,a;o==="left"||o==="right"?(i=0,((c=this.scrollConfig)==null?void 0:c.offsetY)==="center"||((u=this.scrollConfig)==null?void 0:u.offsetY)===void 0?a=(r-this.textHeight)/2:a=this.scrollConfig.offsetY):(((d=this.scrollConfig)==null?void 0:d.offsetX)==="center"||((h=this.scrollConfig)==null?void 0:h.offsetX)===void 0?(i=s/2,this.ctx.textAlign="center"):(i=this.scrollConfig.offsetX,this.ctx.textAlign="left"),a=0),this.drawMultiLineScrollText(o,s,r,n,i,a)}drawMultiLineScrollText(s,r,o,n,i,a){switch(s){case"left":{const c=r-this.position;if(c<r&&c>-this.textWidth&&this.drawTextBlock(c,a,"left"),this.loopConfig&&this.pauseDuration===0&&this.position>n){const u=c+this.textWidth+n;u<r&&this.drawTextBlock(u,a,"left")}break}case"right":{const c=-this.textWidth+this.position;if(c>-this.textWidth&&c<r&&this.drawTextBlock(c,a,"left"),this.loopConfig&&this.pauseDuration===0&&c-n-this.textWidth>-this.textWidth){const u=c-this.textWidth-n;u<r&&this.drawTextBlock(u,a,"left")}break}case"up":{const c=o-this.position;if(c>-this.textHeight&&c<o&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c+this.textHeight+n<o){const u=c+this.textHeight+n;u>-this.textHeight&&this.drawTextBlock(i,u,"center")}break}case"down":{const c=-this.textHeight+this.position;if(c>-this.textHeight&&c<o&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c-n-this.textHeight>-this.textHeight){const u=c-this.textHeight-n;u<o&&this.drawTextBlock(i,u,"center")}break}}}drawTextBlock(s,r,o){for(let n=0;n<this.lines.length;n++){const i=this.lines[n],a=this.lineWidths[n];let c;o==="center"?c=s-a/2:c=s;const u=r+n*this.lineHeight;this.ctx.fillText(i,c,u)}}checkScrollCompletion(s,r,o){if(!this.isPlaying)return;let n=!1;const i=1;switch(o){case"left":n=s-this.position<-this.textWidth-i;break;case"right":n=-this.textWidth+this.position>s+i;break;case"up":n=r-this.position<-this.textHeight-i;break;case"down":n=-this.textHeight+this.position>r+i;break}n&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}dispose(){this.completionCallback=null}}class zw{constructor(e){l(this,"patterns");l(this,"currentPatternIndex",0);l(this,"currentRenderer",null);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"transitionDuration");l(this,"patternOverrides");l(this,"completionCallback",null);l(this,"patternStore");l(this,"canvas");l(this,"ctx");l(this,"width",0);l(this,"height",0);this.patterns=e.patterns,this.loopConfig=e.loop??!1,this.transitionDuration=e.transitionDuration??0,this.patternOverrides=e.patternOverrides??{},this.patternStore=e.patternStore??new Map,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");if(this.ctx=s,this.patterns.length===0)throw new Error("SequenceRenderer requires at least one pattern");this.loadCurrentPattern()}loadCurrentPattern(){var n,i,a,c;const e=this.patterns[this.currentPatternIndex],s=this.patternStore.get(e);if(!s){console.warn(`Pattern "${e}" not found in store, skipping`),this.moveToNextPattern();return}this.currentRenderer&&((i=(n=this.currentRenderer).dispose)==null||i.call(n));const r=this.patternOverrides[e]??{},o={...s.data,...r};try{this.currentRenderer=Fr({mode:s.type,data:o}),this.currentRenderer&&this.isDoneAware(this.currentRenderer)&&this.currentRenderer.onDone(()=>{this.handlePatternComplete()}),this.currentRenderer&&(this.currentRenderer.reset(),(c=(a=this.currentRenderer).play)==null||c.call(a),this.width>0&&this.height>0&&this.currentRenderer.renderFrame(this.width,this.height))}catch(u){console.error(`Failed to create renderer for pattern "${e}":`,u),this.moveToNextPattern()}}isDoneAware(e){return typeof(e==null?void 0:e.onDone)=="function"}handlePatternComplete(){this.transitionDuration>0?setTimeout(()=>{this.moveToNextPattern()},this.transitionDuration):this.moveToNextPattern()}moveToNextPattern(){this.currentPatternIndex++,this.currentPatternIndex>=this.patterns.length?this.loopConfig===!0?(this.currentPatternIndex=0,this.loadCurrentPattern()):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.currentPatternIndex=0,this.loadCurrentPattern()):this.completionCallback&&this.completionCallback():this.loadCurrentPattern()}reset(){this.currentPatternIndex=0,this.currentLoopCount=0,this.loadCurrentPattern()}play(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.play)==null||s.call(e)}pause(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.pause)==null||s.call(e)}renderFrame(e,s){this.width=e,this.height=s,this.canvas.width=e,this.canvas.height=s,this.currentRenderer&&this.currentRenderer.renderFrame(e,s)}readPixels(e,s){return this.currentRenderer?this.currentRenderer.readPixels(e,s):this.ctx.getImageData(0,0,e,s).data}onDone(e){this.completionCallback=e}isOneShot(){var e,s;return this.loopConfig===!1||this.loopConfig===1?this.patterns.length===1&&this.currentRenderer?((s=(e=this.currentRenderer).isOneShot)==null?void 0:s.call(e))??!1:!0:!1}dispose(){var e,s;this.currentRenderer&&((s=(e=this.currentRenderer).dispose)==null||s.call(e)),this.completionCallback=null}setPatternStore(e){this.patternStore=e,this.patterns.length>0&&this.loadCurrentPattern()}}const Vw=ui(mt);class Gw extends Vw{constructor(s={r:0,g:0,b:0}){super();l(this,"color");let r;s.color!==void 0?r=s.color:s.r!==void 0&&s.g!==void 0&&s.b!==void 0?r={r:s.r,g:s.g,b:s.b}:r={r:0,g:0,b:0},this.color=Lr(r)}setColor(s){this.color=Lr(s),this.resetOneShot()}reset(){this.resetOneShot()}renderFrame(s,r){this.isOneShotDone||(this.canvas.width=s,this.canvas.height=r,this.ctx.fillStyle=this.color,this.ctx.fillRect(0,0,s,r),this.signalDoneIfNeeded())}}class Yw extends mt{constructor({minHue:s=0,maxHue:r=360,speed:o=1}={}){super();l(this,"offset",0);l(this,"minHue");l(this,"maxHue");l(this,"speed");this.minHue=s,this.maxHue=r,this.speed=o}reset(){this.offset=0,this.lastUpdate=performance.now()}hslToRgb(s,r,o){let n,i,a;if(r===0)n=i=a=o;else{const c=(h,f,p)=>(p<0&&(p+=1),p>1&&(p-=1),p<.16666666666666666?h+(f-h)*6*p:p<.5?f:p<.6666666666666666?h+(f-h)*(.6666666666666666-p)*6:h),u=o<.5?o*(1+r):o+r-o*r,d=2*o-u;n=c(d,u,s+1/3),i=c(d,u,s),a=c(d,u,s-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(a*255)]}renderFrame(s,r){this.shouldStep(50)&&(this.offset=(this.offset+this.speed)%s);const o=this.ctx.createImageData(s,r),n=o.data;let i=0;for(let a=0;a<r;a++)for(let c=0;c<s;c++){const u=(c+this.offset)%s/s,d=this.minHue/360+u*((this.maxHue-this.minHue)/360),[h,f,p]=this.hslToRgb(d,1,.5);n[i++]=h,n[i++]=f,n[i++]=p,n[i++]=255}this.ctx.putImageData(o,0,0)}}const ha=new Map;js(ee,{register(t,e){ha.set(t,e)},execute(t,e){const s=ha.get(t);return s?new s(e):null}});$.canvas.registerRenderer("video",jw);$.canvas.registerRenderer("video-basic",cd);$[ee].register("image-static",ld);$[ee].register("image-scrolling",dd);const Ww=class{constructor(t){var e;return(e=t.scroll)!=null&&e.enabled?new dd(t):new ld(t)}};$[ee].register("image",Ww);$[ee].register("color",Gw);$[ee].register("matrix",Hw);$[ee].register("sweep",Yw);$[ee].register("gradient",Nw);$[ee].register("drop",Lw);$[ee].register("sequence",zw);$[ee].register("text",qw);const Qw=class{constructor(t){const e=(s,r)=>{const o=Fr({mode:s,data:r});if(!o)throw new Error(`Failed to create renderer of type: ${s}`);return o};return new Kw(t,e)}};$[ee].register("overlay",Qw);const Fr=({mode:t,data:e})=>{const s=$[ee].execute(t,e);if(s)return s;throw new Error(`Unknown mode: ${t}`)};var Zw=Object.defineProperty,Xw=Object.getOwnPropertyDescriptor,Qt=(t,e,s,r)=>{for(var o=r>1?void 0:r?Xw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Zw(e,s,o),o};const hd="canvas-dispatcher-model";function Jw(t){if(t=t.replace(/^#/,""),t.length===3&&(t=t.split("").map(s=>s+s).join("")),t.length!==6)return null;const e=parseInt(t,16);return{r:e>>16&255,g:e>>8&255,b:e&255}}let We=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_content",new Map);l(this,"_patterns",new Map);l(this,"_endpointRenderers");l(this,"pattern");l(this,"data");this.id=t,this.logger=s.logger,this._endpointRenderers=new xe}addNamedEndpoint(t,e){this._endpointRenderers.getModel(t)&&this.logger.warn(`Endpoint "${t}" already exists. Overwriting.`);const s=li.instance(t).options({apiPath:e.apiPath,width:e.width,height:e.height,fps:e.fps,durationMs:e.durationMs??null,endpoint:t}).build();return this._endpointRenderers.addModel(s),s}addContent(t,e){this._content.has(t)&&this.logger.warn(`Content "${t}" already exists. Overwriting.`),this._content.set(t,e)}addPattern(t,e){this._patterns.has(t)&&this.logger.warn(`Pattern "${t}" already exists. Overwriting.`),this._patterns.set(t,e)}async handlePatternsPost(t,e){var o,n;const s=t.body,r=Array.isArray(s)?s:[s];if(r.some(i=>!i.id||!i.type||!i.data)){(o=e.status)==null||o.call(e,400).send({error:"Invalid pattern data"});return}for(const i of r)this._patterns.has(i.id)&&this.logger.warn(`Pattern "${i.id}" already exists. Overwriting.`),this.addPattern(i.id,i);(n=e.status)==null||n.call(e,200).send({status:"OK"})}async handlePatternApplication(t,e){var u,d,h;const s=t.params.pattern,r=t.params.endpoint,o=this._endpointRenderers.getModel(r);if(!o){(u=e.status)==null||u.call(e,404).send({error:`Endpoint "${r}" not found`});return}if(!this._patterns.has(s)){(d=e.status)==null||d.call(e,404).send({error:`Pattern "${s}" not found`});return}const n=this._patterns.get(s),i=n.type,a=t.body||{};this.data={...n.data,...a};const c=i==="sequence"?{...this.data,patternStore:this._patterns}:this.data;o.renderer=Fr({mode:i,data:c}),o.setClearOnComplete(n.clearOnComplete),o.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleColorApplication(t,e){var u,d,h;const s=t.params.color,r=Jw(s);if(!r){(u=e.status)==null||u.call(e,400).send({error:"Invalid color format"});return}const o=t.params.endpoint,n=this._endpointRenderers.getModel(o);if(!n){(d=e.status)==null||d.call(e,404).send({error:`Endpoint "${o}" not found`});return}const{r:i,b:a,g:c}=r;n.renderer=Fr({mode:"color",data:{r:i,g:c,b:a}}),n.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleEndpointCreation(t,e){var r,o;const s=t.body;if(!s.apiPath||!s.id){(r=e.status)==null||r.call(e,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(s.id,s),(o=e.status)==null||o.call(e,200).send({status:"OK"})}async load(t){var s;const e=t==null?void 0:t.get(Nt.loader);e&&((s=e.patterns)==null||s.forEach(r=>{if(!r.id||!r.type||!r.data){this.logger.warn(`Invalid pattern data: ${JSON.stringify(r)}`);return}this.addPattern(r.id,r)}))}};Qt([De],We.prototype,"_endpointRenderers",2);Qt([Ks("/api/ui/canvas/patterns")],We.prototype,"handlePatternsPost",1);Qt([Ks("/api/ui/canvas/pattern/:endpoint/:pattern")],We.prototype,"handlePatternApplication",1);Qt([Ks("/api/ui/canvas/color/:endpoint/:color")],We.prototype,"handleColorApplication",1);Qt([Ks("/api/ui/canvas/endpoint")],We.prototype,"handleEndpointCreation",1);We=Qt([R(hd)],We);const Nt=new Se({class:We,type:hd}),{URL:di}=ce(),{getOne:fd}=oe.build({basePath:`${di}/api/device`}),Nr=m.createLogger({name:"device-service",group:"Services"}),pd=async()=>{Nr.debug("sending GET for device serial number");try{const t=await fd({urlOverride:`${di}/api/kos/device/serialNumber`});return[void 0,t==null?void 0:t.data.serialNumber]}catch(t){if(t instanceof ye)return Nr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},gd=async()=>{Nr.debug("sending GET for device details");try{const t=await fd({urlOverride:`${di}/api/kos/device`});return t?[void 0,t.data]:["unknownError",void 0]}catch(t){if(t instanceof ye)return Nr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},eE=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:gd,getSerialNumber:pd},Symbol.toStringTag,{value:"Module"}));var tE=Object.defineProperty,sE=Object.getOwnPropertyDescriptor,md=(t,e,s,r)=>{for(var o=r>1?void 0:r?sE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&tE(e,s,o),o};const yd="device-model",rE="/kos/criticalData/changed",oE="/kos/criticalData/available";let Ur=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_serialNumber");l(this,"_name");l(this,"_nodeId");this.id=t,this.logger=s.logger,this._serialNumber="unassigned",this._name="unassigned",this._nodeId="unassigned"}get serialNumber(){return this._serialNumber}get name(){return this._name}get nodeId(){return this._nodeId}get nodeType(){const[t]=this.nodeId.split("-");return t}get nodeName(){const[,t]=this.nodeId.split("-");return t}updateModel(t){this._serialNumber=t.serialNumber??"unassigned",this._name=t.name??"unassigned",this._nodeId=t.nodeId??"unassigned"}async loadDeviceData(){const[t,e]=await gd();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}if(e){const{name:s,nodeId:r}=e;this.updateModel({name:s,nodeId:r,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[t,e]=await pd();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}this.updateModel({serialNumber:e,name:this.name,nodeId:this.nodeId})}async handleCriticalDataChanged(){this.logger.debug(`Critical data changed for device ${this.id}`),await this.loadSerialNumber()}async init(){this.logger.debug(`initializing device ${this.id}`)}async load(){this.logger.debug(`loading device ${this.id}`),await this.loadDeviceData(),await this.loadSerialNumber()}};md([B({topic:[rE,oE],websocket:!0})],Ur.prototype,"handleCriticalDataChanged",1);Ur=md([R(yd)],Ur);const jr=new Se({class:Ur,type:yd});var nE=Object.getOwnPropertyDescriptor,iE=(t,e,s,r)=>{for(var o=r>1?void 0:r?nE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const bd="network-interface-model";let Yo=class{constructor(t,e,s){l(this,"id");l(this,"name");l(this,"type");l(this,"nmdevicestate");l(this,"hwaddress");l(this,"mtu");l(this,"configured");l(this,"wifi");l(this,"ethernet");l(this,"ip4settings");l(this,"category");l(this,"logger");this.id=t,this.logger=s.logger,this.name=e.name,this.type=e.type,this.nmdevicestate=e.nmdevicestate,this.hwaddress=e.hwaddress,this.mtu=e.mtu,this.configured=e.configured,this.wifi=e.wifi,this.ethernet=e.ethernet,this.ip4settings=e.ip4settings,this.category=e.category}updateModel(t){this.name=t.name,this.type=t.type,this.nmdevicestate=t.nmdevicestate,this.hwaddress=t.hwaddress,this.mtu=t.mtu,this.configured=t.configured,this.wifi=t.wifi,this.ethernet=t.ethernet,this.ip4settings=t.ip4settings,this.category=t.category}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};Yo=iE([R(bd)],Yo);const hi=new ve({class:Yo,type:bd}),{URL:aE}=ce(),{getAll:cE}=oe.build({basePath:`${aE}/api/kos/network/interfaces`}),fa=m.createLogger({name:"network-interface-service",group:"Services"}),vd=async()=>{fa.debug("sending GET for copy-logs");try{const t=await cE({});return[void 0,t==null?void 0:t.data]}catch(t){if(t instanceof ye)return fa.error(`Error fetching log file size: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},lE=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:vd},Symbol.toStringTag,{value:"Module"}));var uE=Object.defineProperty,dE=Object.getOwnPropertyDescriptor,wd=(t,e,s,r)=>{for(var o=r>1?void 0:r?dE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&uE(e,s,o),o};const Ed="network-interface-container-model";let Br=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new xe({parentId:t,indexMap:{byCategory:"category"}})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[t,e]=await vd();if(t){this.logger.error(`Error loading network interfaces: ${t}`);return}e&&e.forEach(s=>{const r=hi.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};wd([De],Br.prototype,"_models",2);Br=wd([R(Ed)],Br);const ks=new Se({class:Br,type:Ed});ks.addRelatedModel(hi);const{URL:hE}=ce(),{getAll:fE}=oe.build({basePath:`${hE}/api/kos/storage/devices`}),pa=m.createLogger({name:"storage-device-service",group:"Services"}),Md=async()=>{pa.debug("sending GET for storage-device");const t=await fE({});return!(t!=null&&t.data)||t.status!==200?(pa.error("Failed to retrieve storage-device data",t),[]):t.data},pE=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:Md},Symbol.toStringTag,{value:"Module"}));var gE=Object.getOwnPropertyDescriptor,mE=(t,e,s,r)=>{for(var o=r>1?void 0:r?gE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Td="storage-device-model";let Wo=class{constructor(t,e,s){l(this,"id");l(this,"mountDir");l(this,"removed");l(this,"vendor");l(this,"runTimeMs");l(this,"model");l(this,"nodeId");l(this,"local");l(this,"label");l(this,"syspath");l(this,"logger");this.id=t,this.logger=s.logger,this.mountDir=e.mountDir,this.removed=e.removed,this.vendor=e.vendor,this.runTimeMs=e.runTimeMs,this.model=e.model,this.nodeId=e.nodeId,this.local=e.local,this.label=e.label,this.syspath=e.syspath}updateModel(t){this.mountDir=t.mountDir,this.removed=t.removed,this.vendor=t.vendor,this.runTimeMs=t.runTimeMs,this.model=t.model,this.nodeId=t.nodeId,this.local=t.local,this.label=t.label,this.syspath=t.syspath}async init(){this.logger.debug(`initializing storage-device ${this.id}`)}async load(){this.logger.debug(`loading storage-device ${this.id}`)}};Wo=mE([Wr(),R(Td)],Wo);const Hr=new ve({class:Wo,type:Td});var yE=Object.defineProperty,bE=Object.getOwnPropertyDescriptor,fi=(t,e,s,r)=>{for(var o=r>1?void 0:r?bE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&yE(e,s,o),o};const _d="storage-device-container-model",vE="/kos/storage";let Ls=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new xe({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing storage-device-container container ${this.id}`)}get isStorageInserted(){return this.data.length>0}get volumes(){return this.data}handleStorageAvailability(t){this._models.data.filter(s=>!t.find(r=>r.id===s.id)).forEach(s=>{this.removeModel(s.id)}),t.forEach(s=>{const r=this.getModel(s.id);if(r){const o={...s,kosParentId:this.id};r.updateModel(o)}else{const o={...s,kosParentId:this.id},n=Hr.instance(s.id).options(o).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await Md()).forEach(e=>{if(e.deviceType!=="disk"){const s={...e,kosParentId:this.id},r=Hr.instance(e.id).options(s).build();this.addModel(r)}})}};fi([De],Ls.prototype,"_models",2);fi([B({topic:vE,websocket:!0})],Ls.prototype,"handleStorageAvailability",1);Ls=fi([R(_d)],Ls);const Ut=new Se({class:Ls,type:_d});Ut.addRelatedModel(Hr);const{URL:pi}=ce(),{getAll:wE,postModel:EE}=oe.build({basePath:`${pi}/api/kos/update/available`}),ga=m.createLogger({name:"usb-update-service",group:"Services"}),Sd=async()=>{ga.debug("sending GET for usb-update");const t=await wE({urlOverride:`${pi}/api/kos/update/available`});return!(t!=null&&t.data)||(t==null?void 0:t.status)!==200?(ga.error("Failed to retrieve usb-update data",t),[]):t.data},Od=async(t,e,s)=>{const r=await EE({model:{manifestId:t,deviceId:e},tracker:s,urlOverride:`${pi}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},ME=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:Sd,installUpdate:Od},Symbol.toStringTag,{value:"Module"}));var TE=Object.defineProperty,_E=Object.getOwnPropertyDescriptor,Id=(t,e,s,r)=>{for(var o=r>1?void 0:r?_E(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&TE(e,s,o),o};const $d="usb-update-model";let Kr=class{constructor(t,e,s){l(this,"id");l(this,"active");l(this,"blocked");l(this,"createTime");l(this,"deviceId");l(this,"manifestId");l(this,"notes");l(this,"futureHandler");l(this,"logger");this.id=t,this.logger=s.logger,this.active=e.active,this.blocked=e.blocked,this.createTime=e.createTime,this.deviceId=e.deviceId,this.manifestId=e.manifestId,this.notes=e.notes,this.futureHandler=new Xr(this)}updateModel(t){this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(t){if(!t)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),Od(this.manifestId,this.deviceId,t)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};Id([wi()],Kr.prototype,"install",1);Kr=Id([R($d)],Kr);const gi=new ve({class:Kr,type:$d});var SE=Object.defineProperty,OE=Object.getOwnPropertyDescriptor,fo=(t,e,s,r)=>{for(var o=r>1?void 0:r?OE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&SE(e,s,o),o};const Cd="usb-update-container-model";let jt=class{constructor(t,e,s){l(this,"id");l(this,"disposer");l(this,"storageService");l(this,"_activeUpdate");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new xe({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(t){this._activeUpdate=t}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const t=await Sd();X(()=>{const e=t.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!e.includes(s.id)).forEach(s=>this.removeModel(s.id)),t.forEach(s=>{const r=`${s.deviceId}-${s.manifestId}`,o=gi.instance(r).forceUpdate.options({...s,createTime:new Date(s.createTime)}).build();this.addModel(o)}),this.data.length===1?this.updateActiveUpdate(this.data[0]):this.clearActiveUpdate()})}usbInsertedEffect(){this.isUsbInserted?this.syncAvailableUpdates():(this._models.clear(),this.clearActiveUpdate())}async init(){this.logger.debug(`initializing usb-update-container container ${this.id}`)}unload(){var t;(t=this.disposer)==null||t.call(this)}async activate(){this.logger.debug(`activating usb-update-container container ${this.id}`),await this.syncAvailableUpdates()}async load(){this.logger.debug(`loading usb-update-container container ${this.id}`)}};fo([Ht({modelType:Ut.type})],jt.prototype,"storageService",2);fo([De],jt.prototype,"_models",2);fo([Rc({dependencies:t=>[t.isUsbInserted]})],jt.prototype,"usbInsertedEffect",1);jt=fo([R(Cd)],jt);const Fs=new Se({class:jt,type:Cd});Fs.addRelatedModel(gi);const IE=()=>({...{[zt.type]:{class:eu},[Ye.type]:{class:iu,singleton:!0},...re.registration,...ht.registration,...Lt.registration,...Rr.registration,...Ue.registration,[ai.type]:{class:exports.WsEventModel,singleton:!0},...Ps.registration,...ni.registration,..._r.registration}}),mi=IE(),$E={models:mi,preloadModels:[]},ma=!0,Dd=t=>()=>{const e=mi;return Kc(Qo)(Rs).model(Lt).model(Ut).model(Fs).model(jr).model(Cr).model(Os).model(Dr).model(Yn).model(ks).model(Nt).model(li).model(yu).model(zn,ma).model(Gs).model(wu,ma),Object.keys(e).forEach(s=>{const r=e[s];Hc(Qo)(s,r)}),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t)}},Te={};Te.core={models:Dd(Te)};Te.preload=A.model.preloadModel(Te);Te.model=A.model.register(Te);Te.companion=A.companion.register(Te);Te.legacy=A.model.registerLegacyModel(Te);const Qo=Te;class CE{registerTroubleRankMapper(e){return $.propertyMapper.registerPropertyMapper(Ee.TroubleRank,e),this}registerTroubleRoleMapper(e){return $.propertyMapper.registerPropertyMapper(Ee.TroubleRole,e),this}registerTroubleColorMapper(e){return $.propertyMapper.registerPropertyMapper(Ee.TroubleColor,e),this}registerModelLoader(e,s){$.loader.registerLoader(e,s)}registerCanvasPatternLoader(e){$.loader.registerLoader(Nt.loader,e)}}const DE=async(t,e)=>{const s=Yn.instance(t).options({}).build(),r=e?`${e}-`:"";return await fe(s),{getState:o=>s.data[`${r}${o}`],updateState:async(o,n)=>{await s.updateState(`${r}${o}`,n)},clean:async()=>{for(const o of s.data.keys)await s.updateState(`${r}${o}`,void 0)},unsubscribe:()=>{Oe(s)}}},xd="kos:service:region",Ad="regionId",xE=`${xd}-${Ad}`,Rd=async t=>{const e=ht.factory(xE)({path:xd,attribute:Ad});await fe(e),e.updateProperty(t)};function AE(t){return dt(t)}const ya=Be(),RE=Object.freeze(Object.defineProperty({__proto__:null,api:ya,default:ya,kosServiceRequest:AE},Symbol.toStringTag,{value:"Module"}));function PE(t){return dt(t)}const ba=Be(),kE=Object.freeze(Object.defineProperty({__proto__:null,api:ba,default:ba,kosServiceRequest:PE},Symbol.toStringTag,{value:"Module"}));function LE(t){return dt(t)}const va=Be(),FE=Object.freeze(Object.defineProperty({__proto__:null,api:va,default:va,kosServiceRequest:LE},Symbol.toStringTag,{value:"Module"}));function NE(t){return dt(t)}const wa=Be(),UE=Object.freeze(Object.defineProperty({__proto__:null,api:wa,default:wa,kosServiceRequest:NE},Symbol.toStringTag,{value:"Module"}));function jE(t){return dt(t)}const Ea=Be(),BE=Object.freeze(Object.defineProperty({__proto__:null,api:Ea,default:Ea,kosServiceRequest:jE},Symbol.toStringTag,{value:"Module"}));function HE(t){return dt(t)}const Ma=Be(),KE=Object.freeze(Object.defineProperty({__proto__:null,api:Ma,default:Ma,kosServiceRequest:HE},Symbol.toStringTag,{value:"Module"})),yi="/kos-timer-event",bi="/kos-timer-event/tick",vi="defaultTimerEnd",ds=m.createLogger({name:"timer-manager"}),qE=t=>t.updateProperty!==void 0;class Pd{constructor(e,s,r){l(this,"name");l(this,"timeout");l(this,"timer");l(this,"state","inactive");l(this,"decrementValue",1);l(this,"remainingTime");l(this,"timeoutActions",new Map);this.name=e;const o=typeof s=="number"?s:s.value||60;this.timeout=o,this.state="inactive",this.remainingTime=o,qE(s)&&G(()=>{m.info(`Updating config value timer ${e} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:vi}),r&&r.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){ds.debug(`Timer ${this.name} already started`);return}(this.state==="inactive"||this.state==="paused")&&(this.state="active",this.timer=setInterval(()=>this.updateTimer(),1e3))}pause(){this.timer&&(ds.debug(`Pausing timer ${this.name}`),this.state="paused",clearInterval(this.timer))}restart(){this.pause(),this.remainingTime=this.timeout,this.start()}reset(){this.pause(),this.remainingTime=this.timeout,this.state="inactive"}updateTimeout(e){this.timeout=e,this.restart()}addTimeoutAction(e){const s=e.remainingTime??0;this.timeoutActions.has(s)||this.timeoutActions.set(s,[]);const r=e.name,o=this.timeoutActions.get(s).find(n=>n.name===r);o?o.action=e.action:this.timeoutActions.get(s).push(e)}removeTimeoutAction(e){for(const[s,r]of this.timeoutActions.entries()){const o=r.filter(n=>n.name!==e);o.length===0?this.timeoutActions.delete(s):this.timeoutActions.set(s,o)}}updateTimer(){if(this.remainingTime=Math.round((this.remainingTime-this.decrementValue)*100)/100,this.remainingTime<=0){this.state==="active"&&this.executeActions(0),this.pause();return}this.state==="active"&&this.executeActions(this.remainingTime)}executeActions(e){this.timeoutActions.has(e)&&this.timeoutActions.get(e).forEach(s=>{var r;ds.debug(`Executing timer action ${s.name} at ${e}`),(r=s.action)==null||r.call(s,s.name,e),this.notifyTimeoutAction(s),s.singleUse&&(ds.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){q(`${bi}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(e){q(yi,{name:this.name,action:e.name,remainingTime:this.remainingTime})}}const hs=new Map,Et=(t,e)=>{const s=hs.get(t);if(!s){ds.error(`Timer ${t} not found`);return}e(s)},kd={createRelativeTimer(t,e,s){const r=new Date,o=Math.round((e.getTime()-r.getTime())/1e3);return this.createTimer(t,o,s)},createTimer(t,e=60,s){if(hs.has(t))return hs.get(t);const r=new Pd(t,e,s);return hs.set(t,r),r},getTimer(t){return hs.get(t)},clearTimer(t){Et(t,e=>e.pause())},restartTimer(t){Et(t,e=>e.restart())},resetTimer(t){Et(t,e=>e.reset())},addTimeoutAction(t,e){Et(t,s=>s.addTimeoutAction(e))},removeTimeoutAction(t,e){Et(t,s=>s.removeTimeoutAction(e))},startTimer(t){Et(t,e=>e.start())}},Ld="kos:service:region:settings",Fd="timeZone",zE=`${Ld}-${Fd}`,Zo=async t=>{const e=ht.factory(zE)({path:Ld,attribute:Fd});await fe(e),e.updateProperty(t)},VE=t=>!t||!t.data;function wi(t={}){const{alias:e,namespace:s,abortController:r=!1,trackerPolicy:o="id"}=t;return(n,i,a)=>{n[gs]=n[gs]||{},e&&(n[bs]=n[bs]||new Map,n[bs].set(i,e));const c=a.value,u=async function(...d){const h=lt();m.debug(`Calling future service ${i} with tracker ${h}`);let f,p;r&&(f=new AbortController);const y=at.initiateFuture({tracker:h,id:kn});s&&(y.namespace=s),m.debug(`waiting for future ${y.id} to be ready`),await fe(y),m.debug(`future ${y.id} is ready`),X(()=>{m.debug(`Adding future ${y.id} to futureHandler`),this.futureHandler.addFuture(y,e)}),r&&f&&(p=G(()=>{(y.status==="CANCELLED"||y.endState===Ge.Canceled)&&(m.debug(`Future ${y.id} cancelled, aborting request`),f==null||f.abort())}),f.signal.addEventListener("abort",async()=>{if(y.status!=="CANCELLED"&&y.endState!==Ge.Canceled&&!y.endState){m.debug(`AbortController aborted, cancelling future ${y.id}`);try{await y.cancelFuture()}catch(E){m.error(`Failed to cancel future ${y.id}:`,E)}}},{once:!0}));const w=()=>{p&&(p(),p=void 0)};try{const E=[...d];if(r&&f){const U=E[E.length-1];U&&typeof U=="object"&&"aborted"in U?E[E.length-1]=f.signal:E.push(f.signal)}if(o==="context"){const U=E[E.length-1];if(_n(U))U.$tracker=h;else{const I={[Qr]:!0,$tracker:h};E.push(I)}}else E.push(h);const _=await c.apply(this,E);m.debug(`received future response for ${h}`,_);const L=VE(_)?_:_==null?void 0:_.data;return L?(L.progress=1,m.debug("mapping future response to future model"),y.endState?m.debug(`future ${y.id} has already completed. Not updating the model`):Kn(L,y)):this.futureHandler.removeFuture(e),w(),L}catch(E){if(w(),r&&(f!=null&&f.signal.aborted)){const _=new Error("Operation cancelled");throw m.debug(`Operation ${i} was cancelled`),_}throw m.error(E),E}};n[gs][i]={handler:u}}}const GE=({path:t})=>(e,s)=>{e[F]=e[F]||{},e[F][s]={modelType:Ps.type,id:`${Ps.type}-${t}`,options:{path:t},lifecycle:x.INIT}};function YE(t){const{path:e,attribute:s}=t;return(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:ni.type,id:`${e}-${s}`,options:{path:e,attribute:s},lifecycle:x.INIT}}}const It=m.createLogger({name:"services",group:"Services"}),WE=async(t,e)=>Nd(t,e,`${exports.BASE_URL}/api/server/login`),Nd=async(t,e,s=`${exports.BASE_URL}/api/login`)=>{const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:t,password:e})});if(!r.ok){const n=await r.json();throw Error(`${n==null?void 0:n.error}`)}return await r.json()},QE=async t=>Ud(t,`${exports.BASE_URL}/api/server/startPasswordReset`,""),Ud=async(t,e=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const r=await exports.kosFetch(`${e}?email=${t}`,{method:"POST",destinationAddress:s});if(!r.ok)throw Error(`There was a problem reseting config; returned status ${r.status}`);return await r.json()},ZE=async(t,e)=>jd(t,e,`${exports.BASE_URL}/api/server/resetPassword`),jd=async(t,e,s=`${exports.BASE_URL}/api/resetPassword`)=>{It.debug(`resetting password with token ${t} and password ${e.replace(/./g,"*")}`);const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e})});if(It.debug(`password reset returned status ${r.status}`),!r.ok){It.error(`password reset failed with message ${r.statusText}`);const n=await r.json();throw Error(`${n==null?void 0:n.error}:There was a problem resetting the password.`)}return await r.json()},XE=async(t,e,s)=>Bd(t,e,s,`${exports.BASE_URL}/api/server/acceptInvite`),Bd=async(t,e,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{It.debug(`accepting invite with token ${t} and password ${e.replace(/./g,"*")}`);const o=await exports.kosFetch(`${r}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e,name:s})});if(It.debug(`invitation accept returned status ${o.status}`),!o.ok){It.error(`invite failed with message ${o.statusText}`);const i=await o.json();throw Error(`${i==null?void 0:i.error}:There was a problem accepting the invite.`)}return await o.json()};function JE(t,e,s,r){const o=t instanceof Promise?{promise:t,abortController:e,cancelFuture:s,future:r}:t,{promise:n,abortController:i,cancelFuture:a,future:c}=o,u=n;let d=0,h="PENDING",f=!0;const p=new Set;let y;return c&&typeof c=="object"&&(y=M.autorun(()=>{const w=c.progress||0,E=c.status||"PENDING",_=!c.endState;(w!==d||E!==h||_!==f)&&(d=w,h=E,f=_,p.forEach(L=>{try{L(d,h)}catch(U){console.warn("Progress callback error:",U)}}))})),n.finally(()=>{f=!1,i!=null&&i.signal.aborted||(h="COMPLETED",p.forEach(w=>{try{w(d,h)}catch(E){console.warn("Progress callback error:",E)}})),y&&y(),p.clear()}),u.cancel=async()=>{i&&!i.signal.aborted&&i.abort(),a&&await a(),f=!1,h="CANCELLED",p.forEach(w=>{try{w(d,h)}catch(E){console.warn("Progress callback error:",E)}}),y&&y()},u.getController=()=>i,u.isCancelled=()=>(i==null?void 0:i.signal.aborted)??!1,Object.defineProperty(u,"progress",{get:()=>d,enumerable:!0}),Object.defineProperty(u,"status",{get:()=>h,enumerable:!0}),Object.defineProperty(u,"isRunning",{get:()=>f,enumerable:!0}),u.onProgressUpdate=w=>(p.add(w),w(d,h),()=>p.delete(w)),u}const eM=tt.keyframes`
144
+ `,i=this.compileShader(r.VERTEX_SHADER,o),a=this.compileShader(r.FRAGMENT_SHADER,n);this.program=this.createProgram(i,a),this.posBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.posBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),r.STATIC_DRAW),this.aPosition=r.getAttribLocation(this.program,"a_position"),this.uMinHue=r.getUniformLocation(this.program,"minHue"),this.uMaxHue=r.getUniformLocation(this.program,"maxHue"),this.uHueOffset=r.getUniformLocation(this.program,"hueOffset"),this.uGridHeight=r.getUniformLocation(this.program,"gridHeight")}reset(){this.hueOffset=0,this.lastUpdate=performance.now()}renderFrame(s,r){const o=this.gl;if(this.canvas.width=s,this.canvas.height=r,this.shouldStep(50)){const n=this.speedPx/r;this.hueOffset=(this.hueOffset+n)%1}o.viewport(0,0,s,r),o.clear(o.COLOR_BUFFER_BIT),o.useProgram(this.program),o.enableVertexAttribArray(this.aPosition),o.bindBuffer(o.ARRAY_BUFFER,this.posBuffer),o.vertexAttribPointer(this.aPosition,2,o.FLOAT,!1,0,0),o.uniform1f(this.uMinHue,this.minHue/360),o.uniform1f(this.uMaxHue,this.maxHue/360),o.uniform1f(this.uHueOffset,this.hueOffset),o.uniform1f(this.uGridHeight,r),o.drawArrays(o.TRIANGLES,0,6)}compileShader(s,r){const o=this.gl.createShader(s);if(this.gl.shaderSource(o,r),this.gl.compileShader(o),!this.gl.getShaderParameter(o,this.gl.COMPILE_STATUS))throw new Error(this.gl.getShaderInfoLog(o)||"Shader compile failed");return o}createProgram(s,r){const o=this.gl.createProgram();if(this.gl.attachShader(o,s),this.gl.attachShader(o,r),this.gl.linkProgram(o),!this.gl.getProgramParameter(o,this.gl.LINK_STATUS))throw new Error("Program linking failed");return o}}class yt{constructor(){l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("2d");if(!e)throw new Error("2D canvas not supported");this.ctx=e}dispose(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove()}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}}function ui(t){class e extends t{constructor(){super(...arguments);l(this,"doneCallback",null);l(this,"oneShotDone",!1)}isOneShot(){return!0}onDone(o){this.doneCallback=o}signalDoneIfNeeded(){var o;this.oneShotDone||((o=this.doneCallback)==null||o.call(this),this.oneShotDone=!0)}resetOneShot(){this.doneCallback=null,this.oneShotDone=!1}get isOneShotDone(){return this.oneShotDone}}return e}const Fw=ui(yt);class Nw extends Fw{constructor({colors:s=["red","yellow","green"],direction:r="horizontal",speed:o=2,loop:n=!0}={}){super();l(this,"offset",0);l(this,"speed");l(this,"colors");l(this,"direction");l(this,"loop");this.colors=s,this.direction=r,this.speed=o,this.loop=n}reset(){this.offset=0,this.lastUpdate=performance.now(),this.loop||this.resetOneShot()}renderFrame(s,r){if(!this.loop&&this.isOneShotDone)return;this.loop&&this.shouldStep(50)&&(this.offset+=this.speed);const o=this.loop?-this.offset:0,n=this.loop?s*2-this.offset:s,i=this.ctx.createLinearGradient(o,0,n,0),a=1/(this.colors.length-1);this.colors.forEach((c,u)=>{i.addColorStop(u*a,c)}),this.ctx.fillStyle=i,this.ctx.fillRect(0,0,s,r),!this.loop&&!this.isOneShotDone&&this.signalDoneIfNeeded()}}const Uw=ui(yt);class ld extends Uw{constructor({src:s}){super();l(this,"img");l(this,"loaded",!1);this.img=new Image,this.img.src=s,this.img.crossOrigin="anonymous",this.img.onload=()=>{this.loaded=!0}}reset(){this.resetOneShot()}renderFrame(s,r){!this.loaded||this.isOneShotDone||(this.canvas.width=s,this.canvas.height=r,this.ctx.drawImage(this.img,0,0,s,r),this.signalDoneIfNeeded())}}class jw extends cd{constructor(s){super(s);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"startTime");l(this,"endTime");l(this,"completionCallback",null);this.loopConfig=s.loop??!1,this.startTime=s.startTime??0,this.endTime=s.endTime??null,this.video.removeEventListener("ended",this.handleEnded),this.video.addEventListener("ended",this.handleVideoEnd.bind(this)),this.startTime>0&&(this.video.currentTime=this.startTime),this.endTime!==null&&this.video.addEventListener("timeupdate",this.handleTimeUpdate.bind(this))}handleTimeUpdate(){this.endTime!==null&&this.video.currentTime>=this.endTime&&this.handleVideoEnd()}handleVideoEnd(){this.loopConfig===!0?(this.video.currentTime=this.startTime,this.video.play().catch(console.warn)):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.video.currentTime=this.startTime,this.video.play().catch(console.warn)):(this.video.pause(),this.completionCallback&&this.completionCallback())}reset(){super.reset(),this.currentLoopCount=0,this.video.currentTime=this.startTime}onDone(s){this.completionCallback=s}isOneShot(){return this.loopConfig===!1||this.loopConfig===1}dispose(){this.video.removeEventListener("ended",this.handleVideoEnd),this.video.removeEventListener("timeupdate",this.handleTimeUpdate),this.completionCallback=null,super.dispose()}}function Bw(t){const e=t.replace("#","");if(!/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(e))throw new Error(`Invalid hex color: ${t}`);let s,r,o;return e.length===3?(s=parseInt(e[0]+e[0],16),r=parseInt(e[1]+e[1],16),o=parseInt(e[2]+e[2],16)):(s=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),o=parseInt(e.substring(4,6),16)),{r:s,g:r,b:o}}function ud(t){return typeof t=="string"?Bw(t):t}function Lr(t){const e=ud(t);return`rgb(${e.r},${e.g},${e.b})`}class Hw extends yt{constructor(s={}){super();l(this,"columns",[]);l(this,"fallChance");l(this,"speed");l(this,"baseColor");l(this,"trailColors");this.speed=s.speed??1,this.fallChance=s.fallChance??.7,s.baseColor?this.baseColor=ud(s.baseColor):this.baseColor={r:0,g:255,b:255},this.trailColors=this.calculateTrailColors()}calculateTrailColors(){const r=[];for(let o=0;o<=5;o++){const n=1-o/5*.6;r.push({r:Math.floor(this.baseColor.r*n),g:Math.floor(this.baseColor.g*n),b:Math.floor(this.baseColor.b*n)})}return r}reset(){this.columns=[],this.lastUpdate=performance.now()}renderFrame(s,r){this.columns.length!==s&&(this.columns=Array(s).fill(0).map(()=>Math.floor(Math.random()*r))),this.shouldStep(50)&&(this.columns=this.columns.map(i=>i>r+5?0:i+(Math.random()<this.fallChance?this.speed:0)));const o=this.ctx.createImageData(s,r),n=o.data;n.fill(0);for(let i=0;i<r;i++)for(let a=0;a<s;a++){const c=this.columns[a];let u=0,d=0,h=0;if(i===c)u=this.baseColor.r,d=this.baseColor.g,h=this.baseColor.b;else if(i<c&&i>c-this.trailColors.length){const p=c-i;if(p<this.trailColors.length){const y=this.trailColors[p];u=y.r,d=y.g,h=y.b}}const f=(i*s+a)*4;n[f]=u,n[f+1]=d,n[f+2]=h,n[f+3]=255}this.ctx.putImageData(o,0,0)}}class Kw{constructor(e,s){l(this,"baseRenderer");l(this,"overlayIcons",new Map);l(this,"overlayConfigs");l(this,"loadedIcons",new Set);l(this,"canvas");l(this,"ctx");l(this,"persistOverlaysOnComplete");l(this,"baseRendererCompleted",!1);l(this,"completionCallback",null);l(this,"hasSignaledCompletion",!1);this.baseRenderer=s(e.baseRenderer.type,e.baseRenderer.data),this.overlayConfigs=e.overlays,this.persistOverlaysOnComplete=e.persistOverlaysOnComplete!==!1,this.canvas=document.createElement("canvas");const r=this.canvas.getContext("2d");if(!r)throw new Error("2D canvas not supported");this.ctx=r,this.loadOverlayImages(),"onDone"in this.baseRenderer&&typeof this.baseRenderer.onDone=="function"&&this.baseRenderer.onDone(()=>{this.baseRendererCompleted=!0,!this.persistOverlaysOnComplete&&this.completionCallback&&this.completionCallback()})}async loadOverlayImages(){for(const e of this.overlayConfigs){const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{this.loadedIcons.add(e.src)},s.onerror=r=>{console.error(`Failed to load overlay image: ${e.src}`,r)},s.src=e.src,this.overlayIcons.set(e.src,s)}}calculateOverlayPosition(e,s,r){let o,n;if(typeof e.position=="string")switch(e.position){case"top-left":o=0,n=0;break;case"top-center":o=(s-e.size)/2,n=0;break;case"top-right":o=s-e.size,n=0;break;case"center-left":o=0,n=(r-e.size)/2;break;case"center":o=(s-e.size)/2,n=(r-e.size)/2;break;case"center-right":o=s-e.size,n=(r-e.size)/2;break;case"bottom-left":o=0,n=r-e.size;break;case"bottom-center":o=(s-e.size)/2,n=r-e.size;break;case"bottom-right":o=s-e.size,n=r-e.size;break;default:o=0,n=0}else o=e.position.x,n=e.position.y;return e.offset&&(o+=e.offset.x||0,n+=e.offset.y||0),{x:o,y:n}}reset(){this.baseRenderer.reset(),this.baseRendererCompleted=!1,this.hasSignaledCompletion=!1}renderFrame(e,s){if(this.canvas.width=e,this.canvas.height=s,this.ctx.clearRect(0,0,e,s),this.baseRendererCompleted&&this.persistOverlaysOnComplete)this.renderOverlays(e,s);else{this.baseRenderer.renderFrame(e,s);const r=this.baseRenderer.readPixels(e,s);if(r&&r.length>0){const o=new ImageData(r,e,s);this.ctx.putImageData(o,0,0)}this.renderOverlays(e,s)}}renderOverlays(e,s){for(const r of this.overlayConfigs){if(!r.persistent&&r.persistent!==void 0)continue;const o=this.overlayIcons.get(r.src);if(!o||!this.loadedIcons.has(r.src))continue;const n=this.calculateOverlayPosition(r,e,s);this.ctx.save(),r.opacity!==void 0&&(this.ctx.globalAlpha=Math.max(0,Math.min(1,r.opacity))),this.ctx.drawImage(o,n.x,n.y,r.size,r.size),this.ctx.restore()}}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}play(){this.baseRenderer.play&&this.baseRenderer.play()}pause(){this.baseRenderer.pause&&this.baseRenderer.pause()}dispose(){this.overlayIcons.clear(),this.loadedIcons.clear(),this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove(),this.baseRenderer.dispose&&this.baseRenderer.dispose()}onDone(e){this.completionCallback=e,this.hasSignaledCompletion&&e()}isOneShot(){return this.persistOverlaysOnComplete?!1:"isOneShot"in this.baseRenderer&&typeof this.baseRenderer.isOneShot=="function"?this.baseRenderer.isOneShot():!1}}class dd extends yt{constructor(s){super();l(this,"img");l(this,"loaded",!1);l(this,"scrollConfig");l(this,"loopConfig");l(this,"duration");l(this,"pauseDuration");l(this,"colorOverride");l(this,"originalSvgData",null);l(this,"position",0);l(this,"startTime",0);l(this,"lastFrameTime",0);l(this,"currentLoopCount",0);l(this,"completionCallback",null);l(this,"isPlaying",!1);l(this,"completed",!1);l(this,"isPaused",!1);l(this,"pauseStartTime",0);this.img=new Image,this.img.crossOrigin="anonymous",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,this.colorOverride=s.colorOverride,this.colorOverride&&s.src.toLowerCase().includes(".svg")?this.loadAndProcessSvg(s.src):this.img.src=s.src,this.img.onload=()=>{this.loaded=!0},this.img.onerror=r=>{console.error("Failed to load image:",r)}}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(!this.loaded||this.completed)return;if(this.isPaused){this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.ctx.drawImage(this.img,0,0,s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const c=performance.now(),u=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const d=n*u;switch(o){case"left":this.position+=d;break;case"right":this.position+=d;break;case"up":this.position+=d;break;case"down":this.position+=d;break}}this.drawScrollingImage(s,r,o,i),this.checkScrollCompletion(s,r,o,i)}drawScrollingImage(s,r,o,n){var h,f,p,y,w,E,_,L,U;const i=this.img.width/this.img.height;let a,c;((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(f=this.scrollConfig)!=null&&f.height?(c=this.scrollConfig.height,a=c*i):(p=this.scrollConfig)!=null&&p.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,c=((w=this.scrollConfig)==null?void 0:w.height)||r);let u,d;switch(o==="left"||o==="right"?(u=0,((E=this.scrollConfig)==null?void 0:E.offsetY)==="center"||((_=this.scrollConfig)==null?void 0:_.offsetY)===void 0?d=(r-c)/2:d=this.scrollConfig.offsetY):(((L=this.scrollConfig)==null?void 0:L.offsetX)==="center"||((U=this.scrollConfig)==null?void 0:U.offsetX)===void 0?u=(s-a)/2:u=this.scrollConfig.offsetX,d=0),o){case"left":{const I=s-this.position;if(I<s&&I>-a&&this.ctx.drawImage(this.img,I,d,a,c),this.loopConfig&&this.pauseDuration===0&&this.position>n){const S=I+a+n;S<s&&this.ctx.drawImage(this.img,S,d,a,c)}break}case"right":{const I=-a+this.position;if(I>-a&&I<s&&this.ctx.drawImage(this.img,I,d,a,c),this.loopConfig&&this.pauseDuration===0&&I-n-a>-a){const S=I-a-n;S<s&&this.ctx.drawImage(this.img,S,d,a,c)}break}case"up":{const I=r-this.position;if(I>-c&&I<r&&this.ctx.drawImage(this.img,u,I,a,c),this.loopConfig&&this.pauseDuration===0&&I+c+n<r){const S=I+c+n;S>-c&&this.ctx.drawImage(this.img,u,S,a,c)}break}case"down":{const I=-c+this.position;if(I>-c&&I<r&&this.ctx.drawImage(this.img,u,I,a,c),this.loopConfig&&this.pauseDuration===0&&I-n-c>-c){const S=I-c-n;S<r&&this.ctx.drawImage(this.img,u,S,a,c)}break}}}checkScrollCompletion(s,r,o,n){var h,f,p,y,w;if(!this.isPlaying)return;const i=this.img.width/this.img.height;let a,c;switch(((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(f=this.scrollConfig)!=null&&f.height?(c=this.scrollConfig.height,a=c*i):(p=this.scrollConfig)!=null&&p.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,c=((w=this.scrollConfig)==null?void 0:w.height)||r),o){case"left":case"right":this.loopConfig;break;case"up":case"down":this.loopConfig;break}let u=!1;const d=1;switch(o){case"left":u=s-this.position<-a-d;break;case"right":u=-a+this.position>s+d;break;case"up":u=r-this.position<-c-d;break;case"down":u=-c+this.position>r+d;break}u&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}async loadAndProcessSvg(s){try{const o=await(await fetch(s)).text();this.originalSvgData=o;const n=this.applySvgColorOverride(o),i=`data:image/svg+xml;base64,${btoa(n)}`;this.img.src=i}catch(r){console.error("Failed to load and process SVG:",r),this.img.src=s}}applySvgColorOverride(s){if(!this.colorOverride)return s;const r=Lr(this.colorOverride);return s.replace(/fill\s*=\s*["'][^"']*["']/gi,`fill="${r}"`).replace(/fill\s*:\s*[^;"]*/gi,`fill:${r}`).replace(/stroke\s*=\s*["'][^"']*["']/gi,`stroke="${r}"`).replace(/stroke\s*:\s*[^;"]*/gi,`stroke:${r}`)}dispose(){this.img.removeAttribute("src"),this.completionCallback=null,this.originalSvgData=null}}class qw extends yt{constructor(s){super();l(this,"text");l(this,"lines");l(this,"fontSize");l(this,"fontFamily");l(this,"lineHeight");l(this,"textColor");l(this,"scrollConfig");l(this,"loopConfig");l(this,"duration");l(this,"pauseDuration");l(this,"position",0);l(this,"startTime",0);l(this,"lastFrameTime",0);l(this,"currentLoopCount",0);l(this,"completionCallback",null);l(this,"isPlaying",!1);l(this,"completed",!1);l(this,"isPaused",!1);l(this,"pauseStartTime",0);l(this,"textWidth",0);l(this,"textHeight",0);l(this,"lineWidths",[]);l(this,"textMeasured",!1);this.text=s.text,this.lines=s.text.split(`
145
+ `),this.fontSize=s.fontSize??8,this.lineHeight=s.lineHeight??this.fontSize+2,this.fontFamily=s.fontFamily??"monospace, 'Lucida Console', 'Courier New', Courier",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,s.color?this.textColor=Lr(s.color):this.textColor="rgb(255,255,255)"}measureText(){if(this.textMeasured)return;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.lineWidths=[];let s=0;for(const r of this.lines){const n=this.ctx.measureText(r).width;this.lineWidths.push(n),s=Math.max(s,n)}this.textWidth=s,this.textHeight=this.lines.length*this.lineHeight,this.textMeasured=!0}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0,this.textMeasured=!1,this.lineWidths=[]}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(this.canvas.width=s,this.canvas.height=r,this.measureText(),this.completed)return;if(this.isPaused){this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.drawStaticText(s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const c=performance.now(),u=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const d=n*u;switch(o){case"left":case"right":case"up":case"down":this.position+=d;break}}this.drawScrollingText(s,r,o,i),this.checkScrollCompletion(s,r,o)}drawStaticText(s,r){this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";const o=this.textHeight;let n=(r-o)/2;for(let i=0;i<this.lines.length;i++){const a=this.lines[i],c=this.lineWidths[i],u=(s-c)/2,d=n+i*this.lineHeight;this.ctx.fillText(a,u,d)}}drawScrollingText(s,r,o,n){var c,u,d,h;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";let i,a;o==="left"||o==="right"?(i=0,((c=this.scrollConfig)==null?void 0:c.offsetY)==="center"||((u=this.scrollConfig)==null?void 0:u.offsetY)===void 0?a=(r-this.textHeight)/2:a=this.scrollConfig.offsetY):(((d=this.scrollConfig)==null?void 0:d.offsetX)==="center"||((h=this.scrollConfig)==null?void 0:h.offsetX)===void 0?(i=s/2,this.ctx.textAlign="center"):(i=this.scrollConfig.offsetX,this.ctx.textAlign="left"),a=0),this.drawMultiLineScrollText(o,s,r,n,i,a)}drawMultiLineScrollText(s,r,o,n,i,a){switch(s){case"left":{const c=r-this.position;if(c<r&&c>-this.textWidth&&this.drawTextBlock(c,a,"left"),this.loopConfig&&this.pauseDuration===0&&this.position>n){const u=c+this.textWidth+n;u<r&&this.drawTextBlock(u,a,"left")}break}case"right":{const c=-this.textWidth+this.position;if(c>-this.textWidth&&c<r&&this.drawTextBlock(c,a,"left"),this.loopConfig&&this.pauseDuration===0&&c-n-this.textWidth>-this.textWidth){const u=c-this.textWidth-n;u<r&&this.drawTextBlock(u,a,"left")}break}case"up":{const c=o-this.position;if(c>-this.textHeight&&c<o&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c+this.textHeight+n<o){const u=c+this.textHeight+n;u>-this.textHeight&&this.drawTextBlock(i,u,"center")}break}case"down":{const c=-this.textHeight+this.position;if(c>-this.textHeight&&c<o&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c-n-this.textHeight>-this.textHeight){const u=c-this.textHeight-n;u<o&&this.drawTextBlock(i,u,"center")}break}}}drawTextBlock(s,r,o){for(let n=0;n<this.lines.length;n++){const i=this.lines[n],a=this.lineWidths[n];let c;o==="center"?c=s-a/2:c=s;const u=r+n*this.lineHeight;this.ctx.fillText(i,c,u)}}checkScrollCompletion(s,r,o){if(!this.isPlaying)return;let n=!1;const i=1;switch(o){case"left":n=s-this.position<-this.textWidth-i;break;case"right":n=-this.textWidth+this.position>s+i;break;case"up":n=r-this.position<-this.textHeight-i;break;case"down":n=-this.textHeight+this.position>r+i;break}n&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}dispose(){this.completionCallback=null}}class zw{constructor(e){l(this,"patterns");l(this,"currentPatternIndex",0);l(this,"currentRenderer",null);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"transitionDuration");l(this,"patternOverrides");l(this,"completionCallback",null);l(this,"patternStore");l(this,"canvas");l(this,"ctx");l(this,"width",0);l(this,"height",0);this.patterns=e.patterns,this.loopConfig=e.loop??!1,this.transitionDuration=e.transitionDuration??0,this.patternOverrides=e.patternOverrides??{},this.patternStore=e.patternStore??new Map,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");if(this.ctx=s,this.patterns.length===0)throw new Error("SequenceRenderer requires at least one pattern");this.loadCurrentPattern()}loadCurrentPattern(){var n,i,a,c;const e=this.patterns[this.currentPatternIndex],s=this.patternStore.get(e);if(!s){console.warn(`Pattern "${e}" not found in store, skipping`),this.moveToNextPattern();return}this.currentRenderer&&((i=(n=this.currentRenderer).dispose)==null||i.call(n));const r=this.patternOverrides[e]??{},o={...s.data,...r};try{this.currentRenderer=Fr({mode:s.type,data:o}),this.currentRenderer&&this.isDoneAware(this.currentRenderer)&&this.currentRenderer.onDone(()=>{this.handlePatternComplete()}),this.currentRenderer&&(this.currentRenderer.reset(),(c=(a=this.currentRenderer).play)==null||c.call(a),this.width>0&&this.height>0&&this.currentRenderer.renderFrame(this.width,this.height))}catch(u){console.error(`Failed to create renderer for pattern "${e}":`,u),this.moveToNextPattern()}}isDoneAware(e){return typeof(e==null?void 0:e.onDone)=="function"}handlePatternComplete(){this.transitionDuration>0?setTimeout(()=>{this.moveToNextPattern()},this.transitionDuration):this.moveToNextPattern()}moveToNextPattern(){this.currentPatternIndex++,this.currentPatternIndex>=this.patterns.length?this.loopConfig===!0?(this.currentPatternIndex=0,this.loadCurrentPattern()):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.currentPatternIndex=0,this.loadCurrentPattern()):this.completionCallback&&this.completionCallback():this.loadCurrentPattern()}reset(){this.currentPatternIndex=0,this.currentLoopCount=0,this.loadCurrentPattern()}play(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.play)==null||s.call(e)}pause(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.pause)==null||s.call(e)}renderFrame(e,s){this.width=e,this.height=s,this.canvas.width=e,this.canvas.height=s,this.currentRenderer&&this.currentRenderer.renderFrame(e,s)}readPixels(e,s){return this.currentRenderer?this.currentRenderer.readPixels(e,s):this.ctx.getImageData(0,0,e,s).data}onDone(e){this.completionCallback=e}isOneShot(){var e,s;return this.loopConfig===!1||this.loopConfig===1?this.patterns.length===1&&this.currentRenderer?((s=(e=this.currentRenderer).isOneShot)==null?void 0:s.call(e))??!1:!0:!1}dispose(){var e,s;this.currentRenderer&&((s=(e=this.currentRenderer).dispose)==null||s.call(e)),this.completionCallback=null}setPatternStore(e){this.patternStore=e,this.patterns.length>0&&this.loadCurrentPattern()}}const Vw=ui(yt);class Gw extends Vw{constructor(s={r:0,g:0,b:0}){super();l(this,"color");let r;s.color!==void 0?r=s.color:s.r!==void 0&&s.g!==void 0&&s.b!==void 0?r={r:s.r,g:s.g,b:s.b}:r={r:0,g:0,b:0},this.color=Lr(r)}setColor(s){this.color=Lr(s),this.resetOneShot()}reset(){this.resetOneShot()}renderFrame(s,r){this.isOneShotDone||(this.canvas.width=s,this.canvas.height=r,this.ctx.fillStyle=this.color,this.ctx.fillRect(0,0,s,r),this.signalDoneIfNeeded())}}class Yw extends yt{constructor({minHue:s=0,maxHue:r=360,speed:o=1}={}){super();l(this,"offset",0);l(this,"minHue");l(this,"maxHue");l(this,"speed");this.minHue=s,this.maxHue=r,this.speed=o}reset(){this.offset=0,this.lastUpdate=performance.now()}hslToRgb(s,r,o){let n,i,a;if(r===0)n=i=a=o;else{const c=(h,f,p)=>(p<0&&(p+=1),p>1&&(p-=1),p<.16666666666666666?h+(f-h)*6*p:p<.5?f:p<.6666666666666666?h+(f-h)*(.6666666666666666-p)*6:h),u=o<.5?o*(1+r):o+r-o*r,d=2*o-u;n=c(d,u,s+1/3),i=c(d,u,s),a=c(d,u,s-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(a*255)]}renderFrame(s,r){this.shouldStep(50)&&(this.offset=(this.offset+this.speed)%s);const o=this.ctx.createImageData(s,r),n=o.data;let i=0;for(let a=0;a<r;a++)for(let c=0;c<s;c++){const u=(c+this.offset)%s/s,d=this.minHue/360+u*((this.maxHue-this.minHue)/360),[h,f,p]=this.hslToRgb(d,1,.5);n[i++]=h,n[i++]=f,n[i++]=p,n[i++]=255}this.ctx.putImageData(o,0,0)}}const ha=new Map;js(ee,{register(t,e){ha.set(t,e)},execute(t,e){const s=ha.get(t);return s?new s(e):null}});$.canvas.registerRenderer("video",jw);$.canvas.registerRenderer("video-basic",cd);$[ee].register("image-static",ld);$[ee].register("image-scrolling",dd);const Ww=class{constructor(t){var e;return(e=t.scroll)!=null&&e.enabled?new dd(t):new ld(t)}};$[ee].register("image",Ww);$[ee].register("color",Gw);$[ee].register("matrix",Hw);$[ee].register("sweep",Yw);$[ee].register("gradient",Nw);$[ee].register("drop",Lw);$[ee].register("sequence",zw);$[ee].register("text",qw);const Qw=class{constructor(t){const e=(s,r)=>{const o=Fr({mode:s,data:r});if(!o)throw new Error(`Failed to create renderer of type: ${s}`);return o};return new Kw(t,e)}};$[ee].register("overlay",Qw);const Fr=({mode:t,data:e})=>{const s=$[ee].execute(t,e);if(s)return s;throw new Error(`Unknown mode: ${t}`)};var Zw=Object.defineProperty,Xw=Object.getOwnPropertyDescriptor,Qt=(t,e,s,r)=>{for(var o=r>1?void 0:r?Xw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Zw(e,s,o),o};const hd="canvas-dispatcher-model";function Jw(t){if(t=t.replace(/^#/,""),t.length===3&&(t=t.split("").map(s=>s+s).join("")),t.length!==6)return null;const e=parseInt(t,16);return{r:e>>16&255,g:e>>8&255,b:e&255}}let We=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_content",new Map);l(this,"_patterns",new Map);l(this,"_endpointRenderers");l(this,"pattern");l(this,"data");this.id=t,this.logger=s.logger,this._endpointRenderers=new xe}addNamedEndpoint(t,e){this._endpointRenderers.getModel(t)&&this.logger.warn(`Endpoint "${t}" already exists. Overwriting.`);const s=li.instance(t).options({apiPath:e.apiPath,width:e.width,height:e.height,fps:e.fps,durationMs:e.durationMs??null,endpoint:t}).build();return this._endpointRenderers.addModel(s),s}addContent(t,e){this._content.has(t)&&this.logger.warn(`Content "${t}" already exists. Overwriting.`),this._content.set(t,e)}addPattern(t,e){this._patterns.has(t)&&this.logger.warn(`Pattern "${t}" already exists. Overwriting.`),this._patterns.set(t,e)}async handlePatternsPost(t,e){var o,n;const s=t.body,r=Array.isArray(s)?s:[s];if(r.some(i=>!i.id||!i.type||!i.data)){(o=e.status)==null||o.call(e,400).send({error:"Invalid pattern data"});return}for(const i of r)this._patterns.has(i.id)&&this.logger.warn(`Pattern "${i.id}" already exists. Overwriting.`),this.addPattern(i.id,i);(n=e.status)==null||n.call(e,200).send({status:"OK"})}async handlePatternApplication(t,e){var u,d,h;const s=t.params.pattern,r=t.params.endpoint,o=this._endpointRenderers.getModel(r);if(!o){(u=e.status)==null||u.call(e,404).send({error:`Endpoint "${r}" not found`});return}if(!this._patterns.has(s)){(d=e.status)==null||d.call(e,404).send({error:`Pattern "${s}" not found`});return}const n=this._patterns.get(s),i=n.type,a=t.body||{};this.data={...n.data,...a};const c=i==="sequence"?{...this.data,patternStore:this._patterns}:this.data;o.renderer=Fr({mode:i,data:c}),o.setClearOnComplete(n.clearOnComplete),o.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleColorApplication(t,e){var u,d,h;const s=t.params.color,r=Jw(s);if(!r){(u=e.status)==null||u.call(e,400).send({error:"Invalid color format"});return}const o=t.params.endpoint,n=this._endpointRenderers.getModel(o);if(!n){(d=e.status)==null||d.call(e,404).send({error:`Endpoint "${o}" not found`});return}const{r:i,b:a,g:c}=r;n.renderer=Fr({mode:"color",data:{r:i,g:c,b:a}}),n.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleEndpointCreation(t,e){var r,o;const s=t.body;if(!s.apiPath||!s.id){(r=e.status)==null||r.call(e,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(s.id,s),(o=e.status)==null||o.call(e,200).send({status:"OK"})}async load(t){var s;const e=t==null?void 0:t.get(Nt.loader);e&&((s=e.patterns)==null||s.forEach(r=>{if(!r.id||!r.type||!r.data){this.logger.warn(`Invalid pattern data: ${JSON.stringify(r)}`);return}this.addPattern(r.id,r)}))}};Qt([De],We.prototype,"_endpointRenderers",2);Qt([Ks("/api/ui/canvas/patterns")],We.prototype,"handlePatternsPost",1);Qt([Ks("/api/ui/canvas/pattern/:endpoint/:pattern")],We.prototype,"handlePatternApplication",1);Qt([Ks("/api/ui/canvas/color/:endpoint/:color")],We.prototype,"handleColorApplication",1);Qt([Ks("/api/ui/canvas/endpoint")],We.prototype,"handleEndpointCreation",1);We=Qt([R(hd)],We);const Nt=new Se({class:We,type:hd}),{URL:di}=ce(),{getOne:fd}=oe.build({basePath:`${di}/api/device`}),Nr=m.createLogger({name:"device-service",group:"Services"}),pd=async()=>{Nr.debug("sending GET for device serial number");try{const t=await fd({urlOverride:`${di}/api/kos/device/serialNumber`});return[void 0,t==null?void 0:t.data.serialNumber]}catch(t){if(t instanceof ye)return Nr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},gd=async()=>{Nr.debug("sending GET for device details");try{const t=await fd({urlOverride:`${di}/api/kos/device`});return t?[void 0,t.data]:["unknownError",void 0]}catch(t){if(t instanceof ye)return Nr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},eE=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:gd,getSerialNumber:pd},Symbol.toStringTag,{value:"Module"}));var tE=Object.defineProperty,sE=Object.getOwnPropertyDescriptor,md=(t,e,s,r)=>{for(var o=r>1?void 0:r?sE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&tE(e,s,o),o};const yd="device-model",rE="/kos/criticalData/changed",oE="/kos/criticalData/available";let Ur=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_serialNumber");l(this,"_name");l(this,"_nodeId");this.id=t,this.logger=s.logger,this._serialNumber="unassigned",this._name="unassigned",this._nodeId="unassigned"}get serialNumber(){return this._serialNumber}get name(){return this._name}get nodeId(){return this._nodeId}get nodeType(){const[t]=this.nodeId.split("-");return t}get nodeName(){const[,t]=this.nodeId.split("-");return t}updateModel(t){this._serialNumber=t.serialNumber??"unassigned",this._name=t.name??"unassigned",this._nodeId=t.nodeId??"unassigned"}async loadDeviceData(){const[t,e]=await gd();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}if(e){const{name:s,nodeId:r}=e;this.updateModel({name:s,nodeId:r,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[t,e]=await pd();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}this.updateModel({serialNumber:e,name:this.name,nodeId:this.nodeId})}async handleCriticalDataChanged(){this.logger.debug(`Critical data changed for device ${this.id}`),await this.loadSerialNumber()}async init(){this.logger.debug(`initializing device ${this.id}`)}async load(){this.logger.debug(`loading device ${this.id}`),await this.loadDeviceData(),await this.loadSerialNumber()}};md([B({topic:[rE,oE],websocket:!0})],Ur.prototype,"handleCriticalDataChanged",1);Ur=md([R(yd)],Ur);const jr=new Se({class:Ur,type:yd});var nE=Object.getOwnPropertyDescriptor,iE=(t,e,s,r)=>{for(var o=r>1?void 0:r?nE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const bd="network-interface-model";let Yo=class{constructor(t,e,s){l(this,"id");l(this,"name");l(this,"type");l(this,"nmdevicestate");l(this,"hwaddress");l(this,"mtu");l(this,"configured");l(this,"wifi");l(this,"ethernet");l(this,"ip4settings");l(this,"category");l(this,"logger");this.id=t,this.logger=s.logger,this.name=e.name,this.type=e.type,this.nmdevicestate=e.nmdevicestate,this.hwaddress=e.hwaddress,this.mtu=e.mtu,this.configured=e.configured,this.wifi=e.wifi,this.ethernet=e.ethernet,this.ip4settings=e.ip4settings,this.category=e.category}updateModel(t){this.name=t.name,this.type=t.type,this.nmdevicestate=t.nmdevicestate,this.hwaddress=t.hwaddress,this.mtu=t.mtu,this.configured=t.configured,this.wifi=t.wifi,this.ethernet=t.ethernet,this.ip4settings=t.ip4settings,this.category=t.category}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};Yo=iE([R(bd)],Yo);const hi=new ve({class:Yo,type:bd}),{URL:aE}=ce(),{getAll:cE}=oe.build({basePath:`${aE}/api/kos/network/interfaces`}),fa=m.createLogger({name:"network-interface-service",group:"Services"}),vd=async()=>{fa.debug("sending GET for copy-logs");try{const t=await cE({});return[void 0,t==null?void 0:t.data]}catch(t){if(t instanceof ye)return fa.error(`Error fetching log file size: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},lE=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:vd},Symbol.toStringTag,{value:"Module"}));var uE=Object.defineProperty,dE=Object.getOwnPropertyDescriptor,wd=(t,e,s,r)=>{for(var o=r>1?void 0:r?dE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&uE(e,s,o),o};const Ed="network-interface-container-model";let Br=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new xe({parentId:t,indexMap:{byCategory:"category"}})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[t,e]=await vd();if(t){this.logger.error(`Error loading network interfaces: ${t}`);return}e&&e.forEach(s=>{const r=hi.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};wd([De],Br.prototype,"_models",2);Br=wd([R(Ed)],Br);const ks=new Se({class:Br,type:Ed});ks.addRelatedModel(hi);const{URL:hE}=ce(),{getAll:fE}=oe.build({basePath:`${hE}/api/kos/storage/devices`}),pa=m.createLogger({name:"storage-device-service",group:"Services"}),Md=async()=>{pa.debug("sending GET for storage-device");const t=await fE({});return!(t!=null&&t.data)||t.status!==200?(pa.error("Failed to retrieve storage-device data",t),[]):t.data},pE=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:Md},Symbol.toStringTag,{value:"Module"}));var gE=Object.getOwnPropertyDescriptor,mE=(t,e,s,r)=>{for(var o=r>1?void 0:r?gE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Td="storage-device-model";let Wo=class{constructor(t,e,s){l(this,"id");l(this,"mountDir");l(this,"removed");l(this,"vendor");l(this,"runTimeMs");l(this,"model");l(this,"nodeId");l(this,"local");l(this,"label");l(this,"syspath");l(this,"logger");this.id=t,this.logger=s.logger,this.mountDir=e.mountDir,this.removed=e.removed,this.vendor=e.vendor,this.runTimeMs=e.runTimeMs,this.model=e.model,this.nodeId=e.nodeId,this.local=e.local,this.label=e.label,this.syspath=e.syspath}updateModel(t){this.mountDir=t.mountDir,this.removed=t.removed,this.vendor=t.vendor,this.runTimeMs=t.runTimeMs,this.model=t.model,this.nodeId=t.nodeId,this.local=t.local,this.label=t.label,this.syspath=t.syspath}async init(){this.logger.debug(`initializing storage-device ${this.id}`)}async load(){this.logger.debug(`loading storage-device ${this.id}`)}};Wo=mE([Wr(),R(Td)],Wo);const Hr=new ve({class:Wo,type:Td});var yE=Object.defineProperty,bE=Object.getOwnPropertyDescriptor,fi=(t,e,s,r)=>{for(var o=r>1?void 0:r?bE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&yE(e,s,o),o};const _d="storage-device-container-model",vE="/kos/storage";let Ls=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new xe({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing storage-device-container container ${this.id}`)}get isStorageInserted(){return this.data.length>0}get volumes(){return this.data}handleStorageAvailability(t){this._models.data.filter(s=>!t.find(r=>r.id===s.id)).forEach(s=>{this.removeModel(s.id)}),t.forEach(s=>{const r=this.getModel(s.id);if(r){const o={...s,kosParentId:this.id};r.updateModel(o)}else{const o={...s,kosParentId:this.id},n=Hr.instance(s.id).options(o).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await Md()).forEach(e=>{if(e.deviceType!=="disk"){const s={...e,kosParentId:this.id},r=Hr.instance(e.id).options(s).build();this.addModel(r)}})}};fi([De],Ls.prototype,"_models",2);fi([B({topic:vE,websocket:!0})],Ls.prototype,"handleStorageAvailability",1);Ls=fi([R(_d)],Ls);const Ut=new Se({class:Ls,type:_d});Ut.addRelatedModel(Hr);const{URL:pi}=ce(),{getAll:wE,postModel:EE}=oe.build({basePath:`${pi}/api/kos/update/available`}),ga=m.createLogger({name:"usb-update-service",group:"Services"}),Sd=async()=>{ga.debug("sending GET for usb-update");const t=await wE({urlOverride:`${pi}/api/kos/update/available`});return!(t!=null&&t.data)||(t==null?void 0:t.status)!==200?(ga.error("Failed to retrieve usb-update data",t),[]):t.data},Od=async(t,e,s)=>{const r=await EE({model:{manifestId:t,deviceId:e},tracker:s,urlOverride:`${pi}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},ME=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:Sd,installUpdate:Od},Symbol.toStringTag,{value:"Module"}));var TE=Object.defineProperty,_E=Object.getOwnPropertyDescriptor,Id=(t,e,s,r)=>{for(var o=r>1?void 0:r?_E(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&TE(e,s,o),o};const $d="usb-update-model";let Kr=class{constructor(t,e,s){l(this,"id");l(this,"active");l(this,"blocked");l(this,"createTime");l(this,"deviceId");l(this,"manifestId");l(this,"notes");l(this,"futureHandler");l(this,"logger");this.id=t,this.logger=s.logger,this.active=e.active,this.blocked=e.blocked,this.createTime=e.createTime,this.deviceId=e.deviceId,this.manifestId=e.manifestId,this.notes=e.notes,this.futureHandler=new Xr(this)}updateModel(t){this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(t){if(!t)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),Od(this.manifestId,this.deviceId,t)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};Id([wi()],Kr.prototype,"install",1);Kr=Id([R($d)],Kr);const gi=new ve({class:Kr,type:$d});var SE=Object.defineProperty,OE=Object.getOwnPropertyDescriptor,fo=(t,e,s,r)=>{for(var o=r>1?void 0:r?OE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&SE(e,s,o),o};const Cd="usb-update-container-model";let jt=class{constructor(t,e,s){l(this,"id");l(this,"disposer");l(this,"storageService");l(this,"_activeUpdate");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new xe({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(t){this._activeUpdate=t}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const t=await Sd();X(()=>{const e=t.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!e.includes(s.id)).forEach(s=>this.removeModel(s.id)),t.forEach(s=>{const r=`${s.deviceId}-${s.manifestId}`,o=gi.instance(r).forceUpdate.options({...s,createTime:new Date(s.createTime)}).build();this.addModel(o)}),this.data.length===1?this.updateActiveUpdate(this.data[0]):this.clearActiveUpdate()})}usbInsertedEffect(){this.isUsbInserted?this.syncAvailableUpdates():(this._models.clear(),this.clearActiveUpdate())}async init(){this.logger.debug(`initializing usb-update-container container ${this.id}`)}unload(){var t;(t=this.disposer)==null||t.call(this)}async activate(){this.logger.debug(`activating usb-update-container container ${this.id}`),await this.syncAvailableUpdates()}async load(){this.logger.debug(`loading usb-update-container container ${this.id}`)}};fo([Ht({modelType:Ut.type})],jt.prototype,"storageService",2);fo([De],jt.prototype,"_models",2);fo([Rc({dependencies:t=>[t.isUsbInserted]})],jt.prototype,"usbInsertedEffect",1);jt=fo([R(Cd)],jt);const Fs=new Se({class:jt,type:Cd});Fs.addRelatedModel(gi);const IE=()=>({...{[zt.type]:{class:eu},[Ye.type]:{class:iu,singleton:!0},...re.registration,...ft.registration,...Lt.registration,...Rr.registration,...Ue.registration,[ai.type]:{class:exports.WsEventModel,singleton:!0},...Ps.registration,...ni.registration,..._r.registration}}),mi=IE(),$E={models:mi,preloadModels:[]},ma=!0,Dd=t=>()=>{const e=mi;return Kc(Qo)(Rs).model(Lt).model(Ut).model(Fs).model(jr).model(Cr).model(Os).model(Dr).model(Yn).model(ks).model(Nt).model(li).model(yu).model(zn,ma).model(Gs).model(wu,ma),Object.keys(e).forEach(s=>{const r=e[s];Hc(Qo)(s,r)}),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t)}},Te={};Te.core={models:Dd(Te)};Te.preload=A.model.preloadModel(Te);Te.model=A.model.register(Te);Te.companion=A.companion.register(Te);Te.legacy=A.model.registerLegacyModel(Te);const Qo=Te;class CE{registerTroubleRankMapper(e){return $.propertyMapper.registerPropertyMapper(Ee.TroubleRank,e),this}registerTroubleRoleMapper(e){return $.propertyMapper.registerPropertyMapper(Ee.TroubleRole,e),this}registerTroubleColorMapper(e){return $.propertyMapper.registerPropertyMapper(Ee.TroubleColor,e),this}registerModelLoader(e,s){$.loader.registerLoader(e,s)}registerCanvasPatternLoader(e){$.loader.registerLoader(Nt.loader,e)}}const DE=async(t,e)=>{const s=Yn.instance(t).options({}).build(),r=e?`${e}-`:"";return await fe(s),{getState:o=>s.data[`${r}${o}`],updateState:async(o,n)=>{await s.updateState(`${r}${o}`,n)},clean:async()=>{for(const o of s.data.keys)await s.updateState(`${r}${o}`,void 0)},unsubscribe:()=>{Oe(s)}}},xd="kos:service:region",Ad="regionId",xE=`${xd}-${Ad}`,Rd=async t=>{const e=ft.factory(xE)({path:xd,attribute:Ad});await fe(e),e.updateProperty(t)};function AE(t){return ht(t)}const ya=Be(),RE=Object.freeze(Object.defineProperty({__proto__:null,api:ya,default:ya,kosServiceRequest:AE},Symbol.toStringTag,{value:"Module"}));function PE(t){return ht(t)}const ba=Be(),kE=Object.freeze(Object.defineProperty({__proto__:null,api:ba,default:ba,kosServiceRequest:PE},Symbol.toStringTag,{value:"Module"}));function LE(t){return ht(t)}const va=Be(),FE=Object.freeze(Object.defineProperty({__proto__:null,api:va,default:va,kosServiceRequest:LE},Symbol.toStringTag,{value:"Module"}));function NE(t){return ht(t)}const wa=Be(),UE=Object.freeze(Object.defineProperty({__proto__:null,api:wa,default:wa,kosServiceRequest:NE},Symbol.toStringTag,{value:"Module"}));function jE(t){return ht(t)}const Ea=Be(),BE=Object.freeze(Object.defineProperty({__proto__:null,api:Ea,default:Ea,kosServiceRequest:jE},Symbol.toStringTag,{value:"Module"}));function HE(t){return ht(t)}const Ma=Be(),KE=Object.freeze(Object.defineProperty({__proto__:null,api:Ma,default:Ma,kosServiceRequest:HE},Symbol.toStringTag,{value:"Module"})),yi="/kos-timer-event",bi="/kos-timer-event/tick",vi="defaultTimerEnd",ds=m.createLogger({name:"timer-manager"}),qE=t=>t.updateProperty!==void 0;class Pd{constructor(e,s,r){l(this,"name");l(this,"timeout");l(this,"timer");l(this,"state","inactive");l(this,"decrementValue",1);l(this,"remainingTime");l(this,"timeoutActions",new Map);this.name=e;const o=typeof s=="number"?s:s.value||60;this.timeout=o,this.state="inactive",this.remainingTime=o,qE(s)&&Y(()=>{m.info(`Updating config value timer ${e} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:vi}),r&&r.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){ds.debug(`Timer ${this.name} already started`);return}(this.state==="inactive"||this.state==="paused")&&(this.state="active",this.timer=setInterval(()=>this.updateTimer(),1e3))}pause(){this.timer&&(ds.debug(`Pausing timer ${this.name}`),this.state="paused",clearInterval(this.timer))}restart(){this.pause(),this.remainingTime=this.timeout,this.start()}reset(){this.pause(),this.remainingTime=this.timeout,this.state="inactive"}updateTimeout(e){this.timeout=e,this.restart()}addTimeoutAction(e){const s=e.remainingTime??0;this.timeoutActions.has(s)||this.timeoutActions.set(s,[]);const r=e.name,o=this.timeoutActions.get(s).find(n=>n.name===r);o?o.action=e.action:this.timeoutActions.get(s).push(e)}removeTimeoutAction(e){for(const[s,r]of this.timeoutActions.entries()){const o=r.filter(n=>n.name!==e);o.length===0?this.timeoutActions.delete(s):this.timeoutActions.set(s,o)}}updateTimer(){if(this.remainingTime=Math.round((this.remainingTime-this.decrementValue)*100)/100,this.remainingTime<=0){this.state==="active"&&this.executeActions(0),this.pause();return}this.state==="active"&&this.executeActions(this.remainingTime)}executeActions(e){this.timeoutActions.has(e)&&this.timeoutActions.get(e).forEach(s=>{var r;ds.debug(`Executing timer action ${s.name} at ${e}`),(r=s.action)==null||r.call(s,s.name,e),this.notifyTimeoutAction(s),s.singleUse&&(ds.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){q(`${bi}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(e){q(yi,{name:this.name,action:e.name,remainingTime:this.remainingTime})}}const hs=new Map,Mt=(t,e)=>{const s=hs.get(t);if(!s){ds.error(`Timer ${t} not found`);return}e(s)},kd={createRelativeTimer(t,e,s){const r=new Date,o=Math.round((e.getTime()-r.getTime())/1e3);return this.createTimer(t,o,s)},createTimer(t,e=60,s){if(hs.has(t))return hs.get(t);const r=new Pd(t,e,s);return hs.set(t,r),r},getTimer(t){return hs.get(t)},clearTimer(t){Mt(t,e=>e.pause())},restartTimer(t){Mt(t,e=>e.restart())},resetTimer(t){Mt(t,e=>e.reset())},addTimeoutAction(t,e){Mt(t,s=>s.addTimeoutAction(e))},removeTimeoutAction(t,e){Mt(t,s=>s.removeTimeoutAction(e))},startTimer(t){Mt(t,e=>e.start())}},Ld="kos:service:region:settings",Fd="timeZone",zE=`${Ld}-${Fd}`,Zo=async t=>{const e=ft.factory(zE)({path:Ld,attribute:Fd});await fe(e),e.updateProperty(t)},VE=t=>!t||!t.data;function wi(t={}){const{alias:e,namespace:s,abortController:r=!1,trackerPolicy:o="id"}=t;return(n,i,a)=>{n[gs]=n[gs]||{},e&&(n[bs]=n[bs]||new Map,n[bs].set(i,e));const c=a.value,u=async function(...d){const h=ut();m.debug(`Calling future service ${i} with tracker ${h}`);let f,p;r&&(f=new AbortController);const y=ct.initiateFuture({tracker:h,id:kn});s&&(y.namespace=s),m.debug(`waiting for future ${y.id} to be ready`),await fe(y),m.debug(`future ${y.id} is ready`),X(()=>{m.debug(`Adding future ${y.id} to futureHandler`),this.futureHandler.addFuture(y,e)}),r&&f&&(p=Y(()=>{(y.status==="CANCELLED"||y.endState===Ge.Canceled)&&(m.debug(`Future ${y.id} cancelled, aborting request`),f==null||f.abort())}),f.signal.addEventListener("abort",async()=>{if(y.status!=="CANCELLED"&&y.endState!==Ge.Canceled&&!y.endState){m.debug(`AbortController aborted, cancelling future ${y.id}`);try{await y.cancelFuture()}catch(E){m.error(`Failed to cancel future ${y.id}:`,E)}}},{once:!0}));const w=()=>{p&&(p(),p=void 0)};try{const E=[...d];if(r&&f){const U=E[E.length-1];U&&typeof U=="object"&&"aborted"in U?E[E.length-1]=f.signal:E.push(f.signal)}if(o==="context"){const U=E[E.length-1];if(_n(U))U.$tracker=h;else{const I={[Qr]:!0,$tracker:h};E.push(I)}}else E.push(h);const _=await c.apply(this,E);m.debug(`received future response for ${h}`,_);const L=VE(_)?_:_==null?void 0:_.data;return L?(L.progress=1,m.debug("mapping future response to future model"),y.endState?m.debug(`future ${y.id} has already completed. Not updating the model`):Kn(L,y)):this.futureHandler.removeFuture(e),w(),L}catch(E){if(w(),r&&(f!=null&&f.signal.aborted)){const _=new Error("Operation cancelled");throw m.debug(`Operation ${i} was cancelled`),_}throw m.error(E),E}};n[gs][i]={handler:u}}}const GE=({path:t})=>(e,s)=>{e[F]=e[F]||{},e[F][s]={modelType:Ps.type,id:`${Ps.type}-${t}`,options:{path:t},lifecycle:x.INIT}};function YE(t){const{path:e,attribute:s}=t;return(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:ni.type,id:`${e}-${s}`,options:{path:e,attribute:s},lifecycle:x.INIT}}}const It=m.createLogger({name:"services",group:"Services"}),WE=async(t,e)=>Nd(t,e,`${exports.BASE_URL}/api/server/login`),Nd=async(t,e,s=`${exports.BASE_URL}/api/login`)=>{const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:t,password:e})});if(!r.ok){const n=await r.json();throw Error(`${n==null?void 0:n.error}`)}return await r.json()},QE=async t=>Ud(t,`${exports.BASE_URL}/api/server/startPasswordReset`,""),Ud=async(t,e=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const r=await exports.kosFetch(`${e}?email=${t}`,{method:"POST",destinationAddress:s});if(!r.ok)throw Error(`There was a problem reseting config; returned status ${r.status}`);return await r.json()},ZE=async(t,e)=>jd(t,e,`${exports.BASE_URL}/api/server/resetPassword`),jd=async(t,e,s=`${exports.BASE_URL}/api/resetPassword`)=>{It.debug(`resetting password with token ${t} and password ${e.replace(/./g,"*")}`);const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e})});if(It.debug(`password reset returned status ${r.status}`),!r.ok){It.error(`password reset failed with message ${r.statusText}`);const n=await r.json();throw Error(`${n==null?void 0:n.error}:There was a problem resetting the password.`)}return await r.json()},XE=async(t,e,s)=>Bd(t,e,s,`${exports.BASE_URL}/api/server/acceptInvite`),Bd=async(t,e,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{It.debug(`accepting invite with token ${t} and password ${e.replace(/./g,"*")}`);const o=await exports.kosFetch(`${r}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e,name:s})});if(It.debug(`invitation accept returned status ${o.status}`),!o.ok){It.error(`invite failed with message ${o.statusText}`);const i=await o.json();throw Error(`${i==null?void 0:i.error}:There was a problem accepting the invite.`)}return await o.json()};function JE(t,e,s,r){const o=t instanceof Promise?{promise:t,abortController:e,cancelFuture:s,future:r}:t,{promise:n,abortController:i,cancelFuture:a,future:c}=o,u=n;let d=0,h="PENDING",f=!0;const p=new Set;let y;return c&&typeof c=="object"&&(y=M.autorun(()=>{const w=c.progress||0,E=c.status||"PENDING",_=!c.endState;(w!==d||E!==h||_!==f)&&(d=w,h=E,f=_,p.forEach(L=>{try{L(d,h)}catch(U){console.warn("Progress callback error:",U)}}))})),n.finally(()=>{f=!1,i!=null&&i.signal.aborted||(h="COMPLETED",p.forEach(w=>{try{w(d,h)}catch(E){console.warn("Progress callback error:",E)}})),y&&y(),p.clear()}),u.cancel=async()=>{i&&!i.signal.aborted&&i.abort(),a&&await a(),f=!1,h="CANCELLED",p.forEach(w=>{try{w(d,h)}catch(E){console.warn("Progress callback error:",E)}}),y&&y()},u.getController=()=>i,u.isCancelled=()=>(i==null?void 0:i.signal.aborted)??!1,Object.defineProperty(u,"progress",{get:()=>d,enumerable:!0}),Object.defineProperty(u,"status",{get:()=>h,enumerable:!0}),Object.defineProperty(u,"isRunning",{get:()=>f,enumerable:!0}),u.onProgressUpdate=w=>(p.add(w),w(d,h),()=>p.delete(w)),u}const eM=st.keyframes`
146
146
  0% {
147
147
  left: -90px;
148
148
  color: #eee;
@@ -154,7 +154,7 @@ ${u}topics:${e}
154
154
  left: 90px;
155
155
  color: #eee;
156
156
  }
157
- `,tM=tt.css`
157
+ `,tM=st.css`
158
158
  font-size: 100px;
159
159
  margin-top: -80px;
160
160
  position: relative;
@@ -174,31 +174,31 @@ ${u}topics:${e}
174
174
  left: 0;
175
175
  color: ${({theme:t})=>t==="light"?"black":"white"};
176
176
  z-index: 10000;
177
- `;class Kd extends g.Component{constructor(e){super(e),this.state={error:null,errorInfo:null}}componentDidCatch(e,s){this.setState({error:e,errorInfo:s})}render(){return this.state.errorInfo?this.props.fallback||T.jsxs("div",{children:[T.jsx("h2",{children:"Something went wrong."}),T.jsxs("details",{style:{whiteSpace:"pre-wrap"},children:[this.state.error&&this.state.error.toString(),T.jsx("br",{}),this.state.errorInfo.componentStack]})]}):this.props.children}}const oM={normal:"#B5F7F6",warn:"#F3D78A",error:"#FC8486"},nM=({value:t=0,title:e,status:s="normal",subtitle:r})=>{const o=tt.css`
177
+ `;class Kd extends g.Component{constructor(e){super(e),this.state={error:null,errorInfo:null}}componentDidCatch(e,s){this.setState({error:e,errorInfo:s})}render(){return this.state.errorInfo?this.props.fallback||T.jsxs("div",{children:[T.jsx("h2",{children:"Something went wrong."}),T.jsxs("details",{style:{whiteSpace:"pre-wrap"},children:[this.state.error&&this.state.error.toString(),T.jsx("br",{}),this.state.errorInfo.componentStack]})]}):this.props.children}}const oM={normal:"#B5F7F6",warn:"#F3D78A",error:"#FC8486"},nM=({value:t=0,title:e,status:s="normal",subtitle:r})=>{const o=st.css`
178
178
  display: flex;
179
179
  flex-direction: column;
180
- `,n=tt.css`
180
+ `,n=st.css`
181
181
  position: relative;
182
182
  height: 18px;
183
183
  width: 100%;
184
184
  background-color: #ddd;
185
185
  border-radius: 5px;
186
186
  overflow: hidden;
187
- `,i=tt.css`
187
+ `,i=st.css`
188
188
  position: absolute;
189
189
  top: 50%; /* position the top edge of the element at the middle of the parent */
190
190
  left: 50%; /* position the left edge of the element at the middle of the parent */
191
191
  z-index: 5;
192
192
  transform: translate(-50%, -50%);
193
193
  font-size: smaller;
194
- `,a=tt.css`
194
+ `,a=st.css`
195
195
  width: ${t}%;
196
196
  height: 35px;
197
197
  background-color: ${oM[s]};
198
198
  text-align: center;
199
199
  line-height: 32px;
200
200
  color: black;
201
- `,c=tt.css`
201
+ `,c=st.css`
202
202
  animation: indeterminateAnimation 1s infinite linear;
203
203
  transform-origin: 0% 50%;
204
204
  @keyframes indeterminateAnimation {
@@ -212,7 +212,7 @@ ${u}topics:${e}
212
212
  transform: translateX(100%) scaleX(0.5);
213
213
  }
214
214
  }
215
- `;return T.jsxs("div",{css:o,children:[T.jsxs("div",{css:n,children:[T.jsx("div",{css:i,children:e}),T.jsx("div",{css:[a,t<0?c:""]})]}),T.jsx("div",{children:r})]})},iM={setModel:()=>!1},po=g.createContext(iM),aM=()=>{const t=g.useContext(po);if(t==null)throw new Error("useModels must be used within a KosModelProvider");return t.model},qd=({children:t})=>{const[e,s]=g.useState(),r=g.useCallback(o=>(s(o),!0),[s]);return T.jsx(po.Provider,{value:{model:e,setModel:r},children:t})},zd=m.createLogger({name:"kos-model-hierarchy-context"}),cM={models:[],addModel:()=>{zd.debug("Default implementation being used. Do Nothing.")}},go=g.createContext(cM),lM=({children:t})=>{const[e,s]=g.useState([]),r=g.useCallback(o=>{e.includes(o)||(zd.debug("adding to hierarchy context",o.id),s(n=>[...n,o]))},[e]);return T.jsx(go.Provider,{value:{models:e,addModel:r},children:t})},uM=()=>!0,Vd=t=>{const e=g.useContext(go);if(!e)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(t==null?void 0:t.filter)||uM;return g.useMemo(()=>e.models.filter(s),[e.models,s])},dM=t=>Vd({filter:s=>{const r=$e(s.id);return(r==null?void 0:r.type)===t}})[0],hM=m.createLogger({name:"kos-model-loader"}),fM=()=>T.jsx("div",{}),Gd=({fallback:t,children:e,...s})=>T.jsx(qd,{children:T.jsx(Kd,{fallback:t,children:T.jsx(g.Suspense,{children:T.jsx(Yd,{...s,children:e})})})}),Yd=t=>{const[e,s]=g.useState(),[r,o]=g.useState(!1),{setModel:n}=g.useContext(po),i=g.useContext(go);if(g.useEffect(()=>{t.model&&(s(t.model),n(t.model),o(!0),i&&i.addModel(t.model))},[i,t.model,n]),t.error)throw hM.error(t.error),new Error(t.error);const a=t.loading||T.jsx(fM,{});return T.jsx(T.Fragment,{children:e&&r?t.children:a})},pr={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},Wd=g.createContext(pr),pM=({translations:t=pr,children:e})=>{const s={header:{...pr.header,...t.header},createModal:{...pr.createModal,...t.createModal}};return T.jsx(Wd.Provider,{value:s,children:e})};function gM(t,e){const s=O.create(t,!1,e),r=s.whenReady().then(()=>s);return hn(r)}const Qd=g.createContext(void 0),mM=(t={models:{},preloadModels:[]},e)=>{const s=gM(t,e),r=({children:o})=>{const n=s.read(),[i,a]=g.useState(n.isOnline);return g.useEffect(()=>{const c=G(()=>{a(n.isOnline)});return()=>{c()}},[n]),T.jsx(Qd.Provider,{value:{kosCore:n,online:i},children:o})};return{KosCoreContextProvider:sn.observer(r)}},Zd=()=>{const t=g.useContext(Qd);if(t===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return t},yM=8,bM=(t=0)=>new Promise(e=>{setTimeout(()=>{e(!0)},2**t*10)}),rt=new Map;function vM(t,e){if(rt.has(t)){const s=rt.get(t);if(s.status==="finished"){const r=O.getInstance().modelManager.getModelById(t);return{kosModel:r,model:r==null?void 0:r.modelData}}else throw s.promise}else{const s=e().then(()=>{rt.set(t,{status:"finished",key:t})},o=>{throw rt.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw rt.set(t,r),s}}function wM(t,e){return vM(t,e)}async function EM(t,e){const{modelId:s,factory:r,modelType:o,options:n,activate:i}=e;let a=0;await t.whenReady();let c;if(n){const d=typeof o=="string"?t.modelManager.getModelFactory(o):r;if(!d)throw Error("No Factory Specified. Cannot create a new instance");c=d.build(s,n)}const u=t.modelManager.getModelById(s);if(!u){if(a>yM)throw Error(`KOS Model ${s} has not been found`);await bM(a),a=a+1}return await(u==null?void 0:u.whenReady()),u?(c=u.modelData,{kosModel:u,model:c}):{kosModel:void 0,model:void 0}}const Q=t=>{const{modelId:e,modelType:s,activate:r,destroyOnUnmount:o}=t,n=Zd(),[i,a]=g.useState(!1),[c,u]=g.useState(),{kosModel:d,model:h}=wM(e||s||"",()=>EM(n.kosCore,t));return g.useEffect(()=>{t.forceUpdate&&h&&On(h)&&h.updateModel(t.options||{})},[h]),g.useEffect(()=>{async function f(){try{return await n.kosCore.whenReady(),r&&await(d==null?void 0:d.fsm.transitionTo(k.GO_ACTIVE,v.ACTIVE)),a(!0),d}catch(y){throw u(y.message),y}}let p;return n.kosCore&&e&&f().then(y=>{p=G(()=>{const w=(y==null?void 0:y.status)===v.READY;a(w)})}).catch(y=>{console.error(y)}),()=>{if(r){if(h!=null&&h.id){const y=n.kosCore.modelManager.getModelById(h.id);y==null||y.fsm.transitionTo(k.GO_INACTIVE,v.INACTIVE).then(()=>{if(o){const w=h.id;Oe(h).then(()=>{rt.delete(w),p==null||p()})}})}}else o&&h&&Oe(h).then(()=>{rt.delete(e),p==null||p()})}},[r,o,n.kosCore,d,h,e]),{model:h,ready:i,error:c,status:{model:h,ready:i,error:c},KosModelLoader:Gd}},Ei=()=>{const t=_r.type;return Q({modelId:t,modelType:_r.type,options:{}})},Mi=g.createContext(void 0),MM=({children:t})=>{const{model:e,ready:s}=Ei(),r=g.useMemo(()=>s&&e?{model:e}:{},[s,e]);return T.jsx(Mi.Provider,{value:r,children:t})},TM=()=>{const t=g.useContext(Mi);if(!t)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return t},Ti=()=>{const t=Dr.type;return Q({modelId:t,modelType:Dr.type,options:{}})};function _M(t){return()=>e=>{const{model:s,status:r,KosModelLoader:o}=Ti();return T.jsx(o,{...r,children:T.jsx(t,{...e,softwareInfo:s})})}}const _i=g.createContext(void 0),SM=({children:t})=>{const{model:e,ready:s}=Ti(),r=g.useMemo(()=>s&&e?{model:e}:{},[s,e]);return T.jsx(_i.Provider,{value:r,children:t})},OM=()=>{const t=g.useContext(_i);if(!t)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return t},Xd=new Cl,Jd=g.createContext(Xd);function IM({children:t}){return T.jsx(Jd.Provider,{value:Xd,children:t})}const Si=g.createContext(void 0),$M=()=>{const t=window.location.origin,e=be();return(e==null?void 0:e.host)||t},CM=({children:t,appContext:e,locale:s="en",resolver:r,rootUrl:o,descriptorResolver:n})=>{const[i,a]=g.useState(!1),[c,u]=g.useState(),[d,h]=g.useState(),f=o||$M(),p=g.useMemo(()=>e??"app/system",[e]);g.useEffect(()=>{async function E(){const L=(Array.isArray(p)?p:[p]).map(Z=>(n||Xu(Z))()),S=(await Promise.allSettled(L)).map(Z=>{if(Z.status==="rejected"){m.warn("Failed to load localization descriptor",Z.reason);return}return Z.value}).filter(Z=>!!Z).reverse().reduce((Z,Y)=>{const le=Y.path;return Object.keys(Y.namespaces).forEach(Zt=>{const Xt=Y.namespaces[Zt];Xt.basePath=le}),{...Z,namespaces:{...Z.namespaces,...Y.namespaces}}},{});u(S)}E()},[p,n]),g.useEffect(()=>{async function E(){if(c){const _=f,{translations:L}=await rd.init({lang:s,descriptor:c,defaultNamespace:"common",resolver:r,rootUrl:_});h(L),a(!0)}}E()},[s,c,r,f]);const y=g.useMemo(()=>i?{setLocale:E=>{d&&(d.currentLocale=E)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,d]),w=i?t:null;return T.jsx(Si.Provider,{value:y,children:w})},DM=()=>{const t=g.useContext(Si);if(!t)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return t},xM=()=>{const t=Nt.type;return Q({modelId:t,modelType:Nt.type,options:{}})};function AM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=xM();return T.jsx(o,{...r,children:T.jsx(t,{...e,canvasDispatcher:s})})}}const RM=(t,e,s)=>{const r=atob(t),o=new Uint8ClampedArray(e*s*4);for(let n=0,i=0;n<r.length&&i<o.length;n+=3,i+=4)o[i]=r.charCodeAt(n),o[i+1]=r.charCodeAt(n+1),o[i+2]=r.charCodeAt(n+2),o[i+3]=255;return o};function PM({ctx:t,format:e,dataString:s,width:r,height:o,pixelSize:n}){const i=RM(s,r,o),a=new ImageData(i,r,o),c=document.createElement("canvas");c.width=r,c.height=o;const u=c.getContext("2d");u==null||u.putImageData(a,0,0),t.imageSmoothingEnabled=!1,t.clearRect(0,0,r*n,o*n),t.drawImage(c,0,0,r*n,o*n)}const kM=m.createLogger({name:"canvas-streamer"});kM.debug("main-view component loaded");const xo=10,eh=sn.observer(({canvasDispatcher:t,height:e=30,width:s=50,defaultFps:r=10,showPreview:o=!1,name:n,apiPath:i="/api/system/canvas"})=>{const a=g.useRef(null),[c,u]=g.useState();g.useEffect(()=>{const h=t.addNamedEndpoint(n,{apiPath:i,fps:r,width:s,height:e,id:n});u(h)},[t]);const d=g.useCallback(h=>{if(a.current&&o){const f=a.current.getContext("2d");f&&PM({ctx:f,format:"base64",dataString:h,height:e,width:s,pixelSize:xo})}},[s,e,o]);return g.useEffect(()=>{c&&(c.onFrame=d,c.width=s,c.height=e,c.fps=r)},[c,d,s,e,r]),o&&Oa.createPortal(T.jsx(FM,{children:T.jsx(NM,{children:T.jsx("canvas",{ref:a,width:s*xo,height:e*xo,style:{border:"1px solid black"}})})}),document.body)}),LM=AM(eh),FM=tn.div`
215
+ `;return T.jsxs("div",{css:o,children:[T.jsxs("div",{css:n,children:[T.jsx("div",{css:i,children:e}),T.jsx("div",{css:[a,t<0?c:""]})]}),T.jsx("div",{children:r})]})},iM={setModel:()=>!1},po=g.createContext(iM),aM=()=>{const t=g.useContext(po);if(t==null)throw new Error("useModels must be used within a KosModelProvider");return t.model},qd=({children:t})=>{const[e,s]=g.useState(),r=g.useCallback(o=>(s(o),!0),[s]);return T.jsx(po.Provider,{value:{model:e,setModel:r},children:t})},zd=m.createLogger({name:"kos-model-hierarchy-context"}),cM={models:[],addModel:()=>{zd.debug("Default implementation being used. Do Nothing.")}},go=g.createContext(cM),lM=({children:t})=>{const[e,s]=g.useState([]),r=g.useCallback(o=>{e.includes(o)||(zd.debug("adding to hierarchy context",o.id),s(n=>[...n,o]))},[e]);return T.jsx(go.Provider,{value:{models:e,addModel:r},children:t})},uM=()=>!0,Vd=t=>{const e=g.useContext(go);if(!e)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(t==null?void 0:t.filter)||uM;return g.useMemo(()=>e.models.filter(s),[e.models,s])},dM=t=>Vd({filter:s=>{const r=$e(s.id);return(r==null?void 0:r.type)===t}})[0],hM=m.createLogger({name:"kos-model-loader"}),fM=()=>T.jsx("div",{}),Gd=({fallback:t,children:e,...s})=>T.jsx(qd,{children:T.jsx(Kd,{fallback:t,children:T.jsx(g.Suspense,{children:T.jsx(Yd,{...s,children:e})})})}),Yd=t=>{const[e,s]=g.useState(),[r,o]=g.useState(!1),{setModel:n}=g.useContext(po),i=g.useContext(go);if(g.useEffect(()=>{t.model&&(s(t.model),n(t.model),o(!0),i&&i.addModel(t.model))},[i,t.model,n]),t.error)throw hM.error(t.error),new Error(t.error);const a=t.loading||T.jsx(fM,{});return T.jsx(T.Fragment,{children:e&&r?t.children:a})},pr={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},Wd=g.createContext(pr),pM=({translations:t=pr,children:e})=>{const s={header:{...pr.header,...t.header},createModal:{...pr.createModal,...t.createModal}};return T.jsx(Wd.Provider,{value:s,children:e})};function gM(t,e){const s=O.create(t,!1,e),r=s.whenReady().then(()=>s);return hn(r)}const Qd=g.createContext(void 0),mM=(t={models:{},preloadModels:[]},e)=>{const s=gM(t,e),r=({children:o})=>{const n=s.read(),[i,a]=g.useState(n.isOnline);return g.useEffect(()=>{const c=Y(()=>{a(n.isOnline)});return()=>{c()}},[n]),T.jsx(Qd.Provider,{value:{kosCore:n,online:i},children:o})};return{KosCoreContextProvider:sn.observer(r)}},Zd=()=>{const t=g.useContext(Qd);if(t===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return t},yM=8,bM=(t=0)=>new Promise(e=>{setTimeout(()=>{e(!0)},2**t*10)}),ot=new Map;function vM(t,e){if(ot.has(t)){const s=ot.get(t);if(s.status==="finished"){const r=O.getInstance().modelManager.getModelById(t);return{kosModel:r,model:r==null?void 0:r.modelData}}else throw s.promise}else{const s=e().then(()=>{ot.set(t,{status:"finished",key:t})},o=>{throw ot.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw ot.set(t,r),s}}function wM(t,e){return vM(t,e)}async function EM(t,e){const{modelId:s,factory:r,modelType:o,options:n,activate:i}=e;let a=0;await t.whenReady();let c;if(n){const d=typeof o=="string"?t.modelManager.getModelFactory(o):r;if(!d)throw Error("No Factory Specified. Cannot create a new instance");c=d.build(s,n)}const u=t.modelManager.getModelById(s);if(!u){if(a>yM)throw Error(`KOS Model ${s} has not been found`);await bM(a),a=a+1}return await(u==null?void 0:u.whenReady()),u?(c=u.modelData,{kosModel:u,model:c}):{kosModel:void 0,model:void 0}}const Q=t=>{const{modelId:e,modelType:s,activate:r,destroyOnUnmount:o}=t,n=Zd(),[i,a]=g.useState(!1),[c,u]=g.useState(),{kosModel:d,model:h}=wM(e||s||"",()=>EM(n.kosCore,t));return g.useEffect(()=>{t.forceUpdate&&h&&On(h)&&h.updateModel(t.options||{})},[h]),g.useEffect(()=>{async function f(){try{return await n.kosCore.whenReady(),r&&await(d==null?void 0:d.fsm.transitionTo(k.GO_ACTIVE,v.ACTIVE)),a(!0),d}catch(y){throw u(y.message),y}}let p;return n.kosCore&&e&&f().then(y=>{p=Y(()=>{const w=(y==null?void 0:y.status)===v.READY;a(w)})}).catch(y=>{console.error(y)}),()=>{if(r){if(h!=null&&h.id){const y=n.kosCore.modelManager.getModelById(h.id);y==null||y.fsm.transitionTo(k.GO_INACTIVE,v.INACTIVE).then(()=>{if(o){const w=h.id;Oe(h).then(()=>{ot.delete(w),p==null||p()})}})}}else o&&h&&Oe(h).then(()=>{ot.delete(e),p==null||p()})}},[r,o,n.kosCore,d,h,e]),{model:h,ready:i,error:c,status:{model:h,ready:i,error:c},KosModelLoader:Gd}},Ei=()=>{const t=_r.type;return Q({modelId:t,modelType:_r.type,options:{}})},Mi=g.createContext(void 0),MM=({children:t})=>{const{model:e,ready:s}=Ei(),r=g.useMemo(()=>s&&e?{model:e}:{},[s,e]);return T.jsx(Mi.Provider,{value:r,children:t})},TM=()=>{const t=g.useContext(Mi);if(!t)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return t},Ti=()=>{const t=Dr.type;return Q({modelId:t,modelType:Dr.type,options:{}})};function _M(t){return()=>e=>{const{model:s,status:r,KosModelLoader:o}=Ti();return T.jsx(o,{...r,children:T.jsx(t,{...e,softwareInfo:s})})}}const _i=g.createContext(void 0),SM=({children:t})=>{const{model:e,ready:s}=Ti(),r=g.useMemo(()=>s&&e?{model:e}:{},[s,e]);return T.jsx(_i.Provider,{value:r,children:t})},OM=()=>{const t=g.useContext(_i);if(!t)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return t},Xd=new Cl,Jd=g.createContext(Xd);function IM({children:t}){return T.jsx(Jd.Provider,{value:Xd,children:t})}const Si=g.createContext(void 0),$M=()=>{const t=window.location.origin,e=be();return(e==null?void 0:e.host)||t},CM=({children:t,appContext:e,locale:s="en",resolver:r,rootUrl:o,descriptorResolver:n})=>{const[i,a]=g.useState(!1),[c,u]=g.useState(),[d,h]=g.useState(),f=o||$M(),p=g.useMemo(()=>e??"app/system",[e]);g.useEffect(()=>{async function E(){const L=(Array.isArray(p)?p:[p]).map(Z=>(n||Xu(Z))()),S=(await Promise.allSettled(L)).map(Z=>{if(Z.status==="rejected"){m.warn("Failed to load localization descriptor",Z.reason);return}return Z.value}).filter(Z=>!!Z).reverse().reduce((Z,W)=>{const le=W.path;return Object.keys(W.namespaces).forEach(Zt=>{const Xt=W.namespaces[Zt];Xt.basePath=le}),{...Z,namespaces:{...Z.namespaces,...W.namespaces}}},{});u(S)}E()},[p,n]),g.useEffect(()=>{async function E(){if(c){const _=f,{translations:L}=await rd.init({lang:s,descriptor:c,defaultNamespace:"common",resolver:r,rootUrl:_});h(L),a(!0)}}E()},[s,c,r,f]);const y=g.useMemo(()=>i?{setLocale:E=>{d&&(d.currentLocale=E)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,d]),w=i?t:null;return T.jsx(Si.Provider,{value:y,children:w})},DM=()=>{const t=g.useContext(Si);if(!t)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return t},xM=()=>{const t=Nt.type;return Q({modelId:t,modelType:Nt.type,options:{}})};function AM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=xM();return T.jsx(o,{...r,children:T.jsx(t,{...e,canvasDispatcher:s})})}}const RM=(t,e,s)=>{const r=atob(t),o=new Uint8ClampedArray(e*s*4);for(let n=0,i=0;n<r.length&&i<o.length;n+=3,i+=4)o[i]=r.charCodeAt(n),o[i+1]=r.charCodeAt(n+1),o[i+2]=r.charCodeAt(n+2),o[i+3]=255;return o};function PM({ctx:t,format:e,dataString:s,width:r,height:o,pixelSize:n}){const i=RM(s,r,o),a=new ImageData(i,r,o),c=document.createElement("canvas");c.width=r,c.height=o;const u=c.getContext("2d");u==null||u.putImageData(a,0,0),t.imageSmoothingEnabled=!1,t.clearRect(0,0,r*n,o*n),t.drawImage(c,0,0,r*n,o*n)}const kM=m.createLogger({name:"canvas-streamer"});kM.debug("main-view component loaded");const xo=10,eh=sn.observer(({canvasDispatcher:t,height:e=30,width:s=50,defaultFps:r=10,showPreview:o=!1,name:n,apiPath:i="/api/system/canvas"})=>{const a=g.useRef(null),[c,u]=g.useState();g.useEffect(()=>{const h=t.addNamedEndpoint(n,{apiPath:i,fps:r,width:s,height:e,id:n});u(h)},[t]);const d=g.useCallback(h=>{if(a.current&&o){const f=a.current.getContext("2d");f&&PM({ctx:f,format:"base64",dataString:h,height:e,width:s,pixelSize:xo})}},[s,e,o]);return g.useEffect(()=>{c&&(c.onFrame=d,c.width=s,c.height=e,c.fps=r)},[c,d,s,e,r]),o&&Oa.createPortal(T.jsx(FM,{children:T.jsx(NM,{children:T.jsx("canvas",{ref:a,width:s*xo,height:e*xo,style:{border:"1px solid black"}})})}),document.body)}),LM=AM(eh),FM=tn.div`
216
216
  display: flex;
217
217
  flex-direction: column;
218
218
  gap: 8px;
@@ -224,5 +224,5 @@ ${u}topics:${e}
224
224
  display: flex;
225
225
  flex-direction: column;
226
226
  align-items: center;
227
- `,th=()=>{const t=jr.type;return Q({modelId:t,modelType:jr.type,options:{}})};function UM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=th();return T.jsx(o,{...r,children:T.jsx(t,{...e,device:s})})}}function jM(t,e,s){const r=new Promise(o=>{O.getInstance().whenReady().then(()=>{const{model:n}=O.getInstance().modelManager.createModelInstance(t,e??t,s);return n.whenReady().then(()=>{o(n.modelData)})})});return hn(r)}function BM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Ei();return T.jsx(o,{...r,children:T.jsx(t,{...e,kosTime:s})})}}const sh=()=>{const t=ks.type;return Q({modelId:t,modelType:ks.type,options:{}})};function HM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=sh();return T.jsx(o,{...r,children:T.jsx(t,{...e,networkInterfaceContainer:s})})}}const rh=()=>{const t=Cr.type;return Q({modelId:t,modelType:Cr.type,options:{}})};function KM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=rh();return T.jsx(o,{...r,children:T.jsx(t,{...e,oTA:s})})}}function qM(t,e){g.useEffect(()=>{function s(o){t.current&&!t.current.contains(o.target)&&e()}function r(o){o.key==="Escape"&&e()}return document.addEventListener("mousedown",s),document.addEventListener("keydown",r,!1),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",r,!1)}},[t,e])}function zM(t){const e=g.useRef(null),s=t.onAlert;return qM(e,s),T.jsx("div",{ref:e,style:{width:"100%"},children:t.children})}const VM=t=>{var u;const{stateProp:e}=t,[s,r]=g.useState((u=t.stateProp)==null?void 0:u.value),[o,n]=g.useState(!1),[i,a]=g.useState(void 0);return g.useEffect(()=>{async function d(h){try{h&&(await fe(h),n(!0))}catch(f){a(f.message)}}d(e)},[e]),g.useEffect(()=>{const d=G(()=>{e&&o&&r(e.value)});return()=>{d()}},[o,e]),[s,{ready:o,error:i}]},oh=()=>{const[t,e]=g.useState(!1),[s,r]=g.useState([]),o=Ut.type,n=Q({modelId:o,modelType:Ut.type,options:{}});return g.useEffect(()=>{const i=G(()=>{var a,c;e(((a=n.model)==null?void 0:a.isStorageInserted)??!1),r(((c=n.model)==null?void 0:c.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:t,devices:s}};function GM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=oh();return T.jsx(o,{...r,children:T.jsx(t,{...e,storageDeviceContainer:s})})}}const Ao=m.createLogger({name:"use-timer"}),YM=({timerName:t,onTimerExpired:e,onTimerTick:s,timerEventActions:r,autoStart:o})=>{const n=kd.getTimer(t);g.useEffect(()=>{if(!n){console.warn(`Timer with name ${t} does not exist.`);return}const u=C(yi,d=>{const{name:h,action:f,remainingTime:p}=d==null?void 0:d.body;h===t&&(f===vi?e({name:h,action:f,remainingTime:p,timer:n}):r!=null&&r[f]&&r[f]({name:h,action:f,remainingTime:p,timer:n}))});return o&&n.start(),()=>{u.unsubscribe()}},[o,e,r,t,n]),g.useEffect(()=>{if(!n||!s)return;const u=`${bi}/${t}`,d=C(u,h=>{const{name:f,remainingTime:p}=h==null?void 0:h.body;f===t&&s({name:f,remainingTime:p,timer:n})});return()=>{d.unsubscribe()}},[s,t,n]);const i=g.useCallback(()=>{n?n.start():Ao.warn(`Timer with name ${t} does not exist.`)},[n,t]),a=g.useCallback(()=>{n?n.reset():Ao.warn(`Timer with name ${t} does not exist.`)},[n,t]),c=g.useCallback(()=>{n?n.pause():Ao.warn(`Timer with name ${t} does not exist.`)},[n,t]);return{timer:n,start:i,reset:a,pause:c}},WM=t=>{const e=/[\\^$.*+?()[\]{}|]/g;return RegExp(e.source).test(t)?t.replace(e,"\\$&"):t},QM=t=>t instanceof RegExp,ZM=t=>typeof t=="string",XM=(t,e,s)=>{if(t===""||e==="")return t;let r=e;QM(r)||(r=new RegExp("("+WM(r)+")","gi"));const o=t.split(r);for(let n=1,i=o.length;n<i;n+=2)o[n]=s(o[n],n);return o},nh=(t,e,s)=>{let r=t;return Array.isArray(r)||(r=[r]),r.flatMap(o=>ZM(o)?XM(o,e,s):o)};function JM(t,e){let s=t;return Object.entries(e).forEach(([r,o])=>{const n=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=nh(s,n,(i,a)=>o.type==="br"?T.jsx("br",{}):g.cloneElement(o,{key:`${r}-${a}`},i))}),s}const eT=t=>{const{i18nKey:e,t:s,defaults:r,components:o,values:n={},context:i}=t,a=s(e,{defaultValue:r,data:n,context:i,returnObjects:!0}),c=JM(a,o||{});return T.jsx("span",{className:t.className,children:c})},Tt=new Map;function tT(t,e){if(Tt.has(t)){const s=Tt.get(t);if(s.status==="finished")return s.result;throw s.promise}else{const s=e().then(o=>{Tt.set(t,{status:"finished",result:o})},o=>{throw Tt.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw Tt.set(t,r),s}}function Xo(t,e){return tT(t,e)}const sT=async()=>{const t=await Uc(Ue.type);return await fe(t.model),t.model},rT=async(t,e,s)=>{const r=t.resolveNamespace(e);await fe(r);for(const o of s){const n=t.resolveNamespace(o);await fe(n),Tt.set(o,{status:"finished",result:n})}return r},oT=(t,e)=>{const s=[t].flat(),[r,...o]=s,n=Xo(Ue.type,sT),i=s.join("__"),a=Xo(i,()=>rT(n,r,o)),c=g.useMemo(()=>({exists:d=>{const h=e!=null&&e.keyPrefix?`${e.keyPrefix}.${d}`:d;return a?a.exists(h):!1}}),[e==null?void 0:e.keyPrefix,a]);return{t:g.useCallback((d,h)=>{const f=e!=null&&e.keyPrefix?`${e.keyPrefix}.${d}`:d;return a?a.resolveKey(f,h):(m.debug(`Translation model ${t} not ready for key: ${f}`),f)},[e==null?void 0:e.keyPrefix,t,a]),i18n:c}},ih=()=>{const t=Ue.type;return Q({modelId:t,modelType:Ue.type,options:{}})};function nT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=ih();return T.jsx(o,{...r,children:T.jsx(t,{...e,translationContainer:s})})}}const iT=t=>Q({modelId:t,modelType:Rs.type}),Oi=()=>Q({modelId:Lt.type,modelType:Lt.type,options:{}}),aT=({troubleType:t,condition:e})=>{const{model:s}=Oi(),[r,o]=g.useState(!1),[n,i]=g.useState([]),a=g.useCallback(()=>{var c,u;return n.length>0&&((c=n[0])!=null&&c.resolvable)?(u=n[0])==null?void 0:u.resolve():Promise.resolve(void 0)},[n]);return g.useEffect(()=>G(()=>{const u=(t?s==null?void 0:s.troubles.getIndexByKey("byType",t):s==null?void 0:s.troubles.data)||[],d=e?u.filter(e):u;o(d.length>0),i(d)}),[e,s,t]),[r,a,n.length>0?n[0]:void 0,n]};function cT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Oi();return T.jsx(o,{...r,children:T.jsx(t,{...e,troubleContainer:s})})}}const ah=()=>{const t=Fs.type,e=Q({modelId:t,modelType:Fs.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,r]=g.useState(!1),[o,n]=g.useState(!1),[i,a]=g.useState([]);return g.useEffect(()=>{const c=G(()=>{var u,d,h;r(((u=e.model)==null?void 0:u.isUsbInserted)??!1),n(((d=e.model)==null?void 0:d.hasAvailableUpdates)??!1),a(((h=e.model)==null?void 0:h.data)??[])});return()=>{c()}},[e.model]),{...e,inserted:s,updateAvailable:o,updates:i}};function lT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=ah();return T.jsx(o,{...r,children:T.jsx(t,{...e,usbUpdateContainer:s})})}}const uT=({path:t,propKey:e})=>{const{status:s}=Q({modelType:Os.type,modelId:t,options:{path:t}}),[r,o]=g.useState(!1),[n,i]=g.useState(),[a,c]=g.useState(""),[u,d]=g.useState(),h=f=>{n&&e&&n.updateProperty(e,f)};return g.useEffect(()=>{var f;s.model&&i(s.model),s.model&&e&&((f=s.model)!=null&&f.props.has(e)?c(s.model.props[e]):d(`property ${e} not found`)),s.ready&&o(s.ready)},[s.ready,s.model,e]),g.useEffect(()=>{e&&M.autorun(()=>{const f=n==null?void 0:n.props[e];c(f||"")})},[n,e]),{config:n,ready:r,value:a,error:u,updateValue:h}},dT=(t,e)=>{switch(e.type){case"UPDATE":return e.payload;default:return t}},ch=({configProperty:t,optionsTransformer:e})=>{const[s,r]=g.useState(!1),[o,n]=g.useState(""),[i,a]=g.useReducer(dT,{value:String(t==null?void 0:t.value),displayValue:t==null?void 0:t.displayValue,significantValue:t==null?void 0:t.significantValue,unit:t==null?void 0:t.unit,options:t==null?void 0:t.options,mappedOptions:[],updateProperty:t==null?void 0:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}),c=g.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&(t==null||t.updateProperty(d))},[t]);return g.useEffect(()=>{async function u(d){try{d&&(await fe(d),r(!0))}catch(h){n(h.message)}}u(t)},[t]),g.useEffect(()=>{const u=G(()=>{if(t&&s){let d=[];e&&(d=e(t.options)),a({type:"UPDATE",payload:{value:String(t.value),displayValue:t.displayValue,significantValue:t.significantValue,unit:t.unit,options:t.options,mappedOptions:d,updateProperty:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}})}});return()=>{u()}},[t,e,s]),{...i,configSelectProps:{onChange:c,value:i.value,options:e?i.mappedOptions||[]:i.options||[]},ready:s,error:o}};function hT(t,e){const s=e??new Date().getFullYear(),r=[31,28,31,30,31,30,31,31,30,31,30,31];return t===1&&(s%4===0&&s%100!==0||s%400===0)?29:r[t]??0}function fT(t,e){return new Date(t,e,0).getDate()}function lh(t,e){const s=hT(e,t),r=[];for(let o=1;o<=s;o++)r.push(o);return r}function uh(){return[...Array(12).keys()].map(e=>new Date(0,e).getMonth())}function dh(t=[2018,2028]){const e=[];for(let s=t[0];s<=t[1];s++)e.push(s);return e}function hh(t,e=[2018,2028]){const s=dh(e);return t==="long"?s:s.map(r=>Number(r.toString().substring(2)))}function Ii(t="numeric",e="en-US"){const s=new Intl.DateTimeFormat(e,{month:t,timeZone:"UTC"}).format;return[...Array(12).keys()].map(r=>s(new Date(Date.UTC(0,r,1))))}function pT({locale:t="en-US",year:e,month:s,day:r,formatOptions:o={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:n}){const i=s-1,a=new Date(e,i,r),c=new Intl.DateTimeFormat(t,{month:o.month}).format(a),u=new Intl.DateTimeFormat(t,{year:o.year}).format(a),d=new Intl.DateTimeFormat(t,{day:o.day}).format(a);return n?n=="MMDDYY"?`${c} ${d} ${u}`:n==="DDMMYY"?`${d} ${c} ${u}`:n==="YYMMDD"?`${u} ${c} ${d}`:`${u} ${d} ${c}`:new Intl.DateTimeFormat(t,o).format(a)}function we(t){return t.toString().length===2?new Date(Date.parse(`01 Jan 20${t}`)).getFullYear():t}function gT(t){return typeof t=="string"?new Date(Date.parse(`01 ${t.substring(0,3)} 2023`)).getMonth()+1:t}function fh(t,e,s){const r=we(e),o=new Date(r,t,1).getDay(),n=new Date(r,t+1,0).getDate();return[...Array(42).keys()].map(a=>a<o||a>n+o-1?{label:"",value:0,disabled:!0}:s[a-o])}function fs(t,e,s){const r=e-1,o=new Date(t,r,s);return new Date(o).getMonth()===r&&new Date(o).getDate()===s}function ps(t,e){return new Date(t,e,0).getDate()}function ph(t="en-US",e="short"){const s=new Intl.DateTimeFormat(t,{weekday:e}).format;return[...Array(7).keys()].map(r=>s(new Date(Date.UTC(2021,5,r))))}function gh({locale:t="en-US",year:e=new Date().getFullYear(),month:s=new Date().getMonth(),yearRange:r=[2018,2028],daysOfWeekFilter:o=[],formatOptions:{yearFormat:n="long",monthFormat:i="long",dayFormat:a="short"}={}}){const c=$i(n,r),u=mh(n,r,t),d=yh(i,t),h=bh(i,t),f=Ci(e,s),p=vh(e,s,t,o),y=Mh(s,e,p),w=wh(t,a);return{daysArray:f,monthsArray:d,yearsArray:c,yearsOptionsArray:u,monthsOptionsArray:h,daysOptionsArray:p,calendarDayArray:y,dayNamesArray:w}}function $i(t="long",e=[2018,2028]){return g.useMemo(()=>hh(t,e),[t,e])}function mh(t="long",e=[2018,2028],s="en-US"){const r=$i(t,e);return g.useMemo(()=>r.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,r])}function yh(t,e="en-US"){return g.useMemo(()=>Ii(t,e),[t,e])}function bh(t,e="en-US"){const s=g.useMemo(()=>uh(),[]),r=g.useMemo(()=>Ii(t,e),[t,e]);return g.useMemo(()=>[...Array(12).keys()].map(n=>({label:r[n],value:Number(s[n])})),[r,s])}function Ci(t,e){const s=we(t);return g.useMemo(()=>lh(s,e),[e,s])}const mT=(t,e,s,r=[])=>{const o=new Date(t,e,s).getDay();return r.length>0&&r.includes(o)};function vh(t,e,s="en-US",r=[]){const o=Ci(t,e);return g.useMemo(()=>o.map(i=>({label:i.toLocaleString(s),value:i,disabled:mT(t,e,i,r)})),[r,s,e,o,t])}function wh(t="en-US",e="short"){return g.useMemo(()=>ph(t,e),[t,e])}function Eh({year:t=new Date().getFullYear(),month:e=new Date().getMonth(),day:s=new Date().getDate(),formatString:r}){const o=e,n=new Date(t,o,s);return{formattedDate:Ke.format(n,r)}}function Mh(t,e,s){return g.useMemo(()=>fh(t,e,s),[t,e,s])}var Th=(t=>(t.MMDDYY="MMDDYY",t.DDMMYY="DDMMYY",t.YYMMDD="YYMMDD",t.YYDDMM="YYDDMM",t))(Th||{});function yT({locale:t="en-US",date:{year:e=new Date().getFullYear(),month:s=new Date().getMonth(),day:r=new Date().getDate()}={year:new Date().getFullYear(),month:new Date().getMonth(),day:new Date().getDate()},formatOptions:{yearFormat:o="long",monthFormat:n="long",dayFormat:i="short",formatString:a="yyyy/MM/dd"}={},filterOptions:{yearsRange:c=[2018,2028],daysOfWeekFilter:u=[]}={}}){const[d,h]=g.useState(e),[f,p]=g.useState(c),[y,w]=g.useState(s),[E,_]=g.useState(r);g.useEffect(()=>{h(e)},[e]),g.useEffect(()=>{w(s)},[s]),g.useEffect(()=>{_(r)},[r]);const{yearsArray:L,yearsOptionsArray:U,monthsArray:I,monthsOptionsArray:S,daysArray:Z,daysOptionsArray:Y,calendarDayArray:le,dayNamesArray:Zt}=gh({locale:t,year:d,yearRange:f,month:y,formatOptions:{yearFormat:o,monthFormat:n,dayFormat:i},daysOfWeekFilter:u}),{formattedDate:Xt}=Eh({year:d,month:y,day:E,formatString:a});return{dateActions:{setYear:h,setYearRange:p,setMonth:w,setDay:_,nextMonth:()=>{const te=y<11?we(d):we(d+1),ue=y<11?y+1:0;if(!fs(te,ue,E)){const Ze=ps(te,ue);_(Ze)}ue===0&&h(te),w(ue)},previousMonth:()=>{const te=we(y===0?d-1:d),ue=y===0?11:y-1;if(!fs(te,ue,E)){const Ze=ps(te,ue);_(Ze)}ue===11&&h(te),w(ue)},nextYear:()=>{const te=d<f[1]?d+1:f[0],ue=we(te);if(fs(ue,y,E))h(te);else{const Ze=ps(we(d+1),y);_(Ze),h(te)}},previousYear:()=>{const te=d>f[0]?d-1:f[0],ue=we(te);if(fs(ue,y,E))h(te);else{const Ze=ps(we(d-1),y);_(Ze),h(te)}}},dateState:{year:d,yearRange:f,month:y,day:E,yearsArray:L,yearsOptionsArray:U,monthsArray:I,monthsOptionsArray:S,daysArray:Z,daysOptionsArray:Y,calendarDayNames:Zt,calendarDayArray:le,formattedDate:Xt}}}function _h({date:t=new Date,dateFormat:e,timeFormat:s,options:r={}}){const[o,n]=g.useState("Formatting Time..."),[i,a]=g.useState("Formatting Date..."),c=!!r.ignoreDateFormat,{model:u,ready:d}=Q({modelId:re.type,modelType:re.type,options:{}}),h=typeof t=="string"?Ke.parseISO(t):t;return g.useEffect(()=>{c?a(""):e?a(Ke.format(h,e)):d&&a(Ke.format(h,u!=null&&u.selectedDateFormat?u==null?void 0:u.selectedDateFormat:""))},[c,t,e,h,u,d]),g.useEffect(()=>{s?n(Ke.format(h,s)):d&&n(Ke.format(h,u!=null&&u.selectedTimeFormat?u==null?void 0:u.selectedTimeFormat:""))},[t,s,h,u,d]),{formattedDate:i,formattedTime:o}}const Sh=({secondsFromMidnight:t=0})=>{const[e,s]=g.useState(0),[r,o]=g.useState(0),[n,i]=g.useState(0),[a,c]=g.useState(new Date),{formattedTime:u}=_h({date:a,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const d=Number(t),h=Math.floor(d/3600),f=Math.floor(d%3600/60),p=d%60;s(h),o(f),i(p);const y=new Date;y.setHours(0,0,0,0);const w=new Date(y.getTime()+d*1e3);c(new Date(w))},[t]),{hours:e,minutes:r,seconds:n,formattedTime:u,timeActions:{setHours:s,setMinutes:o,setSeconds:i}}},bT=({configProperty:t})=>{const{value:e}=ch({configProperty:t}),s=parseInt(e||"0",10),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}=Sh({secondsFromMidnight:s}),c=g.useRef();return g.useEffect(()=>{const u=r*3600+o*60+n;return c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{t&&t.updateProperty(u.toString())},100),()=>{c.current&&clearTimeout(c.current)}},[t,r,o,n]),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}};function vT(t,e={}){const{intervalMs:s=5*60*1e3,immediate:r=!0}=e;g.useEffect(()=>{const o=()=>{try{t({__warmup:!0})}catch{}};r&&("requestIdleCallback"in window?requestIdleCallback(o):setTimeout(o,1));const n=s?setInterval(o,s):null;return()=>{n&&clearInterval(n)}},[t,s,r])}const wT=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),ET=(t=wT)=>{const[e,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=Q({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const c=G(()=>{s((n==null?void 0:n.dateFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),g.useEffect(()=>{const c=G(()=>{n!=null&&n.dateFormatId&&(n!=null&&n.selectedDateFormat)&&o({id:n==null?void 0:n.dateFormatId,value:n==null?void 0:n.selectedDateFormat})});return()=>{c()}},[n==null?void 0:n.selectedDateFormat,n==null?void 0:n.dateFormatId]);const a=g.useCallback(c=>{var d;let u="";typeof c=="string"?u=c:(d=c==null?void 0:c.target)!=null&&d.value&&(u=c.target.value),u&&(n==null||n.setSelectedDateFormat(u))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(c=>c.id))??[],regionModel:n,selectedDateFormat:(r==null?void 0:r.value)||"",dateFormatId:(r==null?void 0:r.id)||"",updateDateFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)||"",options:e}}},MT=t=>T.jsx("option",{title:t,value:t,children:t},t),Oh="kos:service:region:settings",Ih="timeZone",TT=`${Oh}-${Ih}`,_T=(t=MT)=>{const[e,s]=g.useState([]),[r,o]=g.useState(""),{model:n,ready:i}=Q({modelType:re.type,modelId:re.type,options:{}}),a=ht.factory(TT)({path:Oh,attribute:Ih});g.useEffect(()=>{const u=G(()=>{s((n==null?void 0:n.timeZones.map(t))||[]),n!=null&&n.timeZones.length&&Zo(n==null?void 0:n.timeZones[0])});return()=>{u()}},[n,i,t]),g.useEffect(()=>{const u=G(()=>{o(a.value||"")});return()=>{u()}},[a.value]);const c=g.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&Zo(d)},[]);return{options:e,raw:(n==null?void 0:n.timeZones)??[],regionModel:n,selectedTimeZone:r,timeZones:(n==null?void 0:n.timeZones)??[],updateTimeZone:c,selectProps:{onChange:c,value:r,options:e}}},$h="kos:service:region",Ch="regionId",ST=`${$h}-${Ch}`,OT=t=>T.jsx("option",{title:t,value:t,children:t},t),Dh=(t=OT)=>{const[e,s]=g.useState([]),[r,o]=g.useState("factory"),{model:n,ready:i}=Q({modelType:re.type,modelId:re.type,options:{}}),a=ht.factory(ST)({path:$h,attribute:Ch});g.useEffect(()=>{const u=G(()=>{s((n==null?void 0:n.availableRegions.map(t))||[])});return()=>{u()}},[n,i,t]),g.useEffect(()=>{const u=G(()=>{o(a.value||"factory")});return()=>{u()}},[a.value]);const c=g.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&Rd(d)},[]);return{raw:(n==null?void 0:n.availableRegions)??[],regionModel:n,regionData:n==null?void 0:n.selectedRegion,selectedRegion:r,updateRegion:c,regionSelectProps:{onChange:c,value:r,options:e}}},IT=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),$T=(t=IT)=>{const[e,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=Q({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const c=G(()=>{s((n==null?void 0:n.timeFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),g.useEffect(()=>{const c=G(()=>{n!=null&&n.timeFormatId&&(n!=null&&n.selectedTimeFormat)&&o({id:n==null?void 0:n.timeFormatId,value:n==null?void 0:n.selectedTimeFormat})});return()=>{c()}},[n==null?void 0:n.selectedTimeFormat,n==null?void 0:n.timeFormatId]);const a=g.useCallback(c=>{var d;let u="";typeof c=="string"?u=c:(d=c==null?void 0:c.target)!=null&&d.value&&(u=c.target.value),u&&(n==null||n.setSelectedTimeFormat(u))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(c=>c.id))??[],regionModel:n,selectedTimeFormat:(r==null?void 0:r.value)??"",timeFormatId:(r==null?void 0:r.id)??"",updateTimeFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)??"",options:e}}},CT=(t,e)=>g.useMemo(()=>Rn(t),e),DT={config:{attributes:!0,childList:!0,subtree:!0}};function xT(t,e,s=DT){const[r,o]=g.useState(null);g.useEffect(()=>{if(!e||typeof e!="function")throw new Error("A valid callback function is required");const n=new MutationObserver(e);o(n)},[e,s,o]),g.useEffect(()=>{if(!r)return()=>{};if(!t)throw new Error("A valid DOM element is required");const{config:n}=s;try{r.observe(t,n)}catch(i){m.error(i)}return()=>{r&&r.disconnect()}},[r,t,s])}const xh={validateStart:function(t){return!0},validateStop:function(t){const e=t.event.currentTarget.getBoundingClientRect(),[s,r]=t.xy;return s<e.left||s>e.right||r<e.top||r>e.bottom}},Ro=m.createLogger({name:"usePressGesture",group:"kos-hooks"});function AT({onPressed:t,onRelease:e,intersectionStrategy:s=xh}){const r=g.useRef(!1),o=Hh.useGesture({onDragStart:c=>{Ro.info("onDragStart",c.type),s.validateStart(c)&&(t&&t(),r.current=!0)},onDrag:c=>{Ro.info("onDrag",c.type),r.current&&s.validateStop(c)&&(e&&e(),r.current=!1)},onDragEnd:c=>{Ro.info("onDragEnd",c.type),r.current&&e&&(e(),r.current=!1)}}),n=()=>{t&&t(),r.current=!0},i=()=>{r.current&&e&&(e(),r.current=!1)},a=()=>{r.current&&e&&(e(),r.current=!1)};return{dom:o,mesh:()=>({onPointerDown:n,onPointerUp:i,onPointerOut:a})}}const Ah=()=>{const[t,e]=g.useState(!1),s=O.getInstance();return g.useEffect(()=>{const r=G(()=>{s&&s.reloading!==t&&e(s.reloading)});return()=>{r()}},[s,t]),[t]};function Rh(t=!1,e="2-digit"){return g.useMemo(()=>{const s=t?12:24;return Array.from({length:s},(r,o)=>{const n=t&&o===0?12:o%s;return{id:o,label:e==="2-digit"?n.toString().padStart(2,"0"):n.toString()}})},[e,t])}function Jo(t,e="2-digit",s=0,r=0){return g.useMemo(()=>Array.from({length:t},(o,n)=>{const i=String(n+s);return{id:n+r,label:e==="2-digit"?i.padStart(2,"0"):i}}),[t,s,r,e])}function Ph(t="en-US"){return g.useMemo(()=>["AM","PM"].map(e=>{const s=new Intl.DateTimeFormat(t,{hour:"2-digit",hour12:!0}).formatToParts(new Date().setHours(e==="AM"?0:12))[2].value;return{id:s,label:s}}),[t])}function kh({formatOptions:{hour12:t=!0,hour:e="2-digit",minute:s="2-digit",second:r="2-digit"}={hour12:!0,hour:"2-digit",minute:"2-digit",second:"2-digit"},locale:o="en-US"}){const n=Rh(t,e),i=Jo(60,s),a=Jo(60,r),c=Ph(o);return{hourOptions:n,minuteOptions:i,secondOptions:a,amPmOptions:c}}function Lh(t,e){return Ke.format(t,e)}function Fh({formatOptions:t,initialDate:e=new Date,locale:s="en-US",format:r="HH:mm"}){const[o,n]=g.useState(e),i=g.useCallback(w=>{n(E=>{const _=new Date(E);return _.setHours(Number(w)),_})},[]),a=g.useCallback(w=>{n(E=>{const _=new Date(E);return _.setMinutes(Number(w)),_})},[]),c=g.useCallback(w=>{n(E=>{const _=new Date(E);return _.setSeconds(Number(w)),_})},[]),u=g.useCallback(w=>{const E=new Date(w);n(E)},[]),d=Lh(o,r),{hourOptions:h,minuteOptions:f,secondOptions:p,amPmOptions:y}=kh({formatOptions:t,locale:s});return{amPmOptions:y,formattedTime:d,hourOptions:h,minuteOptions:f,secondOptions:p,setHours:i,setMinutes:a,setSeconds:c,setTime:u,time:new Date(o)}}const RT=t=>{const{regionModel:e}=Dh(),s=g.useMemo(()=>({hour12:e==null?void 0:e.is12HourTimeFormat}),[e==null?void 0:e.is12HourTimeFormat]);return Fh({...t,locale:e==null?void 0:e.regionId,format:e==null?void 0:e.selectedTimeFormat,formatOptions:s})};function PT(t){return e=>{const[s]=Ah();return s?T.jsx(Hd,{message:"Wait a moment while your project reloads..."}):T.jsx(t,{...e})}}const Ta=m.createLogger({name:"studio-properties-service",group:"Services"}),kT="/api/kos/studio/properties",Nh=async t=>{if(Ta.debug("sending GET for studio-properties"),!t)throw Ta.error("connectionId is undefined"),new Error("connectionId is undefined");return await Ae.get(kT,{},{destinationAddress:t,timeout:500})},LT=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:Nh},Symbol.toStringTag,{value:"Module"}));var FT=Object.getOwnPropertyDescriptor,NT=(t,e,s,r)=>{for(var o=r>1?void 0:r?FT(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Uh="studio-properties-model",UT="/kos/studio/properties",_a={"kos.studio.tool.legacy":1};let en=class{constructor(t,e,s){l(this,"id");l(this,"connectionId");l(this,"unsubscribe",null);l(this,"logger");l(this,"data");this.id=t,this.logger=s.logger,this.data=Ie(),this.connectionId=e.connectionId}async init(){this.logger.debug(`initializing studio-properties ${this.id}`)}async load(){this.logger.debug(`loading studio-properties ${this.id}`)}async terminatePropertiesSession(){var t;(t=this.unsubscribe)==null||t.call(this)}async initializePropertiesSession(){this.unsubscribe=Ct.getInstance().subscribeTopic({topic:UT,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[t,e]=await Nh(this.connectionId);if(t){this.logger.error(`Error loading studio-properties: ${t}`),this.data.setValues(_a);return}if(e){const s=Object.keys(e).reduce((r,o)=>(r[o]=e[o]??o,r),{});this.data.setValues(s??_a),m.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(t){return this.data[t]}createObservableProperty(t){return Rn(()=>this.get(t))}};en=NT([R(Uh)],en);const jT=new ve({class:en,type:Uh});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>M.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>M.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>sn.observer});exports.AuthState=_l;exports.BrowserKosRouter=Dl;exports.BrowserRouter=zn;exports.CanvasDispatcher=Nt;exports.CanvasDispatcherServices=Aw;exports.CanvasRenderer=li;exports.CanvasStreamer=LM;exports.CanvasStreamerBase=eh;exports.ChildModels=ze;exports.CompanionParentModel=Ve;exports.ConfigBean=Os;exports.ContainerAwareSetup=Tn;exports.CoreExtensionManager=CE;exports.CoreModels=mi;exports.CreateModelTranslationsContext=Wd;exports.CreateModelTranslationsProvider=pM;exports.DateDisplayFormat=Th;exports.DateHelpers=of;exports.DependencyLifecycle=x;exports.DependencyModels=F;exports.DependencyResolutionPolicy=qe;exports.Device=jr;exports.DeviceServices=eE;exports.DomIntersectionStrategy=xh;exports.EVENT_KOS_MODEL_READY=an;exports.EVENT_TROUBLE_ADDED=Xm;exports.EVENT_TROUBLE_REMOVED=Jm;exports.EXTENSION_CANVAS_RENDERER=ee;exports.EXTENSION_FEATURE_FLAG_RESOLVER=vc;exports.EXTENSION_TROUBLE_DATA_MAPPER=Ir;exports.EXTENSION_TROUBLE_MAPPER=Ys;exports.ErrorBoundaryWithFallback=Kd;exports.EventBus=Vh;exports.EventBusFunctional=Yh;exports.EventBusState=Qh;exports.ExtensionManager=$;exports.FUTURE_CONTAINER_MODEL_TYPE=ou;exports.FUTURE_MODEL_TYPE=Yl;exports.FUTURE_NOT_ASSIGNED=kn;exports.FeatureFlagService=wc;exports.FetchError=ye;exports.FutureAliases=bs;exports.FutureContainerFactory=Ye;exports.FutureContainerModel=iu;exports.FutureContainerSetup=vn;exports.FutureEndState=Ge;exports.FutureFactory=zt;exports.FutureHandler=Xr;exports.FutureManager=at;exports.FutureModel=eu;exports.FutureService=gs;exports.HEADER_CACHE_CONTROL=Da;exports.HEADER_CONTENT_TYPE=Ca;exports.HEADER_DESTINATION_ADDR=je;exports.HEADER_FOS_REQUEST_ID=xa;exports.HEADER_METHOD=qr;exports.HEADER_ORDERED=on;exports.HEADER_REQUEST_ID=Ns;exports.HEADER_REQUEST_TYPE=Ce;exports.HEADER_RESPONSE_ID=zr;exports.HEADER_SOURCE_ADDR=$a;exports.HEADER_TOPIC=Ia;exports.HEADER_URL=Bt;exports.HEADER_WORK_TRACKER=nn;exports.HttpRouteHandlers=ke;exports.KOS_EXECUTION_CONTEXT=Qr;exports.KOS_MODEL_ID=gr;exports.KOS_SERVICE=FE;exports.KOS_SERVICE_1_6_5=RE;exports.KOS_SERVICE_1_8_1=kE;exports.KeyValue=Yn;exports.KeyValueServices=Gy;exports.Kos=ae;exports.KosConfigPropertySpec=ht;exports.KosContainerIndex=Sn;exports.KosContextBean=$l;exports.KosContextManager=V;exports.KosCore=O;exports.KosCoreModelPropertyMapper=Ee;exports.KosDataContainer=An;exports.KosDependencyTypes=Jf;exports.KosExpressionEvaluator=yu;exports.KosExtensionUtils=lf;exports.KosFeatureFlags=Ec;exports.KosFetchMethods=Pc;exports.KosGlobalConfig=yn;exports.KosHttpRouteManager=Cn;exports.KosLog=m;exports.KosLogManager=wu;exports.KosLogManagerServices=ev;exports.KosMockEvents=Pa;exports.KosModel=El;exports.KosModelCollectionProvider=lM;exports.KosModelContainer=xe;exports.KosModelContext=po;exports.KosModelEvents=k;exports.KosModelFactory=ws;exports.KosModelLoader=Gd;exports.KosModelLoaderDisplay=Yd;exports.KosModelManager=Tl;exports.KosModelProvider=qd;exports.KosModelRegistrationFactory=ve;exports.KosModelRegistry=Qo;exports.KosModelState=v;exports.KosModelSymbol=bn;exports.KosModelVisitor=Tm;exports.KosObservableData=Fc;exports.KosRegistration=zm;exports.KosSingletonRegistration=Vm;exports.KosTime=_r;exports.KosTimeContext=Mi;exports.KosTimeProvider=MM;exports.KosTimeServices=av;exports.KosTimer=Pd;exports.KosToken=Cl;exports.KosTranslationProvider=CM;exports.KosTranslations=rd;exports.KosWSTransportStatus=wl;exports.KosWsEvents=Us;exports.LOADER_FEATURE_FLAG=Mf;exports.LOGIN_HOST=Aa;exports.LOGIN_URL=Kh;exports.LoadingMessage=Hd;exports.LogBlock=As;exports.LogBlockContainer=lo;exports.LogConfig=ys;exports.LogStream=_s;exports.LogStreamContainer=Gs;exports.LogStreamServices=bv;exports.LoggerSetup=Mn;exports.MODEL_DELETION_DELAY=Ml;exports.MiddlewareChain=Sl;exports.ModelEffects=nt;exports.ModelError=Xc;exports.MultipleFutureContainerSetup=wn;exports.MultipleFutureHandler=kc;exports.NestedModelContext=go;exports.NetworkInterface=hi;exports.NetworkInterfaceContainer=ks;exports.NetworkInterfaceServices=lE;exports.ObservableData=Ie;exports.OptionsRequired=Hs;exports.Ota=Cr;exports.OutsideAlerter=zM;exports.PLUGIN_EXTENSION_NAME=uf;exports.PORT=Ra;exports.PROFILE_ENABLE_RELEASES=hf;exports.PROFILE_LOG_DEBUG=lc;exports.PROFILE_LOG_INFO=uc;exports.PROFILE_RELAX_STORE_VALIDATION=ff;exports.PROFILE_TOOLS_PREVIEW=cc;exports.ParentModel=ms;exports.PluginExtensionManager=df;exports.ProgressBar=nM;exports.ReferenceConfig=cr;exports.RegionInfo=re;exports.RegionServices=ly;exports.RegistrationManager=A;exports.Registry=$E;exports.ReplayStrategy=ot;exports.ResponseRetention=se;exports.STATUS=rn;exports.ServiceFactory=oe;exports.ServiceRequestHandlers=it;exports.SingletonKosModelRegistrationFactory=Se;exports.SoftwareInfo=Dr;exports.SoftwareInfoContext=_i;exports.SoftwareInfoProvider=SM;exports.SoftwareInfoServices=ew;exports.StateActionHandlers=Sf;exports.StateBean=Ps;exports.StateBeanServices=nw;exports.StateEntryHandlers=St;exports.StateExitHandlers=vs;exports.StateMachineSetup=Bs;exports.StateProp=ni;exports.StatePropServices=gw;exports.StorageDevice=Hr;exports.StorageDeviceContainer=Ut;exports.StorageDeviceServices=pE;exports.StudioProperties=jT;exports.StudioPropertiesServices=LT;exports.SubscriptionHandlers=J;exports.TIMER_END=vi;exports.TIMER_EVENT=yi;exports.TOPIC_TIMER_TICK_EVENT=bi;exports.TimerManager=kd;exports.TokenContext=Jd;exports.TokenProvider=IM;exports.Topics=Ts;exports.Trans=eT;exports.TransitionMap=ur;exports.Transitions=In;exports.Translation=Rr;exports.TranslationContainer=Ue;exports.TranslationContainerContext=Si;exports.TranslationContext=Sw;exports.TransportFactory=Uo;exports.Trouble=Rs;exports.TroubleAwareSetup=En;exports.TroubleContainer=Lt;exports.TroubleServices=Fv;exports.Troubles=me;exports.UsbUpdate=gi;exports.UsbUpdateContainer=Fs;exports.UsbUpdateServices=ME;exports.VFS_SERVICE=KE;exports.VFS_SERVICE_1_6_5=UE;exports.VFS_SERVICE_1_8_1=BE;exports.WS_EVENT_TYPE=od;exports.WebSocketEvents=Ms;exports.WebSocketTransport=Ct;exports.WsEventFactory=ai;exports.acceptOrgInvitation=Bd;exports.addDaysToDate=ec;exports.addFuture=Ql;exports.addMonthsToDate=Ja;exports.api=tu;exports.applyMixins=Xh;exports.arraysEqual=Jh;exports.buildConfigBeanModel=sy;exports.buildFuture=qn;exports.buildFutureModel=Xl;exports.cancelFuture=Zl;exports.checkAppsStarted=Qm;exports.checkWildcardPattern=Vc;exports.clearAllServiceResponses=Um;exports.clearPath=Nm;exports.clearServiceResponse=Fm;exports.convert=jn;exports.convertFileSizeRaw=Zh;exports.convertWithUnits=gy;exports.createBaseMessage=dl;exports.createBroadcastMessageResponse=gl;exports.createCancellablePromise=JE;exports.createClient=Be;exports.createFosBaseMessage=ul;exports.createHeaders=ss;exports.createKosHtpMessageResponse=ml;exports.createKosMessage=fl;exports.createKosMessageResponse=yl;exports.createMessageBody=Qe;exports.createModelDependency=tl;exports.createOptionKey=Gf;exports.createPropKey=ut;exports.createReadableStream=rs;exports.createStudioMessage=ll;exports.createStudioMessageRequest=hl;exports.createStudioMessageResponse=pl;exports.debounce=ic;exports.del=Cc;exports.deleteFuture=Wl;exports.destroyKosModel=Oe;exports.evaluateScopes=Nl;exports.executeChildrenModelLifecycle=ol;exports.executeDependentModelLifecycle=ts;exports.executeListLifecycle=rl;exports.fetchModel=jM;exports.findModel=vp;exports.findModels=jc;exports.formatDate=rc;exports.formatDateSince=Xa;exports.formatDateTime=nc;exports.formatTime=oc;exports.get=$c;exports.getAllKosCompanionModels=Bc;exports.getCalendarMonthArray=fh;exports.getConfigBean=Fl;exports.getDayStrings=ph;exports.getDays=fT;exports.getDaysArray=lh;exports.getDaysInMonth=mn;exports.getDependenciesByLifecycle=sl;exports.getFormattedDate=pT;exports.getFormattedMonth=gT;exports.getFormattedMonthsArray=Ii;exports.getFormattedYear=we;exports.getFormattedYearsArray=hh;exports.getFutures=Ay;exports.getHttpRouteHandlers=Dc;exports.getKosCompanionModel=wp;exports.getKosLocalizationDescriptor=Xu;exports.getKosMessageLogging=pc;exports.getKosModel=Uc;exports.getKosModelSync=$e;exports.getKosModelType=bp;exports.getKosSessionKey=Il;exports.getLastDayOfMonth=ps;exports.getLocalizationDescriptor=yw;exports.getLogLevel=fc;exports.getLogMessageToStudio=gc;exports.getMessageBody=No;exports.getMonthsArray=uh;exports.getObservableCompanions=Ep;exports.getQueryParams=be;exports.getServiceResponse=km;exports.getStartedApps=Zm;exports.getTranslations=Zu;exports.getYearsArray=dh;exports.hasCachedResponse=Lm;exports.hasDecimals=kl;exports.hasHttpRouteHandlers=yr;exports.hasKosProfile=Po;exports.hslStringToHex=Tc;exports.hslToHex=Mc;exports.httpDelete=tp;exports.initKosProvider=mM;exports.initializeStateMachine=Oc;exports.injectStateMachineSupport=Sc;exports.isBoolean=Fn;exports.isKosCompanionTypeFactory=Yc;exports.isKosDataModel=Es;exports.isKosExecutionContext=_n;exports.isKosLoggingEnabled=mf;exports.isKosModel=_e;exports.isKosModelContainer=$n;exports.isKosModelReady=br;exports.isLeapYear=gn;exports.isLocalRefId=Bm;exports.isNumber=Jr;exports.isPrintable=ng;exports.isTroubleAware=Ow;exports.isValidDate=fs;exports.kosAction=X;exports.kosAutoEffect=G;exports.kosChild=De;exports.kosCompanion=Wf;exports.kosComputed=Rn;exports.kosConfigBean=eo;exports.kosConfigProperty=Sy;exports.kosContainerAware=Ic;exports.kosContext=Qf;exports.kosDependency=Ht;exports.kosEffect=Rl;exports.kosFuture=wi;exports.kosFutureAware=Zf;exports.kosLogger=sp;exports.kosLoggerAware=Ac;exports.kosModel=R;exports.kosModelEffect=Rc;exports.kosMultipleFutureAware=Xf;exports.kosObservable=Pn;exports.kosParentAware=Wr;exports.kosReference=rp;exports.kosServiceRequest=dt;exports.kosStateBean=GE;exports.kosStateEntry=lp;exports.kosStateExit=up;exports.kosStateGuard=dp;exports.kosStateMachine=cp;exports.kosStateProp=YE;exports.kosSubscribe=kp;exports.kosTopicHandler=B;exports.kosTroubleAware=hp;exports.kosWhen=Bo;exports.login=Nd;exports.mapConfigBeanModelToDto=Hl;exports.mapDataToModel=ko;exports.mapDtoToConfigBeanModel=jl;exports.mapDtoToFutureModel=Kn;exports.mapDtoToFutureOptions=Hn;exports.mapUpdateDtoToConfigBeanModel=Bl;exports.modelEventTopicFactory=Wc;exports.modelFactory=Kt;exports.modelTypeEventTopicFactory=Qc;exports.modifyConfigBean=Ll;exports.modifyFuture=Ry;exports.pairedClientHeartbeat=Im;exports.parseWildcardSegment=zc;exports.pipe=Ol;exports.post=Ks;exports.preloadKosModel=_p;exports.processId=rf;exports.processMiddleware=_m;exports.put=ep;exports.registerCompanionModel=Tp;exports.registerCoreModels=Dd;exports.registerExtensionPoint=js;exports.registerHttpRoutes=bg;exports.registerKosModel=Kc;exports.registerLegacyModel=Hc;exports.resetKosModel=yp;exports.resetPassword=jd;exports.resolveBaseUrl=il;exports.resolveChild=el;exports.resolveContainerDeltas=ef;exports.resolveItemListDeltas=sf;exports.resolveKosCompanion=Lo;exports.resolveKosContext=qm;exports.resolveKosProfiles=hc;exports.resolveListDeltas=tf;exports.resolveServiceUrl=ce;exports.resolveVariable=_c;exports.retryWithExponentialBackoff=Cm;exports.sendAsyncIntent=Ym;exports.sendBroadcastMessage=Fg;exports.sendIntent=Gm;exports.sendKosHttpMessageResponse=vl;exports.sendKosMessage=Pg;exports.sendKosMessageResponse=bl;exports.sendRequest=Hm;exports.sendStudioMessage=Lg;exports.sendStudioMessageRequest=kg;exports.startPasswordReset=Ud;exports.stringComponentInsert=nh;exports.studioAcceptOrgInvitation=XE;exports.studioLogin=WE;exports.studioResetPassword=ZE;exports.studioStartPasswordReset=QE;exports.subscribeStore=DE;exports.syncPublish=Km;exports.troubleByTypeReducer=Lc;exports.troubleDataFactory=Bu;exports.unloadKosModel=mp;exports.updateCompanionModelRegistration=Om;exports.updateModelRegistration=Sm;exports.updateRegion=Rd;exports.updateTimeZone=Zo;exports.useAmPmValues=Ph;exports.useCalendarDayArray=Mh;exports.useConfigBean=uT;exports.useConfigProperty=ch;exports.useContextModel=aM;exports.useContextModelHierarchy=Vd;exports.useDateArrays=gh;exports.useDateProps=yT;exports.useDateRelativeConfig=bT;exports.useDateRelativeData=Sh;exports.useDayNames=wh;exports.useDayOptions=vh;exports.useDays=Ci;exports.useDevice=th;exports.useFormattedDate=Eh;exports.useFormattedTime=Lh;exports.useFunctionWarmup=vT;exports.useHourValues=Rh;exports.useKosCore=Zd;exports.useKosDateFormats=ET;exports.useKosModel=Q;exports.useKosRegions=Dh;exports.useKosTime=Ei;exports.useKosTimeContext=TM;exports.useKosTimeFormats=$T;exports.useKosTimeZones=_T;exports.useKosTranslation=oT;exports.useKosTranslationContext=DM;exports.useLocalComputed=CT;exports.useModelFromHierarchy=dM;exports.useMonths=yh;exports.useMonthsOptions=bh;exports.useMutationObserver=xT;exports.useNetworkInterfaceContainer=sh;exports.useOta=rh;exports.usePressGesture=AT;exports.useProjectReload=Ah;exports.useRegionTimeProps=RT;exports.useRegionalTimeDate=_h;exports.useSoftwareInfo=Ti;exports.useSoftwareInfoContext=OM;exports.useStateProperty=VM;exports.useStorageDeviceContainer=oh;exports.useSuspenseData=Xo;exports.useTimeOptions=kh;exports.useTimeProps=Fh;exports.useTimeValues=Jo;exports.useTimer=YM;exports.useTranslationContainer=ih;exports.useTroubleContainerModel=Oi;exports.useTroubleModel=iT;exports.useTroublePresence=aT;exports.useUsbUpdateContainer=ah;exports.useYears=$i;exports.useYearsOptions=mh;exports.uuid=lt;exports.variableToHex=Tf;exports.waitForAppToStart=Wm;exports.waitForAppsToStart=Al;exports.waitForRequest=xn;exports.whenReady=fe;exports.withDevice=UM;exports.withKosTime=BM;exports.withNetworkInterfaceContainer=HM;exports.withOta=KM;exports.withProjectReloading=PT;exports.withSoftwareInfo=_M;exports.withStorageDeviceContainer=GM;exports.withTranslationContainer=nT;exports.withTroubleContainer=cT;exports.withUsbUpdateContainer=lT;exports.wrapPromise=hn;
227
+ `,th=()=>{const t=jr.type;return Q({modelId:t,modelType:jr.type,options:{}})};function UM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=th();return T.jsx(o,{...r,children:T.jsx(t,{...e,device:s})})}}function jM(t,e,s){const r=new Promise(o=>{O.getInstance().whenReady().then(()=>{const{model:n}=O.getInstance().modelManager.createModelInstance(t,e??t,s);return n.whenReady().then(()=>{o(n.modelData)})})});return hn(r)}function BM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Ei();return T.jsx(o,{...r,children:T.jsx(t,{...e,kosTime:s})})}}const sh=()=>{const t=ks.type;return Q({modelId:t,modelType:ks.type,options:{}})};function HM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=sh();return T.jsx(o,{...r,children:T.jsx(t,{...e,networkInterfaceContainer:s})})}}const rh=()=>{const t=Cr.type;return Q({modelId:t,modelType:Cr.type,options:{}})};function KM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=rh();return T.jsx(o,{...r,children:T.jsx(t,{...e,oTA:s})})}}function qM(t,e){g.useEffect(()=>{function s(o){t.current&&!t.current.contains(o.target)&&e()}function r(o){o.key==="Escape"&&e()}return document.addEventListener("mousedown",s),document.addEventListener("keydown",r,!1),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",r,!1)}},[t,e])}function zM(t){const e=g.useRef(null),s=t.onAlert;return qM(e,s),T.jsx("div",{ref:e,style:{width:"100%"},children:t.children})}const VM=t=>{var u;const{stateProp:e}=t,[s,r]=g.useState((u=t.stateProp)==null?void 0:u.value),[o,n]=g.useState(!1),[i,a]=g.useState(void 0);return g.useEffect(()=>{async function d(h){try{h&&(await fe(h),n(!0))}catch(f){a(f.message)}}d(e)},[e]),g.useEffect(()=>{const d=Y(()=>{e&&o&&r(e.value)});return()=>{d()}},[o,e]),[s,{ready:o,error:i}]},oh=()=>{const[t,e]=g.useState(!1),[s,r]=g.useState([]),o=Ut.type,n=Q({modelId:o,modelType:Ut.type,options:{}});return g.useEffect(()=>{const i=Y(()=>{var a,c;e(((a=n.model)==null?void 0:a.isStorageInserted)??!1),r(((c=n.model)==null?void 0:c.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:t,devices:s}};function GM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=oh();return T.jsx(o,{...r,children:T.jsx(t,{...e,storageDeviceContainer:s})})}}const Ao=m.createLogger({name:"use-timer"}),YM=({timerName:t,onTimerExpired:e,onTimerTick:s,timerEventActions:r,autoStart:o})=>{const n=kd.getTimer(t);g.useEffect(()=>{if(!n){console.warn(`Timer with name ${t} does not exist.`);return}const u=C(yi,d=>{const{name:h,action:f,remainingTime:p}=d==null?void 0:d.body;h===t&&(f===vi?e({name:h,action:f,remainingTime:p,timer:n}):r!=null&&r[f]&&r[f]({name:h,action:f,remainingTime:p,timer:n}))});return o&&n.start(),()=>{u.unsubscribe()}},[o,e,r,t,n]),g.useEffect(()=>{if(!n||!s)return;const u=`${bi}/${t}`,d=C(u,h=>{const{name:f,remainingTime:p}=h==null?void 0:h.body;f===t&&s({name:f,remainingTime:p,timer:n})});return()=>{d.unsubscribe()}},[s,t,n]);const i=g.useCallback(()=>{n?n.start():Ao.warn(`Timer with name ${t} does not exist.`)},[n,t]),a=g.useCallback(()=>{n?n.reset():Ao.warn(`Timer with name ${t} does not exist.`)},[n,t]),c=g.useCallback(()=>{n?n.pause():Ao.warn(`Timer with name ${t} does not exist.`)},[n,t]);return{timer:n,start:i,reset:a,pause:c}},WM=t=>{const e=/[\\^$.*+?()[\]{}|]/g;return RegExp(e.source).test(t)?t.replace(e,"\\$&"):t},QM=t=>t instanceof RegExp,ZM=t=>typeof t=="string",XM=(t,e,s)=>{if(t===""||e==="")return t;let r=e;QM(r)||(r=new RegExp("("+WM(r)+")","gi"));const o=t.split(r);for(let n=1,i=o.length;n<i;n+=2)o[n]=s(o[n],n);return o},nh=(t,e,s)=>{let r=t;return Array.isArray(r)||(r=[r]),r.flatMap(o=>ZM(o)?XM(o,e,s):o)};function JM(t,e){let s=t;return Object.entries(e).forEach(([r,o])=>{const n=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=nh(s,n,(i,a)=>o.type==="br"?T.jsx("br",{}):g.cloneElement(o,{key:`${r}-${a}`},i))}),s}const eT=t=>{const{i18nKey:e,t:s,defaults:r,components:o,values:n={},context:i}=t,a=s(e,{defaultValue:r,data:n,context:i,returnObjects:!0}),c=JM(a,o||{});return T.jsx("span",{className:t.className,children:c})},Tt=new Map;function tT(t,e){if(Tt.has(t)){const s=Tt.get(t);if(s.status==="finished")return s.result;throw s.promise}else{const s=e().then(o=>{Tt.set(t,{status:"finished",result:o})},o=>{throw Tt.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw Tt.set(t,r),s}}function Xo(t,e){return tT(t,e)}const sT=async()=>{const t=await Uc(Ue.type);return await fe(t.model),t.model},rT=async(t,e,s)=>{const r=t.resolveNamespace(e);await fe(r);for(const o of s){const n=t.resolveNamespace(o);await fe(n),Tt.set(o,{status:"finished",result:n})}return r},oT=(t,e)=>{const s=[t].flat(),[r,...o]=s,n=Xo(Ue.type,sT),i=s.join("__"),a=Xo(i,()=>rT(n,r,o)),c=g.useMemo(()=>({exists:d=>{const h=e!=null&&e.keyPrefix?`${e.keyPrefix}.${d}`:d;return a?a.exists(h):!1}}),[e==null?void 0:e.keyPrefix,a]);return{t:g.useCallback((d,h)=>{const f=e!=null&&e.keyPrefix?`${e.keyPrefix}.${d}`:d;return a?a.resolveKey(f,h):(m.debug(`Translation model ${t} not ready for key: ${f}`),f)},[e==null?void 0:e.keyPrefix,t,a]),i18n:c}},ih=()=>{const t=Ue.type;return Q({modelId:t,modelType:Ue.type,options:{}})};function nT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=ih();return T.jsx(o,{...r,children:T.jsx(t,{...e,translationContainer:s})})}}const iT=t=>Q({modelId:t,modelType:Rs.type}),Oi=()=>Q({modelId:Lt.type,modelType:Lt.type,options:{}}),aT=({troubleType:t,condition:e})=>{const{model:s}=Oi(),[r,o]=g.useState(!1),[n,i]=g.useState([]),a=g.useCallback(()=>{var c,u;return n.length>0&&((c=n[0])!=null&&c.resolvable)?(u=n[0])==null?void 0:u.resolve():Promise.resolve(void 0)},[n]);return g.useEffect(()=>Y(()=>{const u=(t?s==null?void 0:s.troubles.getIndexByKey("byType",t):s==null?void 0:s.troubles.data)||[],d=e?u.filter(e):u;o(d.length>0),i(d)}),[e,s,t]),[r,a,n.length>0?n[0]:void 0,n]};function cT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Oi();return T.jsx(o,{...r,children:T.jsx(t,{...e,troubleContainer:s})})}}const ah=()=>{const t=Fs.type,e=Q({modelId:t,modelType:Fs.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,r]=g.useState(!1),[o,n]=g.useState(!1),[i,a]=g.useState([]);return g.useEffect(()=>{const c=Y(()=>{var u,d,h;r(((u=e.model)==null?void 0:u.isUsbInserted)??!1),n(((d=e.model)==null?void 0:d.hasAvailableUpdates)??!1),a(((h=e.model)==null?void 0:h.data)??[])});return()=>{c()}},[e.model]),{...e,inserted:s,updateAvailable:o,updates:i}};function lT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=ah();return T.jsx(o,{...r,children:T.jsx(t,{...e,usbUpdateContainer:s})})}}const uT=({path:t,propKey:e})=>{const{status:s}=Q({modelType:Os.type,modelId:t,options:{path:t}}),[r,o]=g.useState(!1),[n,i]=g.useState(),[a,c]=g.useState(""),[u,d]=g.useState(),h=f=>{n&&e&&n.updateProperty(e,f)};return g.useEffect(()=>{var f;s.model&&i(s.model),s.model&&e&&((f=s.model)!=null&&f.props.has(e)?c(s.model.props[e]):d(`property ${e} not found`)),s.ready&&o(s.ready)},[s.ready,s.model,e]),g.useEffect(()=>{e&&M.autorun(()=>{const f=n==null?void 0:n.props[e];c(f||"")})},[n,e]),{config:n,ready:r,value:a,error:u,updateValue:h}},dT=(t,e)=>{switch(e.type){case"UPDATE":return e.payload;default:return t}},ch=({configProperty:t,optionsTransformer:e})=>{const[s,r]=g.useState(!1),[o,n]=g.useState(""),[i,a]=g.useReducer(dT,{value:String(t==null?void 0:t.value),displayValue:t==null?void 0:t.displayValue,significantValue:t==null?void 0:t.significantValue,unit:t==null?void 0:t.unit,options:t==null?void 0:t.options,mappedOptions:[],updateProperty:t==null?void 0:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}),c=g.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&(t==null||t.updateProperty(d))},[t]);return g.useEffect(()=>{async function u(d){try{d&&(await fe(d),r(!0))}catch(h){n(h.message)}}u(t)},[t]),g.useEffect(()=>{const u=Y(()=>{if(t&&s){let d=[];e&&(d=e(t.options)),a({type:"UPDATE",payload:{value:String(t.value),displayValue:t.displayValue,significantValue:t.significantValue,unit:t.unit,options:t.options,mappedOptions:d,updateProperty:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}})}});return()=>{u()}},[t,e,s]),{...i,configSelectProps:{onChange:c,value:i.value,options:e?i.mappedOptions||[]:i.options||[]},ready:s,error:o}};function hT(t,e){const s=e??new Date().getFullYear(),r=[31,28,31,30,31,30,31,31,30,31,30,31];return t===1&&(s%4===0&&s%100!==0||s%400===0)?29:r[t]??0}function fT(t,e){return new Date(t,e,0).getDate()}function lh(t,e){const s=hT(e,t),r=[];for(let o=1;o<=s;o++)r.push(o);return r}function uh(){return[...Array(12).keys()].map(e=>new Date(0,e).getMonth())}function dh(t=[2018,2028]){const e=[];for(let s=t[0];s<=t[1];s++)e.push(s);return e}function hh(t,e=[2018,2028]){const s=dh(e);return t==="long"?s:s.map(r=>Number(r.toString().substring(2)))}function Ii(t="numeric",e="en-US"){const s=new Intl.DateTimeFormat(e,{month:t,timeZone:"UTC"}).format;return[...Array(12).keys()].map(r=>s(new Date(Date.UTC(0,r,1))))}function pT({locale:t="en-US",year:e,month:s,day:r,formatOptions:o={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:n}){const i=s-1,a=new Date(e,i,r),c=new Intl.DateTimeFormat(t,{month:o.month}).format(a),u=new Intl.DateTimeFormat(t,{year:o.year}).format(a),d=new Intl.DateTimeFormat(t,{day:o.day}).format(a);return n?n=="MMDDYY"?`${c} ${d} ${u}`:n==="DDMMYY"?`${d} ${c} ${u}`:n==="YYMMDD"?`${u} ${c} ${d}`:`${u} ${d} ${c}`:new Intl.DateTimeFormat(t,o).format(a)}function we(t){return t.toString().length===2?new Date(Date.parse(`01 Jan 20${t}`)).getFullYear():t}function gT(t){return typeof t=="string"?new Date(Date.parse(`01 ${t.substring(0,3)} 2023`)).getMonth()+1:t}function fh(t,e,s){const r=we(e),o=new Date(r,t,1).getDay(),n=new Date(r,t+1,0).getDate();return[...Array(42).keys()].map(a=>a<o||a>n+o-1?{label:"",value:0,disabled:!0}:s[a-o])}function fs(t,e,s){const r=e-1,o=new Date(t,r,s);return new Date(o).getMonth()===r&&new Date(o).getDate()===s}function ps(t,e){return new Date(t,e,0).getDate()}function ph(t="en-US",e="short"){const s=new Intl.DateTimeFormat(t,{weekday:e}).format;return[...Array(7).keys()].map(r=>s(new Date(Date.UTC(2021,5,r))))}function gh({locale:t="en-US",year:e=new Date().getFullYear(),month:s=new Date().getMonth(),yearRange:r=[2018,2028],daysOfWeekFilter:o=[],formatOptions:{yearFormat:n="long",monthFormat:i="long",dayFormat:a="short"}={}}){const c=$i(n,r),u=mh(n,r,t),d=yh(i,t),h=bh(i,t),f=Ci(e,s),p=vh(e,s,t,o),y=Mh(s,e,p),w=wh(t,a);return{daysArray:f,monthsArray:d,yearsArray:c,yearsOptionsArray:u,monthsOptionsArray:h,daysOptionsArray:p,calendarDayArray:y,dayNamesArray:w}}function $i(t="long",e=[2018,2028]){return g.useMemo(()=>hh(t,e),[t,e])}function mh(t="long",e=[2018,2028],s="en-US"){const r=$i(t,e);return g.useMemo(()=>r.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,r])}function yh(t,e="en-US"){return g.useMemo(()=>Ii(t,e),[t,e])}function bh(t,e="en-US"){const s=g.useMemo(()=>uh(),[]),r=g.useMemo(()=>Ii(t,e),[t,e]);return g.useMemo(()=>[...Array(12).keys()].map(n=>({label:r[n],value:Number(s[n])})),[r,s])}function Ci(t,e){const s=we(t);return g.useMemo(()=>lh(s,e),[e,s])}const mT=(t,e,s,r=[])=>{const o=new Date(t,e,s).getDay();return r.length>0&&r.includes(o)};function vh(t,e,s="en-US",r=[]){const o=Ci(t,e);return g.useMemo(()=>o.map(i=>({label:i.toLocaleString(s),value:i,disabled:mT(t,e,i,r)})),[r,s,e,o,t])}function wh(t="en-US",e="short"){return g.useMemo(()=>ph(t,e),[t,e])}function Eh({year:t=new Date().getFullYear(),month:e=new Date().getMonth(),day:s=new Date().getDate(),formatString:r}){const o=e,n=new Date(t,o,s);return{formattedDate:Ke.format(n,r)}}function Mh(t,e,s){return g.useMemo(()=>fh(t,e,s),[t,e,s])}var Th=(t=>(t.MMDDYY="MMDDYY",t.DDMMYY="DDMMYY",t.YYMMDD="YYMMDD",t.YYDDMM="YYDDMM",t))(Th||{});function yT({locale:t="en-US",date:{year:e=new Date().getFullYear(),month:s=new Date().getMonth(),day:r=new Date().getDate()}={year:new Date().getFullYear(),month:new Date().getMonth(),day:new Date().getDate()},formatOptions:{yearFormat:o="long",monthFormat:n="long",dayFormat:i="short",formatString:a="yyyy/MM/dd"}={},filterOptions:{yearsRange:c=[2018,2028],daysOfWeekFilter:u=[]}={}}){const[d,h]=g.useState(e),[f,p]=g.useState(c),[y,w]=g.useState(s),[E,_]=g.useState(r);g.useEffect(()=>{h(e)},[e]),g.useEffect(()=>{w(s)},[s]),g.useEffect(()=>{_(r)},[r]);const{yearsArray:L,yearsOptionsArray:U,monthsArray:I,monthsOptionsArray:S,daysArray:Z,daysOptionsArray:W,calendarDayArray:le,dayNamesArray:Zt}=gh({locale:t,year:d,yearRange:f,month:y,formatOptions:{yearFormat:o,monthFormat:n,dayFormat:i},daysOfWeekFilter:u}),{formattedDate:Xt}=Eh({year:d,month:y,day:E,formatString:a});return{dateActions:{setYear:h,setYearRange:p,setMonth:w,setDay:_,nextMonth:()=>{const te=y<11?we(d):we(d+1),ue=y<11?y+1:0;if(!fs(te,ue,E)){const Ze=ps(te,ue);_(Ze)}ue===0&&h(te),w(ue)},previousMonth:()=>{const te=we(y===0?d-1:d),ue=y===0?11:y-1;if(!fs(te,ue,E)){const Ze=ps(te,ue);_(Ze)}ue===11&&h(te),w(ue)},nextYear:()=>{const te=d<f[1]?d+1:f[0],ue=we(te);if(fs(ue,y,E))h(te);else{const Ze=ps(we(d+1),y);_(Ze),h(te)}},previousYear:()=>{const te=d>f[0]?d-1:f[0],ue=we(te);if(fs(ue,y,E))h(te);else{const Ze=ps(we(d-1),y);_(Ze),h(te)}}},dateState:{year:d,yearRange:f,month:y,day:E,yearsArray:L,yearsOptionsArray:U,monthsArray:I,monthsOptionsArray:S,daysArray:Z,daysOptionsArray:W,calendarDayNames:Zt,calendarDayArray:le,formattedDate:Xt}}}function _h({date:t=new Date,dateFormat:e,timeFormat:s,options:r={}}){const[o,n]=g.useState("Formatting Time..."),[i,a]=g.useState("Formatting Date..."),c=!!r.ignoreDateFormat,{model:u,ready:d}=Q({modelId:re.type,modelType:re.type,options:{}}),h=typeof t=="string"?Ke.parseISO(t):t;return g.useEffect(()=>{c?a(""):e?a(Ke.format(h,e)):d&&a(Ke.format(h,u!=null&&u.selectedDateFormat?u==null?void 0:u.selectedDateFormat:""))},[c,t,e,h,u,d]),g.useEffect(()=>{s?n(Ke.format(h,s)):d&&n(Ke.format(h,u!=null&&u.selectedTimeFormat?u==null?void 0:u.selectedTimeFormat:""))},[t,s,h,u,d]),{formattedDate:i,formattedTime:o}}const Sh=({secondsFromMidnight:t=0})=>{const[e,s]=g.useState(0),[r,o]=g.useState(0),[n,i]=g.useState(0),[a,c]=g.useState(new Date),{formattedTime:u}=_h({date:a,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const d=Number(t),h=Math.floor(d/3600),f=Math.floor(d%3600/60),p=d%60;s(h),o(f),i(p);const y=new Date;y.setHours(0,0,0,0);const w=new Date(y.getTime()+d*1e3);c(new Date(w))},[t]),{hours:e,minutes:r,seconds:n,formattedTime:u,timeActions:{setHours:s,setMinutes:o,setSeconds:i}}},bT=({configProperty:t})=>{const{value:e}=ch({configProperty:t}),s=parseInt(e||"0",10),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}=Sh({secondsFromMidnight:s}),c=g.useRef();return g.useEffect(()=>{const u=r*3600+o*60+n;return c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{t&&t.updateProperty(u.toString())},100),()=>{c.current&&clearTimeout(c.current)}},[t,r,o,n]),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}};function vT(t,e={}){const{intervalMs:s=5*60*1e3,immediate:r=!0}=e;g.useEffect(()=>{const o=()=>{try{t({__warmup:!0})}catch{}};r&&("requestIdleCallback"in window?requestIdleCallback(o):setTimeout(o,1));const n=s?setInterval(o,s):null;return()=>{n&&clearInterval(n)}},[t,s,r])}const wT=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),ET=(t=wT)=>{const[e,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=Q({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const c=Y(()=>{s((n==null?void 0:n.dateFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),g.useEffect(()=>{const c=Y(()=>{n!=null&&n.dateFormatId&&(n!=null&&n.selectedDateFormat)&&o({id:n==null?void 0:n.dateFormatId,value:n==null?void 0:n.selectedDateFormat})});return()=>{c()}},[n==null?void 0:n.selectedDateFormat,n==null?void 0:n.dateFormatId]);const a=g.useCallback(c=>{var d;let u="";typeof c=="string"?u=c:(d=c==null?void 0:c.target)!=null&&d.value&&(u=c.target.value),u&&(n==null||n.setSelectedDateFormat(u))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(c=>c.id))??[],regionModel:n,selectedDateFormat:(r==null?void 0:r.value)||"",dateFormatId:(r==null?void 0:r.id)||"",updateDateFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)||"",options:e}}},MT=t=>T.jsx("option",{title:t,value:t,children:t},t),Oh="kos:service:region:settings",Ih="timeZone",TT=`${Oh}-${Ih}`,_T=(t=MT)=>{const[e,s]=g.useState([]),[r,o]=g.useState(""),{model:n,ready:i}=Q({modelType:re.type,modelId:re.type,options:{}}),a=ft.factory(TT)({path:Oh,attribute:Ih});g.useEffect(()=>{const u=Y(()=>{s((n==null?void 0:n.timeZones.map(t))||[]),n!=null&&n.timeZones.length&&Zo(n==null?void 0:n.timeZones[0])});return()=>{u()}},[n,i,t]),g.useEffect(()=>{const u=Y(()=>{o(a.value||"")});return()=>{u()}},[a.value]);const c=g.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&Zo(d)},[]);return{options:e,raw:(n==null?void 0:n.timeZones)??[],regionModel:n,selectedTimeZone:r,timeZones:(n==null?void 0:n.timeZones)??[],updateTimeZone:c,selectProps:{onChange:c,value:r,options:e}}},$h="kos:service:region",Ch="regionId",ST=`${$h}-${Ch}`,OT=t=>T.jsx("option",{title:t,value:t,children:t},t),Dh=(t=OT)=>{const[e,s]=g.useState([]),[r,o]=g.useState("factory"),{model:n,ready:i}=Q({modelType:re.type,modelId:re.type,options:{}}),a=ft.factory(ST)({path:$h,attribute:Ch});g.useEffect(()=>{const u=Y(()=>{s((n==null?void 0:n.availableRegions.map(t))||[])});return()=>{u()}},[n,i,t]),g.useEffect(()=>{const u=Y(()=>{o(a.value||"factory")});return()=>{u()}},[a.value]);const c=g.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&Rd(d)},[]);return{raw:(n==null?void 0:n.availableRegions)??[],regionModel:n,regionData:n==null?void 0:n.selectedRegion,selectedRegion:r,updateRegion:c,regionSelectProps:{onChange:c,value:r,options:e}}},IT=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),$T=(t=IT)=>{const[e,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=Q({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const c=Y(()=>{s((n==null?void 0:n.timeFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),g.useEffect(()=>{const c=Y(()=>{n!=null&&n.timeFormatId&&(n!=null&&n.selectedTimeFormat)&&o({id:n==null?void 0:n.timeFormatId,value:n==null?void 0:n.selectedTimeFormat})});return()=>{c()}},[n==null?void 0:n.selectedTimeFormat,n==null?void 0:n.timeFormatId]);const a=g.useCallback(c=>{var d;let u="";typeof c=="string"?u=c:(d=c==null?void 0:c.target)!=null&&d.value&&(u=c.target.value),u&&(n==null||n.setSelectedTimeFormat(u))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(c=>c.id))??[],regionModel:n,selectedTimeFormat:(r==null?void 0:r.value)??"",timeFormatId:(r==null?void 0:r.id)??"",updateTimeFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)??"",options:e}}},CT=(t,e)=>g.useMemo(()=>Rn(t),e),DT={config:{attributes:!0,childList:!0,subtree:!0}};function xT(t,e,s=DT){const[r,o]=g.useState(null);g.useEffect(()=>{if(!e||typeof e!="function")throw new Error("A valid callback function is required");const n=new MutationObserver(e);o(n)},[e,s,o]),g.useEffect(()=>{if(!r)return()=>{};if(!t)throw new Error("A valid DOM element is required");const{config:n}=s;try{r.observe(t,n)}catch(i){m.error(i)}return()=>{r&&r.disconnect()}},[r,t,s])}const xh={validateStart:function(t){return!0},validateStop:function(t){const e=t.event.currentTarget.getBoundingClientRect(),[s,r]=t.xy;return s<e.left||s>e.right||r<e.top||r>e.bottom}},Ro=m.createLogger({name:"usePressGesture",group:"kos-hooks"});function AT({onPressed:t,onRelease:e,intersectionStrategy:s=xh}){const r=g.useRef(!1),o=Hh.useGesture({onDragStart:c=>{Ro.info("onDragStart",c.type),s.validateStart(c)&&(t&&t(),r.current=!0)},onDrag:c=>{Ro.info("onDrag",c.type),r.current&&s.validateStop(c)&&(e&&e(),r.current=!1)},onDragEnd:c=>{Ro.info("onDragEnd",c.type),r.current&&e&&(e(),r.current=!1)}}),n=()=>{t&&t(),r.current=!0},i=()=>{r.current&&e&&(e(),r.current=!1)},a=()=>{r.current&&e&&(e(),r.current=!1)};return{dom:o,mesh:()=>({onPointerDown:n,onPointerUp:i,onPointerOut:a})}}const Ah=()=>{const[t,e]=g.useState(!1),s=O.getInstance();return g.useEffect(()=>{const r=Y(()=>{s&&s.reloading!==t&&e(s.reloading)});return()=>{r()}},[s,t]),[t]};function Rh(t=!1,e="2-digit"){return g.useMemo(()=>{const s=t?12:24;return Array.from({length:s},(r,o)=>{const n=t&&o===0?12:o%s;return{id:o,label:e==="2-digit"?n.toString().padStart(2,"0"):n.toString()}})},[e,t])}function Jo(t,e="2-digit",s=0,r=0){return g.useMemo(()=>Array.from({length:t},(o,n)=>{const i=String(n+s);return{id:n+r,label:e==="2-digit"?i.padStart(2,"0"):i}}),[t,s,r,e])}function Ph(t="en-US"){return g.useMemo(()=>["AM","PM"].map(e=>{const s=new Intl.DateTimeFormat(t,{hour:"2-digit",hour12:!0}).formatToParts(new Date().setHours(e==="AM"?0:12))[2].value;return{id:s,label:s}}),[t])}function kh({formatOptions:{hour12:t=!0,hour:e="2-digit",minute:s="2-digit",second:r="2-digit"}={hour12:!0,hour:"2-digit",minute:"2-digit",second:"2-digit"},locale:o="en-US"}){const n=Rh(t,e),i=Jo(60,s),a=Jo(60,r),c=Ph(o);return{hourOptions:n,minuteOptions:i,secondOptions:a,amPmOptions:c}}function Lh(t,e){return Ke.format(t,e)}function Fh({formatOptions:t,initialDate:e=new Date,locale:s="en-US",format:r="HH:mm"}){const[o,n]=g.useState(e),i=g.useCallback(w=>{n(E=>{const _=new Date(E);return _.setHours(Number(w)),_})},[]),a=g.useCallback(w=>{n(E=>{const _=new Date(E);return _.setMinutes(Number(w)),_})},[]),c=g.useCallback(w=>{n(E=>{const _=new Date(E);return _.setSeconds(Number(w)),_})},[]),u=g.useCallback(w=>{const E=new Date(w);n(E)},[]),d=Lh(o,r),{hourOptions:h,minuteOptions:f,secondOptions:p,amPmOptions:y}=kh({formatOptions:t,locale:s});return{amPmOptions:y,formattedTime:d,hourOptions:h,minuteOptions:f,secondOptions:p,setHours:i,setMinutes:a,setSeconds:c,setTime:u,time:new Date(o)}}const RT=t=>{const{regionModel:e}=Dh(),s=g.useMemo(()=>({hour12:e==null?void 0:e.is12HourTimeFormat}),[e==null?void 0:e.is12HourTimeFormat]);return Fh({...t,locale:e==null?void 0:e.regionId,format:e==null?void 0:e.selectedTimeFormat,formatOptions:s})};function PT(t){return e=>{const[s]=Ah();return s?T.jsx(Hd,{message:"Wait a moment while your project reloads..."}):T.jsx(t,{...e})}}const Ta=m.createLogger({name:"studio-properties-service",group:"Services"}),kT="/api/kos/studio/properties",Nh=async t=>{if(Ta.debug("sending GET for studio-properties"),!t)throw Ta.error("connectionId is undefined"),new Error("connectionId is undefined");return await Ae.get(kT,{},{destinationAddress:t,timeout:500})},LT=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:Nh},Symbol.toStringTag,{value:"Module"}));var FT=Object.getOwnPropertyDescriptor,NT=(t,e,s,r)=>{for(var o=r>1?void 0:r?FT(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Uh="studio-properties-model",UT="/kos/studio/properties",_a={"kos.studio.tool.legacy":1};let en=class{constructor(t,e,s){l(this,"id");l(this,"connectionId");l(this,"unsubscribe",null);l(this,"logger");l(this,"data");this.id=t,this.logger=s.logger,this.data=Ie(),this.connectionId=e.connectionId}async init(){this.logger.debug(`initializing studio-properties ${this.id}`)}async load(){this.logger.debug(`loading studio-properties ${this.id}`)}async terminatePropertiesSession(){var t;(t=this.unsubscribe)==null||t.call(this)}async initializePropertiesSession(){this.unsubscribe=Ct.getInstance().subscribeTopic({topic:UT,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[t,e]=await Nh(this.connectionId);if(t){this.logger.error(`Error loading studio-properties: ${t}`),this.data.setValues(_a);return}if(e){const s=Object.keys(e).reduce((r,o)=>(r[o]=e[o]??o,r),{});this.data.setValues(s??_a),m.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(t){return this.data[t]}createObservableProperty(t){return Rn(()=>this.get(t))}};en=NT([R(Uh)],en);const jT=new ve({class:en,type:Uh});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>M.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>M.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>sn.observer});exports.AuthState=_l;exports.BrowserKosRouter=Dl;exports.BrowserRouter=zn;exports.CanvasDispatcher=Nt;exports.CanvasDispatcherServices=Aw;exports.CanvasRenderer=li;exports.CanvasStreamer=LM;exports.CanvasStreamerBase=eh;exports.ChildModels=ze;exports.CompanionParentModel=Ve;exports.ConfigBean=Os;exports.ContainerAwareSetup=Tn;exports.CoreExtensionManager=CE;exports.CoreModels=mi;exports.CreateModelTranslationsContext=Wd;exports.CreateModelTranslationsProvider=pM;exports.DateDisplayFormat=Th;exports.DateHelpers=of;exports.DependencyLifecycle=x;exports.DependencyModels=F;exports.DependencyResolutionPolicy=qe;exports.Device=jr;exports.DeviceServices=eE;exports.DomIntersectionStrategy=xh;exports.EVENT_KOS_MODEL_READY=an;exports.EVENT_TROUBLE_ADDED=Xm;exports.EVENT_TROUBLE_REMOVED=Jm;exports.EXTENSION_CANVAS_RENDERER=ee;exports.EXTENSION_FEATURE_FLAG_RESOLVER=vc;exports.EXTENSION_TROUBLE_DATA_MAPPER=Ir;exports.EXTENSION_TROUBLE_MAPPER=Ys;exports.ErrorBoundaryWithFallback=Kd;exports.EventBus=Vh;exports.EventBusFunctional=Yh;exports.EventBusState=Qh;exports.ExtensionManager=$;exports.FUTURE_CONTAINER_MODEL_TYPE=ou;exports.FUTURE_MODEL_TYPE=Yl;exports.FUTURE_NOT_ASSIGNED=kn;exports.FeatureFlagService=wc;exports.FetchError=ye;exports.FutureAliases=bs;exports.FutureContainerFactory=Ye;exports.FutureContainerModel=iu;exports.FutureContainerSetup=vn;exports.FutureEndState=Ge;exports.FutureFactory=zt;exports.FutureHandler=Xr;exports.FutureManager=ct;exports.FutureModel=eu;exports.FutureService=gs;exports.HEADER_CACHE_CONTROL=Da;exports.HEADER_CONTENT_TYPE=Ca;exports.HEADER_DESTINATION_ADDR=je;exports.HEADER_FOS_REQUEST_ID=xa;exports.HEADER_METHOD=qr;exports.HEADER_ORDERED=on;exports.HEADER_REQUEST_ID=Ns;exports.HEADER_REQUEST_TYPE=Ce;exports.HEADER_RESPONSE_ID=zr;exports.HEADER_SOURCE_ADDR=$a;exports.HEADER_TOPIC=Ia;exports.HEADER_URL=Bt;exports.HEADER_WORK_TRACKER=nn;exports.HttpRouteHandlers=ke;exports.KOS_EXECUTION_CONTEXT=Qr;exports.KOS_MODEL_ID=gr;exports.KOS_SERVICE=FE;exports.KOS_SERVICE_1_6_5=RE;exports.KOS_SERVICE_1_8_1=kE;exports.KeyValue=Yn;exports.KeyValueServices=Gy;exports.Kos=ae;exports.KosConfigPropertySpec=ft;exports.KosContainerIndex=Sn;exports.KosContextBean=$l;exports.KosContextManager=G;exports.KosCore=O;exports.KosCoreModelPropertyMapper=Ee;exports.KosDataContainer=An;exports.KosDependencyTypes=Jf;exports.KosExpressionEvaluator=yu;exports.KosExtensionUtils=lf;exports.KosFeatureFlags=Ec;exports.KosFetchMethods=Pc;exports.KosGlobalConfig=yn;exports.KosHttpRouteManager=Cn;exports.KosLog=m;exports.KosLogManager=wu;exports.KosLogManagerServices=ev;exports.KosMockEvents=Pa;exports.KosModel=El;exports.KosModelCollectionProvider=lM;exports.KosModelContainer=xe;exports.KosModelContext=po;exports.KosModelEvents=k;exports.KosModelFactory=ws;exports.KosModelLoader=Gd;exports.KosModelLoaderDisplay=Yd;exports.KosModelManager=Tl;exports.KosModelProvider=qd;exports.KosModelRegistrationFactory=ve;exports.KosModelRegistry=Qo;exports.KosModelState=v;exports.KosModelSymbol=bn;exports.KosModelVisitor=Tm;exports.KosObservableData=Fc;exports.KosRegistration=zm;exports.KosSingletonRegistration=Vm;exports.KosTime=_r;exports.KosTimeContext=Mi;exports.KosTimeProvider=MM;exports.KosTimeServices=av;exports.KosTimer=Pd;exports.KosToken=Cl;exports.KosTranslationProvider=CM;exports.KosTranslations=rd;exports.KosWSTransportStatus=wl;exports.KosWsEvents=Us;exports.LOADER_FEATURE_FLAG=Mf;exports.LOGIN_HOST=Aa;exports.LOGIN_URL=Kh;exports.LoadingMessage=Hd;exports.LogBlock=As;exports.LogBlockContainer=lo;exports.LogConfig=ys;exports.LogStream=_s;exports.LogStreamContainer=Gs;exports.LogStreamServices=bv;exports.LoggerSetup=Mn;exports.MODEL_DELETION_DELAY=Ml;exports.MiddlewareChain=Sl;exports.ModelEffects=it;exports.ModelError=Xc;exports.MultipleFutureContainerSetup=wn;exports.MultipleFutureHandler=kc;exports.NestedModelContext=go;exports.NetworkInterface=hi;exports.NetworkInterfaceContainer=ks;exports.NetworkInterfaceServices=lE;exports.ObservableData=Ie;exports.OptionsRequired=Hs;exports.Ota=Cr;exports.OutsideAlerter=zM;exports.PLUGIN_EXTENSION_NAME=uf;exports.PORT=Ra;exports.PROFILE_ENABLE_RELEASES=hf;exports.PROFILE_LOG_DEBUG=lc;exports.PROFILE_LOG_INFO=uc;exports.PROFILE_RELAX_STORE_VALIDATION=ff;exports.PROFILE_TOOLS_PREVIEW=cc;exports.ParentModel=ms;exports.PluginExtensionManager=df;exports.ProgressBar=nM;exports.ReferenceConfig=cr;exports.RegionInfo=re;exports.RegionServices=ly;exports.RegistrationManager=A;exports.Registry=$E;exports.ReplayStrategy=nt;exports.ResponseRetention=se;exports.STATUS=rn;exports.ServiceFactory=oe;exports.ServiceRequestHandlers=at;exports.SingletonKosModelRegistrationFactory=Se;exports.SoftwareInfo=Dr;exports.SoftwareInfoContext=_i;exports.SoftwareInfoProvider=SM;exports.SoftwareInfoServices=ew;exports.StateActionHandlers=Sf;exports.StateBean=Ps;exports.StateBeanServices=nw;exports.StateEntryHandlers=St;exports.StateExitHandlers=vs;exports.StateMachineSetup=Bs;exports.StateProp=ni;exports.StatePropServices=gw;exports.StorageDevice=Hr;exports.StorageDeviceContainer=Ut;exports.StorageDeviceServices=pE;exports.StudioProperties=jT;exports.StudioPropertiesServices=LT;exports.SubscriptionHandlers=J;exports.TIMER_END=vi;exports.TIMER_EVENT=yi;exports.TOPIC_TIMER_TICK_EVENT=bi;exports.TimerManager=kd;exports.TokenContext=Jd;exports.TokenProvider=IM;exports.Topics=Ts;exports.Trans=eT;exports.TransitionMap=ur;exports.Transitions=In;exports.Translation=Rr;exports.TranslationContainer=Ue;exports.TranslationContainerContext=Si;exports.TranslationContext=Sw;exports.TransportFactory=Uo;exports.Trouble=Rs;exports.TroubleAwareSetup=En;exports.TroubleContainer=Lt;exports.TroubleServices=Fv;exports.Troubles=me;exports.UsbUpdate=gi;exports.UsbUpdateContainer=Fs;exports.UsbUpdateServices=ME;exports.VFS_SERVICE=KE;exports.VFS_SERVICE_1_6_5=UE;exports.VFS_SERVICE_1_8_1=BE;exports.WS_EVENT_TYPE=od;exports.WebSocketEvents=Ms;exports.WebSocketTransport=Ct;exports.WsEventFactory=ai;exports.acceptOrgInvitation=Bd;exports.addDaysToDate=ec;exports.addFuture=Ql;exports.addMonthsToDate=Ja;exports.api=tu;exports.applyMixins=Xh;exports.arraysEqual=Jh;exports.buildConfigBeanModel=sy;exports.buildFuture=qn;exports.buildFutureModel=Xl;exports.cancelFuture=Zl;exports.checkAppsStarted=Qm;exports.checkWildcardPattern=Vc;exports.clearAllServiceResponses=Um;exports.clearPath=Nm;exports.clearServiceResponse=Fm;exports.convert=jn;exports.convertFileSizeRaw=Zh;exports.convertWithUnits=gy;exports.createBaseMessage=dl;exports.createBroadcastMessageResponse=gl;exports.createCancellablePromise=JE;exports.createClient=Be;exports.createFosBaseMessage=ul;exports.createHeaders=ss;exports.createKosHtpMessageResponse=ml;exports.createKosMessage=fl;exports.createKosMessageResponse=yl;exports.createMessageBody=Qe;exports.createModelDependency=tl;exports.createOptionKey=Gf;exports.createPropKey=dt;exports.createReadableStream=rs;exports.createStudioMessage=ll;exports.createStudioMessageRequest=hl;exports.createStudioMessageResponse=pl;exports.debounce=ic;exports.del=Cc;exports.deleteFuture=Wl;exports.destroyKosModel=Oe;exports.evaluateScopes=Nl;exports.executeChildrenModelLifecycle=ol;exports.executeDependentModelLifecycle=ts;exports.executeListLifecycle=rl;exports.fetchModel=jM;exports.findModel=vp;exports.findModels=jc;exports.formatDate=rc;exports.formatDateSince=Xa;exports.formatDateTime=nc;exports.formatTime=oc;exports.get=$c;exports.getAllKosCompanionModels=Bc;exports.getCalendarMonthArray=fh;exports.getConfigBean=Fl;exports.getDayStrings=ph;exports.getDays=fT;exports.getDaysArray=lh;exports.getDaysInMonth=mn;exports.getDependenciesByLifecycle=sl;exports.getFormattedDate=pT;exports.getFormattedMonth=gT;exports.getFormattedMonthsArray=Ii;exports.getFormattedYear=we;exports.getFormattedYearsArray=hh;exports.getFutures=Ay;exports.getHttpRouteHandlers=Dc;exports.getKosCompanionModel=wp;exports.getKosLocalizationDescriptor=Xu;exports.getKosMessageLogging=pc;exports.getKosModel=Uc;exports.getKosModelSync=$e;exports.getKosModelType=bp;exports.getKosSessionKey=Il;exports.getLastDayOfMonth=ps;exports.getLocalizationDescriptor=yw;exports.getLogLevel=fc;exports.getLogMessageToStudio=gc;exports.getMessageBody=No;exports.getMonthsArray=uh;exports.getObservableCompanions=Ep;exports.getQueryParams=be;exports.getServiceResponse=km;exports.getStartedApps=Zm;exports.getTranslations=Zu;exports.getYearsArray=dh;exports.hasCachedResponse=Lm;exports.hasDecimals=kl;exports.hasHttpRouteHandlers=yr;exports.hasKosProfile=Po;exports.hslStringToHex=Tc;exports.hslToHex=Mc;exports.httpDelete=tp;exports.initKosProvider=mM;exports.initializeStateMachine=Oc;exports.injectStateMachineSupport=Sc;exports.isBoolean=Fn;exports.isKosCompanionTypeFactory=Yc;exports.isKosDataModel=Es;exports.isKosExecutionContext=_n;exports.isKosLoggingEnabled=mf;exports.isKosModel=_e;exports.isKosModelContainer=$n;exports.isKosModelReady=br;exports.isLeapYear=gn;exports.isLocalRefId=Bm;exports.isNumber=Jr;exports.isPrintable=ng;exports.isTroubleAware=Ow;exports.isValidDate=fs;exports.kosAction=X;exports.kosAutoEffect=Y;exports.kosChild=De;exports.kosCompanion=Wf;exports.kosComputed=Rn;exports.kosConfigBean=eo;exports.kosConfigProperty=Sy;exports.kosContainerAware=Ic;exports.kosContext=Qf;exports.kosDependency=Ht;exports.kosEffect=Rl;exports.kosFuture=wi;exports.kosFutureAware=Zf;exports.kosLogger=sp;exports.kosLoggerAware=Ac;exports.kosModel=R;exports.kosModelEffect=Rc;exports.kosMultipleFutureAware=Xf;exports.kosObservable=Pn;exports.kosParentAware=Wr;exports.kosReference=rp;exports.kosServiceRequest=ht;exports.kosStateBean=GE;exports.kosStateEntry=lp;exports.kosStateExit=up;exports.kosStateGuard=dp;exports.kosStateMachine=cp;exports.kosStateProp=YE;exports.kosSubscribe=kp;exports.kosTopicHandler=B;exports.kosTroubleAware=hp;exports.kosWhen=Bo;exports.login=Nd;exports.mapConfigBeanModelToDto=Hl;exports.mapDataToModel=ko;exports.mapDtoToConfigBeanModel=jl;exports.mapDtoToFutureModel=Kn;exports.mapDtoToFutureOptions=Hn;exports.mapUpdateDtoToConfigBeanModel=Bl;exports.modelEventTopicFactory=Wc;exports.modelFactory=Kt;exports.modelTypeEventTopicFactory=Qc;exports.modifyConfigBean=Ll;exports.modifyFuture=Ry;exports.pairedClientHeartbeat=Im;exports.parseWildcardSegment=zc;exports.pipe=Ol;exports.post=Ks;exports.preloadKosModel=_p;exports.processId=rf;exports.processMiddleware=_m;exports.put=ep;exports.registerCompanionModel=Tp;exports.registerCoreModels=Dd;exports.registerExtensionPoint=js;exports.registerHttpRoutes=bg;exports.registerKosModel=Kc;exports.registerLegacyModel=Hc;exports.resetKosModel=yp;exports.resetPassword=jd;exports.resolveBaseUrl=il;exports.resolveChild=el;exports.resolveContainerDeltas=ef;exports.resolveItemListDeltas=sf;exports.resolveKosCompanion=Lo;exports.resolveKosContext=qm;exports.resolveKosProfiles=hc;exports.resolveListDeltas=tf;exports.resolveServiceUrl=ce;exports.resolveVariable=_c;exports.retryWithExponentialBackoff=Cm;exports.sendAsyncIntent=Ym;exports.sendBroadcastMessage=Fg;exports.sendIntent=Gm;exports.sendKosHttpMessageResponse=vl;exports.sendKosMessage=Pg;exports.sendKosMessageResponse=bl;exports.sendRequest=Hm;exports.sendStudioMessage=Lg;exports.sendStudioMessageRequest=kg;exports.startPasswordReset=Ud;exports.stringComponentInsert=nh;exports.studioAcceptOrgInvitation=XE;exports.studioLogin=WE;exports.studioResetPassword=ZE;exports.studioStartPasswordReset=QE;exports.subscribeStore=DE;exports.syncPublish=Km;exports.troubleByTypeReducer=Lc;exports.troubleDataFactory=Bu;exports.unloadKosModel=mp;exports.updateCompanionModelRegistration=Om;exports.updateModelRegistration=Sm;exports.updateRegion=Rd;exports.updateTimeZone=Zo;exports.useAmPmValues=Ph;exports.useCalendarDayArray=Mh;exports.useConfigBean=uT;exports.useConfigProperty=ch;exports.useContextModel=aM;exports.useContextModelHierarchy=Vd;exports.useDateArrays=gh;exports.useDateProps=yT;exports.useDateRelativeConfig=bT;exports.useDateRelativeData=Sh;exports.useDayNames=wh;exports.useDayOptions=vh;exports.useDays=Ci;exports.useDevice=th;exports.useFormattedDate=Eh;exports.useFormattedTime=Lh;exports.useFunctionWarmup=vT;exports.useHourValues=Rh;exports.useKosCore=Zd;exports.useKosDateFormats=ET;exports.useKosModel=Q;exports.useKosRegions=Dh;exports.useKosTime=Ei;exports.useKosTimeContext=TM;exports.useKosTimeFormats=$T;exports.useKosTimeZones=_T;exports.useKosTranslation=oT;exports.useKosTranslationContext=DM;exports.useLocalComputed=CT;exports.useModelFromHierarchy=dM;exports.useMonths=yh;exports.useMonthsOptions=bh;exports.useMutationObserver=xT;exports.useNetworkInterfaceContainer=sh;exports.useOta=rh;exports.usePressGesture=AT;exports.useProjectReload=Ah;exports.useRegionTimeProps=RT;exports.useRegionalTimeDate=_h;exports.useSoftwareInfo=Ti;exports.useSoftwareInfoContext=OM;exports.useStateProperty=VM;exports.useStorageDeviceContainer=oh;exports.useSuspenseData=Xo;exports.useTimeOptions=kh;exports.useTimeProps=Fh;exports.useTimeValues=Jo;exports.useTimer=YM;exports.useTranslationContainer=ih;exports.useTroubleContainerModel=Oi;exports.useTroubleModel=iT;exports.useTroublePresence=aT;exports.useUsbUpdateContainer=ah;exports.useYears=$i;exports.useYearsOptions=mh;exports.uuid=ut;exports.variableToHex=Tf;exports.waitForAppToStart=Wm;exports.waitForAppsToStart=Al;exports.waitForRequest=xn;exports.whenReady=fe;exports.withDevice=UM;exports.withKosTime=BM;exports.withNetworkInterfaceContainer=HM;exports.withOta=KM;exports.withProjectReloading=PT;exports.withSoftwareInfo=_M;exports.withStorageDeviceContainer=GM;exports.withTranslationContainer=nT;exports.withTroubleContainer=cT;exports.withUsbUpdateContainer=lT;exports.wrapPromise=hn;
228
228
  //# sourceMappingURL=index.cjs.map