@kosdev-code/kos-ui-sdk 0.1.0-dev.5053 → 0.1.0-dev.5072
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/core/core/decorators/index.d.ts +2 -0
- package/core/core/decorators/index.d.ts.map +1 -1
- package/core/core/decorators/kos-execution-context.d.ts +60 -0
- package/core/core/decorators/kos-execution-context.d.ts.map +1 -0
- package/core/core/decorators/kos-service-request.d.ts +381 -0
- package/core/core/decorators/kos-service-request.d.ts.map +1 -0
- package/core/core/decorators/kosTopicHandler.d.ts +33 -5
- package/core/core/decorators/kosTopicHandler.d.ts.map +1 -1
- package/core/core/kosModel.d.ts +2 -0
- package/core/core/kosModel.d.ts.map +1 -1
- package/core/core/model/kos-model-component-factory.d.ts +4 -0
- package/core/core/model/kos-model-component-factory.d.ts.map +1 -1
- package/core/core/model/kos-offline-queue.d.ts +78 -1
- package/core/core/model/kos-offline-queue.d.ts.map +1 -1
- package/core/core/model/kos-service-request-manager.d.ts +102 -0
- package/core/core/model/kos-service-request-manager.d.ts.map +1 -0
- package/core/core/model/kos-subscription-manager.d.ts +18 -0
- package/core/core/model/kos-subscription-manager.d.ts.map +1 -1
- package/core/core/model/model-introspection-utils.d.ts +1 -0
- package/core/core/model/model-introspection-utils.d.ts.map +1 -1
- package/core/core/model/service-response-store.d.ts +164 -0
- package/core/core/model/service-response-store.d.ts.map +1 -0
- package/core/types/index.d.ts +1 -0
- package/core/types/index.d.ts.map +1 -1
- package/core/types/service-response-store.d.ts +152 -0
- package/core/types/service-response-store.d.ts.map +1 -0
- package/core/util/index.d.ts +1 -0
- package/core/util/index.d.ts.map +1 -1
- package/core/util/kos-service-request.d.ts +8 -0
- package/core/util/kos-service-request.d.ts.map +1 -1
- package/core/util/service-response.d.ts +110 -0
- package/core/util/service-response.d.ts.map +1 -0
- package/index.cjs +77 -77
- package/index.cjs.map +1 -1
- package/index.js +7721 -6766
- package/index.js.map +1 -1
- package/models/decorators/future-service.d.ts +7 -0
- package/models/decorators/future-service.d.ts.map +1 -1
- package/models/utils/service.d.ts +58 -2
- package/models/utils/service.d.ts.map +1 -1
- package/package.json +2 -2
package/index.cjs
CHANGED
|
@@ -1,83 +1,83 @@
|
|
|
1
|
-
"use strict";var mh=Object.defineProperty;var yh=(e,t,s)=>t in e?mh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var l=(e,t,s)=>(yh(e,typeof t!="symbol"?t+"":t,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("loglevel"),E=require("mobx"),y=require("robot3"),je=require("date-fns"),T=require("@emotion/react/jsx-runtime"),No=require("@emotion/styled"),sa=require("react-dom"),qe=require("@emotion/react"),g=require("react"),Uo=require("mobx-react-lite"),bh=require("@use-gesture/react"),Sr="method",ra="topic",At="url",Is="request-id",$r="response-id",jo="status",Le="dst-addr",oa="src-addr",Oe="type",Bo="ordered",Ko="tracker",na="Content-Type",ia="Cache-Control",aa="requestId",ca=process.env.KOS_LOGIN_URL||"http://localhost",la=process.env.KOS_APP_PORT||"8080",vh=`${ca}:${la}`,Xs="{MODEL_ID}";var Ss=(e=>(e.SEND="/ws/log/msg/send",e.RECEIVED="/ws/log/msg/receive",e))(Ss||{}),ua=(e=>(e.MSG_RECEIVE="/mock/msg/receive",e))(ua||{});const Ho="/kos/model/ready/";C.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const K=globalThis.kos.subscriptions,wh=()=>Symbol("eventKey");function zo(e){return K[e]&&Object.getOwnPropertySymbols(K[e]).length>0}function $(e,t){const s=wh();return K[e]||(C.debug(`Initializing subscription for ${e}`),K[e]={}),C.debug(`Subscribing to ${e} with id ${s.toString()}`),K[e][s]=t,{count:K[e]?Object.getOwnPropertySymbols(K[e]).length:0,unsubscribe:()=>(C.debug(`Unsubscribing from ${e} with id ${s.toString()}`),K[e]&&K[e][s]&&delete K[e][s],K[e]&&Object.getOwnPropertySymbols(K[e]).length===0&&delete K[e],{count:K[e]?Object.getOwnPropertySymbols(K[e]).length:0})}}function z(e,t,s={}){if(!K[e]||Object.getOwnPropertySymbols(K[e]).length===0)return C.debug(`No subscriptions for ${e}. Not publishing.`),{eventType:e,subscribers:0};const r=Object.getOwnPropertySymbols(K[e]).length;return Object.getOwnPropertySymbols(K[e]).forEach(o=>{if(s.sync){const n=s.sync;C.debug(`Performing sync publish for ${e} with sync id ${n}`),K[e][o]({body:t,headers:s}).then(i=>{C.debug(`Response recieved for ${n}, publishing back to source.`),z(n,i)})}else C.debug(`Performing async publish for ${e}`),K[e][o]({body:t,headers:s})}),{eventType:e,subscribers:r}}function Eh(){C.warn("Resetting event bus"),Object.keys(K).forEach(e=>delete K[e])}function da(e,t){const s=$(e,r=>{s.unsubscribe(),t(r)});return s.unsubscribe}function Go(e,t){return new Promise((s,r)=>{let o=null;const n=da(e,i=>{o&&clearTimeout(o),s(i)});t&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${e}`))},t))})}const Mh=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:zo,once:da,publish:z,reset:Eh,subscribe:$,waitFor:Go},Symbol.toStringTag,{value:"Module"}));function Cr(e,t){const s=$(e,r=>{s.unsubscribe(),t(r)});return s.unsubscribe}function Dr(e,t){return new Promise((s,r)=>{let o=null;const n=Cr(e,i=>{o&&clearTimeout(o),s(i)});t&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${e}`))},t))})}function ha(e,t){const s=e.map(r=>Dr(r,t));return Promise.all(s)}function fa(e,t){return new Promise((s,r)=>{const o=[];let n=null,i=!1;const a=()=>{o.forEach(c=>c()),n&&clearTimeout(n)};e.forEach(c=>{const u=Cr(c,d=>{i||(i=!0,a(),s({eventType:c,data:d}))});o.push(u)}),t&&(n=setTimeout(()=>{i||(i=!0,a(),r(new Error(`Timeout waiting for any event: ${e.join(", ")}`)))},t))})}function pa(e,t,s){return $(e,o=>{o&&t(o)&&s(o)}).unsubscribe}function ga(e,t,s){return $(e,o=>{if(o){const n=t(o);s(n)}}).unsubscribe}function ma(e,t,s){let r=null;const o=$(e,n=>{r&&clearTimeout(r),r=setTimeout(()=>{s(n)},t)});return()=>{r&&clearTimeout(r),o.unsubscribe()}}function ya(e,t,s){let r=0,o=null;const n=$(e,i=>{const a=Date.now(),c=a-r;c>=t?(r=a,s(i)):o||(o=setTimeout(()=>{r=Date.now(),s(i),o=null},t-c))});return()=>{o&&clearTimeout(o),n.unsubscribe()}}function ba(e,t,s){let r=[],o=null;const n=()=>{r.length>0&&(s([...r]),r=[])},i=$(e,a=>{a&&(r.push(a),o||(o=setTimeout(()=>{n(),o=null},t)))});return()=>{o&&(clearTimeout(o),n()),i.unsubscribe()}}function Vo(e,t=1){const s=[];return $(e,r=>{r&&(s.push(r),s.length>t&&s.shift())}),{subscribe:r=>(s.forEach(o=>r(o)),$(e,r))}}function va(e,t){const s=e.map(r=>$(r,o=>{o&&t(r,o)}));return()=>{s.forEach(r=>r.unsubscribe())}}function wa(e,t){let s=e;const r=[],o=new Set;return Object.values(t).forEach(n=>{Object.keys(n).forEach(i=>{o.add(i)})}),o.forEach(n=>{const{unsubscribe:i}=$(n,a=>{const c=t[s];c&&c[n]&&(s=c[n](a))});r.push(i)}),{get state(){return s},unsubscribe:()=>{r.forEach(n=>n())}}}function Ea(e,t,s,r){const o=Dr(t,r);return z(e,s),o}async function*Ma(e){const t=[],s=[],r=$(e,o=>{o&&(s.length>0?s.shift()(o):t.push(o))});try{for(;;)t.length>0?yield t.shift():yield await new Promise(o=>{s.push(o)})}finally{r.unsubscribe()}}const Th={once:Cr,waitFor:Dr,waitForAll:ha,race:fa,filter:pa,map:ga,debounce:ma,throttle:ya,buffer:ba,replay:Vo,merge:va,stateMachine:wa,request:Ea,eventIterator:Ma},_h=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:Th,buffer:ba,debounce:ma,eventIterator:Ma,filter:pa,map:ga,merge:va,once:Cr,race:fa,replay:Vo,request:Ea,stateMachine:wa,throttle:ya,waitFor:Dr,waitForAll:ha},Symbol.toStringTag,{value:"Module"}));async function xr(e,t){const{getCurrentState:s,transformState:r,shouldUseFetchedState:o,timeout:n}=t,i=Go(e,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 Ta(e,t,s){const{getCurrentState:r,transformState:o}=s;let n=!1;const i=$(e,a=>{a&&(n=!0,t(a))});return Promise.resolve(r()).then(a=>{const c=o?o(a):a;n||t(c)}).catch(a=>{console.error("Failed to fetch initial state:",a)}),i.unsubscribe}function _a(e,t){let s;const r=new Set,o=async()=>{try{typeof t=="string"?s=await(await fetch(t)).json():s=await t(),r.forEach(a=>a(s))}catch(a){throw console.error("Failed to fetch initial state:",a),a}};$(e,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 Yo(e,t){if(typeof e=="string")return xr(e,t);const s=e,{getCurrentState:r,shouldUseFetchedState:o,timeout:n}=t,i=await r(),a=t.transformState?t.transformState(i):i;if(o&&o(a))return a;const c=s.map(d=>Go(d,n)),u=await Promise.all(c);return u[u.length-1]}function Oa(e,t,s){const{fetchMissedEvents:r,checkInterval:o=3e4,deduplicateById:n}=s,i=new Set,a=$(e,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 t(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 t(h))}else await t(h)}catch(u){console.error("Failed to fetch missed events:",u)}},o);return()=>{a.unsubscribe(),clearInterval(c)}}function Ia(e){const{connectEvent:t,disconnectEvent:s,errorEvent:r,dataEvent:o,fetchInitialState:n,reconnectDelay:i=5e3}=e,a={state:"disconnected",data:void 0,async waitForConnection(d){if(a.state==="connected"&&a.data)return a.data;const h=await xr(t,{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 $(t,d=>{a.state="connected",d!=null&&d.body&&(a.data=d.body),u()}),$(s,()=>{a.state="disconnected",u(),setTimeout(()=>{a.state==="disconnected"&&a.reconnect()},i)}),r&&$(r,()=>{a.state="error",u()}),o&&$(o,d=>{d!=null&&d.body&&a.state==="connected"&&(a.data=d.body,u())}),a.reconnect(),a}const Oh={waitForOrGetState:xr,subscribeWithInitialState:Ta,createStatefulEventStream:_a,waitForAllWithState:Yo,createResilientEventHandler:Oa,createConnectionStateManager:Ia},Ih=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:Oh,createConnectionStateManager:Ia,createResilientEventHandler:Oa,createStatefulEventStream:_a,subscribeWithInitialState:Ta,waitForAllWithState:Yo,waitForOrGetState:xr},Symbol.toStringTag,{value:"Module"})),Sh=(e,t=0)=>{if(!+e)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,r=t<0?0:t,o=["bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(e)/Math.log(s)),i=parseFloat((e/Math.pow(s,n)).toFixed(r)),a=o[n];return{value:i,scale:a,toString:()=>`${i} ${a}`}};function qo(e){let t="pending",s;const r=e.then(n=>{t="success",s=n},n=>{t="error",s=n});return{read:()=>{switch(t){case"pending":throw r;case"error":throw s;default:return s}}}}function tt(){return"xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0;return(e=="x"?t:t&3|8).toString(16)})}function $h(e,t){t.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(r=>{const o=Object.getOwnPropertyDescriptor(s.prototype,r);Object.defineProperty(e.prototype,r,o)})})}function Ch(e,t){const s=e??[],r=t??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const Wo=(e,t)=>{const s=e.map(n=>n.id);return t.map(n=>n.id).filter(n=>!s.includes(n))},Sa=e=>e,$a=e=>e,Dh=({container:e,onAddItem:t,onUpdateItem:s,onRemoveItem:r=Sa,idMapper:o=$a})=>n=>{const i=n.map(o),c=Wo(i,e.data).map(r).filter(Boolean);e.removeAll(c);const u=i.map(d=>{const h=e.getModel(d.id);return h&&s?s(d,h):t(d)}).filter(Boolean);e.addAll(u)},xh=({container:e,onAddItem:t,onRemoveItem:s=Sa,idMapper:r=$a})=>o=>{const n=o.map(r);Wo(n,e.models).forEach(s),n.forEach(t)},Ah=({items:e,onAddItem:t,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r);Wo(n,e).forEach(s),n.forEach(t)},Ph=(e,t="parent-")=>{let s=e;return s.startsWith(t)&&(s=s.replace(t,"")),s},pi=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),gi=[{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 Ca(e){let t=(e.getTime()-Date.now())/1e3;for(let s=0;s<=gi.length;s++){const r=gi[s];if(Math.abs(t)<r.amount)return pi.format(Math.round(t),r.name);t/=r.amount}return pi.format(Math.round(t),"years")}const Qo=e=>e%4===0&&e%100!==0||e%400===0,Zo=(e,t)=>[31,Qo(e)?29:28,31,30,31,30,31,31,30,31,30,31][t],Da=(e,t)=>{const s=new Date(e),r=e.getDate();return s.setDate(1),s.setMonth(s.getMonth()+t),s.setDate(Math.min(r,Zo(s.getFullYear(),s.getMonth()))),s},xa=(e,t)=>{const s=new Date(e);return s.setDate(s.getDate()+t),s},yt="en-US",Aa={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"}},Pa={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"}},Ra=(e,{dateStyle:t="short",locales:s=yt}={dateStyle:"short",locales:yt})=>{const r=t==="short"?Aa.short:{dateStyle:t};return new Intl.DateTimeFormat(s,r).format(e)},ka=(e,{locales:t=yt,timeStyle:s="short"}={locales:yt,timeStyle:"short"})=>{const r=Pa[s];return new Intl.DateTimeFormat(t,r).format(e)},La=(e,{dateStyle:t="short",locales:s=yt,timeStyle:r="short"}={dateStyle:"short",locales:yt,timeStyle:"short"})=>{const o={...t&&Aa[t],...r&&Pa[r]};return new Intl.DateTimeFormat(s,o).format(e)},Rh=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:xa,addMonthsToDate:Da,formatDate:Ra,formatDateSince:Ca,formatDateTime:La,formatTime:ka,getDaysInMonth:Zo,isLeapYear:Qo},Symbol.toStringTag,{value:"Module"}));function Fa(e,t,s=300){let r;return(...o)=>{clearTimeout(r),r=setTimeout(()=>{t.apply(e,o)},s)}}const te="canvas-renderer",Xr=new Map,mi=new Map,Jr=new Map,eo=new Map,$s=(e,t)=>{Na[e]=t},Na={indexExtension:{registerIndexExtension:(e,t)=>{const s=eo.get(e)||{};Object.assign(s,t),eo.set(e,t)},loadIndexExtensions:e=>eo.get(e)||{}},loader:{registerLoader:(e,t)=>{mi.set(e,t)},executeLoader:async(e,t)=>{const s=mi.get(e);if(s)return await s(t)}},propertyMapper:{registerPropertyMapper:(e,t)=>{Jr.set(e,t)},hasMapper:e=>Jr.has(e),executeMapper:(e,t,s)=>{const r=Jr.get(e);return r?r(t,s):""}},dataMapper:{registerDataMapper:(e,t)=>{const s=Xr.get(e)||[];s.push(t),Xr.set(e,s)},executeMapper:async(e,t,s)=>{const r=Xr.get(e);if(!r)return{};const o={};for(const n of r){const i=await n(t,s);Object.assign(o,i)}return o}},canvas:{registerRenderer:(e,t)=>{if(!S[te]){console.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${e}".`);return}S[te].register(e,t)}}},S=Na,kh=async({context:e,extension:t})=>{const s=await S.loader.executeLoader(t,{});return e==null||e.set(t,s),s},Lh=async({extension:e,contextData:t,data:s})=>await S.dataMapper.executeMapper(e,s,t),Fh=async({extension:e,contextData:t,data:s})=>await S.propertyMapper.executeMapper(e,s,t),Nh=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:Lh,executeLoaderExtension:kh,executePropertyMapperExtension:Fh},Symbol.toStringTag,{value:"Module"})),Uh="Extensions";class jh{constructor(){l(this,"extensions");this.extensions={}}register(t,s,r){this.extensions[t]={},this.extensions[t][s]={component:r}}get(t,s){if(!this.extensions[t])throw new Error(`Extension point ${t} not found`);return this.extensions[t][s]}get allExtensions(){return this.extensions}}const ge=(e=null)=>(e||window.location.search.replace("?","")).split("&").map(t=>{const[s,r]=t.split("=");return[s,decodeURIComponent(r||"")]}).reduce((t,[s,r])=>(t[s]=r,t),{}),Ua="studio.tools.preview",Bh="studio.relax.store.validation",ja="studio.log.debug",Ba="studio.log.info",Kh={profiles:[Ua]};var ta;const Hh=((ta=globalThis.getKosConfig)==null?void 0:ta.call(globalThis))||JSON.stringify(Kh),Ka=JSON.parse(Hh);globalThis.kosConfig=Ka;const Xo=Ka,Ha=()=>Xo.profiles||[],yo=e=>Ha().includes(e),zh=()=>Xo.logging||!1,Gh=()=>{const e=yo(ja),t=yo(Ba);return e?"DEBUG":t?"INFO":void 0},za=()=>{const e=ge(),t=Gh(),r=e.kosLogLevel??t??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},Ga=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",Va=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",Ya="ws-log",Vh=C.methodFactory,qa=Ga(),Yh=Va();C.methodFactory=function(e,t,s){const r=Vh(e,t,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!==Ya||qa&&Yh)&&globalThis.kosLog(`UI: ${i}${a}`)}};let Wa=za();C.setLevel(Wa);window.setKosLogLevel=e=>{Wa=e,C.setLevel(e)};const Js=C.getLogger(Ya);window.enableKosMessageLog=()=>{Js.setLevel(C.levels.INFO)};window.disableKosMessageLog=()=>{Js.setLevel(C.levels.ERROR)};qa?window.enableKosMessageLog():window.disableKosMessageLog();const qh=["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(";"),Wh=["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(";"),ks=e=>t=>{C.getLevel()<=e&&t()},m={...C,ifDebug:ks(C.levels.DEBUG),ifInfo:ks(C.levels.INFO),ifWarn:ks(C.levels.WARN),ifError:ks(C.levels.ERROR),getLogger:e=>C.getLogger(`kos::${e}`),getLoggers:()=>C.getLoggers(),createLogger:({name:e,group:t})=>{var n,i,a,c;const s=`${t?`${t}:`:"kos"}::${e}`,r=C.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:(...e)=>{const t=String(e).replace(/\n/g,"\\n");Js.info(`%c⬆ ${t}`,qh)},wsReceive:(...e)=>{const t=String(e).replace(/\n/g,"\\n");Js.info(`%c⬇ ${t}`,Wh)}},Qa="featureFlagResolver",Ls=new Map;$s(Qa,{register:(e,t)=>{var s;Ls.has(e)||Ls.set(e,[]),(s=Ls.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Ls.get(e);if(!s)return[];const r=s.map(a=>a(t)),n=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(m.info(`Feature flag resolver ${e} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(n)).reduce((a,c)=>(a[c]=!0,a),{});return Xa.updateFlags(i),Object.keys(i)}});const Qh="kos.loader.featureFlag";class Za{constructor(t={}){l(this,"flags",{});this.flags=t}isFeatureEnabled(t){return!!this.flags[t]}enableFeature(t){this.flags[t]=!0}disableFeature(t){this.flags[t]=!1}toggleFeature(t){this.flags[t]=!this.flags[t]}updateFlags(t){this.flags={...this.flags,...t}}}window.KosFeatureFlags=window.KosFeatureFlags??new Za;const Xa=window.KosFeatureFlags,Ja=(e,t,s)=>{s/=100;const r=t*Math.min(s,1-s)/100,o=n=>{const i=(n+e/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)}`},ec=e=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(e);if(!s)throw Error("Invalid HSL string");return Ja(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},tc=(e,t)=>getComputedStyle(e).getPropertyValue(t),Zh=(e,t)=>ec(tc(e,t)),Xh=(e,t)=>{const s={...e};return s.id&&delete s.id,s},bo=(e,t,s=Xh)=>{const r=s(e,t);E.runInAction(()=>{Object.assign(t,r)})},to=new Map,sc={addToDeletionQueue:(e,t)=>{const s=to.get(e)||[];s.push(t),to.set(e,s)},cancelDeletion:e=>{const t=to.get(e);t&&t.forEach(s=>{clearTimeout(s)})}},Jh=m.createLogger({name:"kos-dependency-manager"});class ef{constructor(){l(this,"_usedByCache",new Map);l(this,"_usesCache",new Map)}add(t,s){sc.cancelDeletion(s);const r=this._usedByCache.get(s)||[];r.includes(t)||r.push(t),this._usedByCache.set(s,r);const o=this._usesCache.get(t)||[];o.includes(s)||o.push(s),this._usesCache.set(t,o)}remove(t,s){const r=this._usedByCache.get(s)||[];this._usedByCache.set(s,r.filter(n=>n!==t));const o=this._usesCache.get(t)||[];this._usesCache.set(t,o.filter(n=>n!==s))}canDestroy(t){const s=this._usedByCache.get(t);return s!=null&&s.length?(Jh.info(`Model ${t} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}var v=(e=>(e.CREATING="creating",e.CREATED="created",e.INITIALIZING="initializing",e.INITIALIZED="initialized",e.LOADING="loading",e.LOADED="loaded",e.ONLINE="online",e.READYING="readying",e.READY="ready",e.READY_FAILED="ready_failed",e.RESETTING="resetting",e.RESET="reset",e.OFFLINE="offline",e.UNLOADING="unloading",e.UNLOADED="unloaded",e.FAILED="failed",e.INACTIVE="inactive",e.ACTIVE="active",e.ACTIVATING="activating",e.DEACTIVATING="deactivating",e))(v||{}),R=(e=>(e.CREATE="create",e.INITIALIZE="init",e.LOAD="load",e.READY="ready",e.GO_ONLINE="go_online",e.GO_OFFLINE="go_offline",e.RESET="go_offline",e.UNLOAD="unload",e.FAILED="failed",e.GO_ACTIVE="go_active",e.GO_INACTIVE="go_inactive",e.TIMEOUT="timeout",e))(R||{});const yi=m.createLogger({name:"kos-model-cache"});class tf{constructor(t=[]){l(this,"_modelsById",E.observable.map(new Map));l(this,"_toDelete",new Map);l(this,"_preloaded",[]);l(this,"_isPreloaded",!1);this.preloadKeys=t}get models(){return Array.from(this._modelsById.values()).map(t=>t).filter(t=>!this._toDelete.has(t.modelId))}getModelById(t){if(t&&!this._toDelete.has(t))return this._modelsById.get(t)}addModel(t){const s=this.getModelById(t.modelId)||t;return this._modelsById.set(s.modelId,s),s}removeModel(t){this._modelsById.delete(t),this._toDelete.delete(t)}hasModel(t){return!!t&&this._modelsById.has(t)&&!this._toDelete.has(t)}restoreFromDeleteCache(t){if(t&&this._toDelete.has(t)){const s=this._toDelete.get(t);this._toDelete.delete(t),this._modelsById.set(t,s)}}markForDeletion(t){this._modelsById.delete(t.modelId),this._toDelete.set(t.modelId,t)}preload(t){return this._isPreloaded?(yi.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(yi.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),t(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const ee=Symbol("SubscriptionHandlers"),k=Symbol("DependencyModels"),os=Symbol("FutureService"),Be=Symbol("ChildModels"),ns=Symbol("ParentModel"),is=Symbol("LogConfig"),Vs=Symbol("ReferenceConfig"),Jo=Symbol("KosModelSymbol"),Ze=Symbol("ModelEffects"),bt=Symbol("CompanionParentModel"),en=Symbol("FutureContainerSetup"),tn=Symbol("MultipleFutureContainerSetup"),as=Symbol("FutureAliases"),sn=Symbol("TroubleAwareSetup"),rn=Symbol("LoggerSetup"),on=Symbol("ContainerAwareSetup"),Ie=(e,t)=>{e[Be]=e[Be]||{},e[Be][t]=!0},st=e=>`{PROP_${String(e)}}`,sf=e=>`{PROP_${String(e)}}`,rf=st("kosParentId"),Ar=e=>t=>{t[ns]=t[ns]||{};const s=(e==null?void 0:e.parentId)||rf;t[ns]={parentId:s}};function of(e){return t=>{const s=(e==null?void 0:e.mode)||"decorator",r=(e==null?void 0:e.parentProperty)||"companionParent",o=(e==null?void 0:e.excludeProperties)||[];return Ar()(t),t.prototype[bt]={mode:s,parentProperty:r,excludeProperties:o},t}}function rc(e){return t=>{const s=e!=null&&e.legacy?"_models":(e==null?void 0:e.containerProperty)||"container",r=(e==null?void 0:e.includeMethods)!==!1,o=(e==null?void 0:e.includeGetters)!==!1,n=(e==null?void 0:e.modelsProperty)||"models",i=(e==null?void 0:e.containerOptions)||{};return t.prototype[on]={containerProperty:s,includeMethods:r,includeGetters:o,modelsProperty:n,containerOptions:i,legacy:(e==null?void 0:e.legacy)||!1},t}}function nf(e,t,s){const r=s.value;s.value=function(...o){const n=V.getContext(this.id);return o.push(n),r.apply(this,o)}}function af(e){return t=>{const s=(e==null?void 0:e.mode)||"full",r=(e==null?void 0:e.handlerProperty)||"futureHandler";return t.prototype[en]={mode:s,handlerProperty:r},t}}function cf(e){return t=>{const s=(e==null?void 0:e.mode)||"full",r=(e==null?void 0:e.handlerProperty)||"futureHandler";return t.prototype[tn]={mode:s,handlerProperty:r},t}}var H=(e=>(e.INIT="init",e.LOAD="load",e.READY="ready",e.ACTIVATE="activate",e.ONLINE="online",e))(H||{});const lf=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:H},Symbol.toStringTag,{value:"Module"})),xe=Symbol("HttpRouteHandlers"),bi="__httpBrowserRouter";function Pr(e){return function(s){return function(r,o,n){r[xe]=r[xe]||[];const i={method:e,path:s,handler:o};return r[xe].push(i),r[k]=r[k]||{},r[k][bi]||(r[k][bi]={modelType:"browser-router-model",lifecycle:H.INIT}),n}}}const oc=Pr("GET"),Cs=Pr("POST"),uf=Pr("PUT"),nc=Pr("DELETE"),df=nc;function er(e){return!!(e!=null&&e[xe])&&e[xe].length>0}function ic(e){return(e==null?void 0:e[xe])||[]}const hf=({group:e}={group:""})=>t=>{t[is]=t[is]||{},t[is]={group:e}};class ac{static create({modelId:t,modelTypeName:s,component:r}){const o=[r??"kos",s,t].filter(Boolean).join(".");return m.createLogger({name:o})}}function cc(e){return t=>{const s=(e==null?void 0:e.loggerProperty)||"logger",r=e==null?void 0:e.loggerContext;t.prototype[rn]={loggerProperty:s,loggerContext:r};const o=()=>{var i;return(i=t.prototype[Jo])==null?void 0:i.type};let n;return Object.defineProperty(t.prototype,s,{get(){if(!n){const i=o();n=ac.create({modelTypeName:r||i,component:"kos-model"})}return n},enumerable:!1,configurable:!1}),t}}function lc(e){return(t,s,r)=>{t[Ze]=t[Ze]||{},t[Ze][s]={dependencies:e==null?void 0:e.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const ff=e=>(t,s)=>{t[Vs]=t[Vs]||{},t[Vs][s]=e};function pf(e){return t=>{const s=(e==null?void 0:e.pathProperty)||"path";return t.prototype[sn]={pathProperty:s},t.prototype[k]=t.prototype[k]||{},t.prototype[k].troubleContainer={modelType:"trouble-container-model",id:"trouble-container-model",options:{},lazy:!1},t}}const Pt=({modelType:e,id:t,options:s,lifecycle:r})=>(o,n)=>{o[k]=o[k]||{},o[k][n]={modelType:e,id:t,options:s,lifecycle:r||H.INIT}};class uc{constructor(t,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=mn.map(new Map),this.context="",this.defaultContext=s||"",this.container=t,E.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(t,s){this.futures.set(s||t.id,t),this.context=s||t.id;const r=Y(()=>{var o,n;(t.endState||t.progress)&&((n=(o=this.container)==null?void 0:o.onFutureUpdate)==null||n.call(o,t))});this.disposers.set(s||t.id,r)}removeFuture(t){var s;this.futures.delete(t||this.context),(s=this.disposers.get(t||this.context))==null||s(),this.disposers.delete(t||this.context)}getFuture(t){return this.futures.get(t||this.context)}get futureMap(){return this.futures}}class Rr{constructor(t){l(this,"disposer");l(this,"_future");l(this,"container");l(this,"onFutureUpdate");this._future=void 0,this.container=t,E.makeAutoObservable(this)}removeFuture(){var t;this._future=void 0,(t=this.disposer)==null||t.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(t){this._future=t;const s=Y(()=>{var r,o;(t.endState||t.progress)&&((o=(r=this.container)==null?void 0:r.onFutureUpdate)==null||o.call(r,t))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var t;return((t=this._future)==null?void 0:t.timeRemaining)||""}get status(){var t;return((t=this._future)==null?void 0:t.status)||"NOT_RESOLVED"}get progress(){var t;return((t=this._future)==null?void 0:t.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(t){throw m.error(t),t}}}const dc=(e,t)=>{const s=t.type;return e[s]||(e[s]=[]),e[s].push(t),e},hc=Symbol("KosObservableData");class fc{constructor(){l(this,"map");l(this,"_revision",1);l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(t,s)=>{var r;return s==="_revision"||t[s]!==void 0?t[s]:this.atomMap.has(s)&&(r=this.atomMap.get(s))!=null&&r.reportObserved()?this.getValue(s):this.getValue(s)},set:(t,s,r)=>{var o;return this.map.has(s),this.setValue(s,r),this.atomMap.has(s)||this.atomMap.set(s,E.createAtom(s.toString())),(o=this.atomMap.get(s))==null||o.reportChanged(),!0},ownKeys:()=>[...Array.from(this.map.keys()),"_revision"]});this.map=E.observable.map(new Map),E.makeObservable(this,{_revision:E.observable})}setValue(t,s){const r=this.map.has(t);this.map.set(t,s),r||E.action(()=>{this._revision++})()}getValue(t){return this.map.get(t)}has(t){return this.map.has(t)}get entries(){return Array.from(this.map.entries())}get keys(){return this._revision,Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(t){t&&Object.keys(t).forEach(s=>{this.setValue(s,t[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}fc.prototype[hc]=!0;function gf(e,t){return new Proxy(e,{construct:(s,r)=>{const o=new e(...r);return o.setValues(t),o.proxy}})}const Te=e=>{const t=gf(fc,e);return new t(e)};function mf(e,t){return e.length!==t.length?!1:e.every(s=>t.includes(s))}class nn{constructor({container:t,key:s}){l(this,"_container");l(this,"_map");l(this,"_key");l(this,"data");this._container=t,this._map=E.observable.map(new Map),this._key=s,this.data=Te(),this.generateIndex(),E.autorun(()=>{this._container.revision&&this.generateIndex()}),E.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(t,s,r=this._map,o=this.data){const n=r.get(t)||new Set;n.add(s),r.set(t,n),o[t]=Array.from(n)}resolveIndex(t,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(mf(n,i))m.debug(`KosContainerIndex - Index ${o} is the same`);else{this.data[o]=n;const a=t.get(o)||new Set;this._map.set(o,a)}})}generateIndex(){E.runInAction(async()=>{const t=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,t,s)}):typeof o=="string"||typeof o=="number"?this.addItemToIndex(String(o),r,t,s):typeof o=="boolean"&&this.addItemToIndex(String(o),r,t,s)}this.resolveIndex(t,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(t){const s=this._map.get(t);return s?Array.from(s):[]}}function yf(e,t,s=[]){const r=Object.getOwnPropertyDescriptors(e);return Object.keys(r).filter(i=>E.isComputedProp(e,i)).filter(i=>s.includes(i)).map(i=>E.reaction(()=>e[i],(a,c)=>{t({name:i,newValue:a,oldValue:c})}))}const Kt=m.createLogger({name:"kos-container-model"});class Se{constructor(t){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");this._data=E.observable.map(new Map),this._sortKey=t==null?void 0:t.sortKey,this._revision=1;const s=t!=null&&t.extensionId?S.indexExtension.loadIndexExtensions(t.extensionId):{},r=(t==null?void 0:t.indexMap)||{};this._optionsMap={...r,...s};const o=t!=null&&t.indexMap?Object.keys(t.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=E.observable.map(o),this.idx=Te(),this._parentId=t==null?void 0:t.parentId,E.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],r=new nn({container:this,key:s});this._index.set(t,r),this.idx[t]=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((t,s)=>{var r;return t[s]=(r=this.index.get(s))==null?void 0:r.keys,t},{})}sortFn(t,s){const r=this._sortKey;return r?String(t[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const t=Array.from(this._data.values());return this._sortKey&&t.sort(this.sortFn.bind(this)),t}increment(){E.runInAction(()=>{this._revision=this._revision+1})}addAll(t){E.runInAction(()=>{t.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(t){E.runInAction(()=>{t.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(t,s){this._data.set(t.id||"",t),t.id&&this._parentId&&V.setParentContext(t.id,this._parentId),s||this.increment();const r=this._disposerMap.get(t.id);r&&(r(),this._disposerMap.delete(t.id));const o=Object.entries(this._optionsMap||{}),n=Object.values(this._optionsMap||{}),i=new Map(o.map(([d,h])=>[h,d])),a=d=>{var f,p;n.includes(d.name)&&((f=this.index.get(i.get(d.name)))==null||f.refresh());const h=o.filter(([,b])=>typeof b=="function");for(const[b]of h)(p=this.index.get(b))==null||p.refresh()},c=yf(t,a,n.filter(d=>typeof d=="string")),u=E.observe(t,a);this._disposerMap.set(t.id||"",()=>[u,...c].forEach(d=>d()))}removeModel(t,s){this._data.delete(t),s||this.increment();const r=this._disposerMap.get(t);r&&(r(),this._disposerMap.delete(t))}updateModel(t){this._data.set(t.id||"",t),this.increment()}getModel(t){return this._data.get(t)}getIndexKeys(t){return this.index.has(t)?this.index.get(t).keys??[]:(Kt.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(t,s){if(this.index.has(t)){const r=this.index.get(t);return r.index.has(s)?r.getByKey(s):(Kt.info(`key ${s} not found in ${t} index: ${Array.from(r.index.keys())}`),[])}else return Kt.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(t=>{const s=t.id;Xe(t).then(()=>{Kt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>Kt.error(r))}),this.increment()}filter(t,s){return this.data.filter(t,s)}sort(t){return this.data.sort(t)}map(t,s){return this.data.map(t,s)}forEach(t,s){this.data.forEach(t,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}const ue=async e=>{if(e.id){const t=I.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error(`Model with ID ${e.id} not found`);await(t==null?void 0:t.whenReady())}else throw new Error("Data model must have a valid ID");return e},Xe=async e=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.initiateDestroyModel(e)},bf=async e=>{if(await I.getInstance().whenReady(),!e.id)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e.id);t&&await t.fsm.transitionTo(R.UNLOAD,v.UNLOADED)},vf=async e=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.reloadModel(e),m.debug(`reload model initiated for model ${e.id}, model ready: ${tr(e)} - ${Date.now()} `),await ue(e),m.debug(`reload model complete for model ${e.id}, model ready: ${tr(e)} - ${Date.now()} `)},wf=async e=>{if(await I.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);return t==null?void 0:t.modelTypeName},pc=async e=>{if(await I.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},_e=e=>{if(!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},gc=(e,t)=>{if(!e)throw new Error("Model type is required");return I.getInstance().modelManager.getModelsByType(e).filter(o=>Object.keys(t).every(n=>o[n]===t[n]))},Ef=(e,t)=>gc(e,t)[0],Mf=(e,t)=>{if(!e.id)throw new Error("Model ID is required");const s=I.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error("Model not found");const r=s.companionModels.get(t);return r==null?void 0:r.modelData},mc=e=>{if(!e.id)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return Array.from(t.companionModels.all()).map(r=>r.modelData)},Tf=e=>{if(!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);if(!t)throw new Error("Model not found");return t.companionModels.data},vo=(e,t)=>{const s=I.getInstance().modelManager.getModelById(e);if(!s){m.info(`Model not found for id ${e}`);return}return Array.from(s.companionModels.all()).find(o=>t(o.modelData))},Ee=e=>t=>Object.getPrototypeOf(t).modelTypeId===e,tr=e=>{const t=I.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return t.isReady()},_f=m.createLogger({name:"kos-model-factory"}),cs={byModelType:e=>I.getInstance().modelManager.getModelFactory(e),getModelInstance:(e,t,s)=>{const r=cs.byModelType(t);if(!r)throw _f.error(`No registered factory found for model type ${t}. Please register a factory for this model type. `),Error(`No factory found for model type ${t}`);return r.build(e,s)}},ie={Factory:{create:e=>t=>(s,r)=>(r&&V.setParentContext(t,r),cs.getModelInstance(t,e,s))},Singleton:{create:e=>(t,s)=>(s&&V.setParentContext(e,s),cs.getModelInstance(e,e,t))},Model:{instance:e=>t=>cs.getModelInstance(t,e)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const vi=window.KosRegistry.coreModels,so=window.KosRegistry.preloadModels,ro=window.KosRegistry.companionModels,Fs=window.KosRegistry.models,x={model:{registerLegacyModel:e=>(t,s)=>(vi.set(t,s),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}),preloadModel:e=>t=>(so.includes(t)||so.push(t),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}),register:e=>(t,s)=>{const r=oo(t)?t.registration():t;return Fs.set(r.type,r),oo(t)&&t.relatedModels.forEach(o=>Fs.set(o.type,o.registration())),I.getInstance().isReady&&(I.getInstance().modelManager.registry.models[r.type]||(console.info(`Model with type ${r.type} doesn't exist. Adding new registration`),I.getInstance().modelManager.registry.models[r.type]=r.registration[r.type],oo(t)&&t.relatedModels.forEach(o=>I.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&x.model.preloadModel(e)(r.type),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}},get:e=>Fs.get(e),getAll:()=>Array.from(Fs.entries()),getPreloadModels:()=>so,getLegacyModels:()=>Array.from(vi.entries()).reduce((e,[t,s])=>(e[t]=s,e),{})},companion:{register:e=>(t,s)=>{const r=ro.get(t)||[];return r.push(s),ro.set(t,r),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}},getAll:()=>Array.from(ro.entries())}},yc=x.model.registerLegacyModel,bc=x.model.register,Of=x.companion.register,If=x.model.preloadModel,an=e=>typeof e.updateModel=="function",oo=e=>e.registration!==void 0&&typeof e.registration=="function";class vc{constructor(t){l(this,"singleton");l(this,"type");l(this,"loader");l(this,"class");l(this,"guard");l(this,"factory");l(this,"relatedModels",[]);this.singleton=t.singleton,this.guard=Ee(t.type),this.type=t.type,this.loader=`kos.extension.model.loader.${t.type}`,this.factory=t.factory,this.class=t.class}addRelatedModel(t){this.relatedModels.push(t)}registerRelatedModels(){this.relatedModels.forEach(t=>t.register())}register(){x.model.register({})(this.registration()),this.registerRelatedModels()}}class me extends vc{constructor(t){super({...t,singleton:!1,factory:ie.Factory.create(t.type)})}instance(t){const s=this.factory(t);return{get:()=>{const r=_e(t);if(!r)throw new Error("Model not found with id "+t);if(this.guard(r))return r;throw new Error("Model is not of type "+this.type)},forceUpdate:{options:r=>({build:()=>{const o=s(r);if(this.guard(o)){if(an(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 Me extends vc{constructor(t){super({...t,singleton:!0,factory:ie.Singleton.create(t.type)})}instance(){const t=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=t(r);if(this.guard(o)){if(an(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=t(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 no=m.createLogger({name:"resolve-parameters"}),vt=({value:e,modelId:t,modelData:s})=>{let r=e;if(Array.isArray(r))return[...e];if(typeof r!="string"&&typeof r!="object")return r;if(typeof r=="object")r=Object.keys(r).reduce((o,n)=>(o[n]=vt({value:r[n],modelId:t,modelData:s}),o),{});else if(typeof r=="string"){const o=new RegExp("{PROP_(.+?)}","g");let n=r!=null&&r.includes(Xs)?r.replace(Xs,t):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?(no.debug(`Resolved ${c} to ${h}`),h):(no[a?"debug":"warn"](`Property ${u} is falsy${a?"":" in composite string"}, marking for undefined return`),i=!0,c)}return no[a?"debug":"warn"](`Property ${u} not found in modelData${a?"":" for composite string"}`),c}),i)return}return n}else return r;return r},wo=m.createLogger({group:"decorators",name:"kos-model"});function Sf(e,t,s){var n;const r=(n=e[ns])==null?void 0:n.parentId;if(!r)return;const o=vt({value:r,modelData:s,modelId:t});o&&typeof o=="string"&&V.setParentContext(t,o)}function $f(e){const t=e[os];t&&Object.entries(t).forEach(([s,{handler:r}])=>{e[s]=r})}function Cf(e,t){const s=e[k]||{};Object.entries(s).forEach(([r,o])=>{const n=vt({value:o.id||o.modelType,modelData:e,modelId:t}),i=Object.entries((o==null?void 0:o.options)||{}).reduce((a,[c,u])=>(a[c]=vt({value:u,modelData:e,modelId:t}),a),{});if(typeof n=="string"){if(!o.lazy){const a=I.getInstance().modelManager.createModelInstance(o.modelType,n,i);e[r]=a.data}I.getInstance().modelManager.addDependency(t,n)}})}function Df(e){const t=e[en];if(!t)return;const{mode:s,handlerProperty:r}=t,o=new Rr(e);e[r]=o,s==="full"&&(Object.defineProperty(e,"future",{get(){return o.future},enumerable:!0,configurable:!0}),Object.defineProperty(e,"progress",{get(){var n;return((n=o.future)==null?void 0:n.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"status",{get(){var n;return((n=o.future)==null?void 0:n.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isCancelled",{get(){var n;return((n=o.future)==null?void 0:n.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),e.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function xf(e){const t=e[tn];if(!t)return;const{mode:s,handlerProperty:r}=t,o=new uc(e);e[r]=o,Object.defineProperty(e,"future",{get(){return o.future},enumerable:!0,configurable:!0});const n=e[as];n instanceof Map&&n.forEach(i=>{const a=`${i}Future`;Object.defineProperty(e,a,{get(){return o.futureMap.get(i)},enumerable:!0,configurable:!0}),s==="full"&&(Object.defineProperty(e,`${i}Progress`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(e,`${i}Status`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(e,`${i}IsRunning`,{get(){const c=o.futureMap.get(i);return c?!c.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(e,`${i}IsCancelled`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),e[`cancel${i.charAt(0).toUpperCase()}${i.slice(1)}`]=async()=>{const c=o.futureMap.get(i);c&&await c.cancelFuture()})}),s==="full"&&(Object.defineProperty(e,"progress",{get(){var i;return((i=o.future)==null?void 0:i.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"status",{get(){var i;return((i=o.future)==null?void 0:i.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isCancelled",{get(){var i;return((i=o.future)==null?void 0:i.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),e.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function Af(e){const t=e[sn];if(!t)return;const{pathProperty:s}=t;Object.defineProperty(e,"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(e,"troubleStatus",{get(){return""},enumerable:!0,configurable:!0}),Object.defineProperty(e,"troublesByType",{get(){return this.troubles.reduce(dc,{})},enumerable:!0,configurable:!0})}function Pf(e,t){const s=e[on];if(!s)return;const{containerProperty:r,includeMethods:o,includeGetters:n,modelsProperty:i,containerOptions:a,legacy:c}=s,u={...a,parentId:a.parentId||t},d=new Se(u);e[r]=d,e[Be]||(e[Be]={}),e[Be][r]=d,o&&(e.getModel=h=>d.getModel(h),e.addModel=h=>{d.addModel(h)},e.removeModel=h=>{d.removeModel(h)}),n&&(Object.defineProperty(e,i,{get(){return d},enumerable:!0,configurable:!0}),Object.defineProperty(e,"data",{get(){return d.data},enumerable:!0,configurable:!0}))}function Rf(e,t){const s=e.constructor.prototype[bt];if(!s)return;const{mode:r,parentProperty:o,excludeProperties:n}=s,i=t[o];if(!i){wo.warn(`Companion decorator configured but no parent model found at '${o}'`);return}if(e.getCompanionParent=()=>i,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 b=i.constructor.prototype[ee]||{};return Object.values(b).some(w=>{const M=w==null?void 0:w.handler;return M===i[p]||M===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 e,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 b=i[p];typeof b=="function"?e[p]=(...w)=>b.apply(i,w):Object.defineProperty(e,p,{get:()=>i[p],set:w=>{i[p]=w},enumerable:!0,configurable:!0})}catch(b){wo.debug(`Skipping companion proxy for property ${p}:`,b)}}function kf(e){try{return E.makeAutoObservable(e)}catch(t){return wo.error("Failed to make observable:",t),e}}const Lf={construct(e,t){var c;const[s,r={}]=t,o=V.createContext(s);Sf(e,s,r);const i=!!e.prototype[rn]?null:m.createLogger({name:e.prototype.modelTypeId,group:((c=e[is])==null?void 0:c.group)??"kos-model"}),a=new e(s,r,{logger:i,kosContext:o});return $f(a),Df(a),xf(a),Af(a),Pf(a,s),Rf(a,r),Cf(a,s),kf(a)}};function A(e){return t=>{var n,i;const s=t,r=typeof e=="string"?{modelTypeId:e,autoRegister:!1}:{autoRegister:!1,...e};s.prototype.modelTypeId=r.modelTypeId,s.prototype[Jo]=!0,(n=s.prototype)[ee]??(n[ee]={}),(i=s.prototype)[k]??(i[k]={}),m.ifDebug(()=>{m.debug(`Registering model with id ${r.modelTypeId}`)});const o=new Proxy(s,Lf);if(r.singleton!==void 0){let a;r.singleton?a=new Me({class:o,type:r.modelTypeId}):a=new me({class:o,type:r.modelTypeId}),Object.defineProperty(o,"Registration",{value:a,writable:!1,enumerable:!0,configurable:!1}),r.autoRegister&&a.register()}return o}}const Ff=({topic:e,handler:t,websocket:s=!1,condition:r=()=>!0})=>o=>{o[ee]=o[ee]||{},Array.isArray(e)?e.forEach(n=>{o[ee][n]={websocket:s,handler:t,condition:r}}):o[ee][e]={websocket:s,handler:Fa(o,E.action(t),200),condition:r}};function wc(e,t,s){const r={};if(!e.endsWith("/*"))return r;const o=e.slice(0,-2);if(t.startsWith(o)){const n=t.slice(o.length+1),i=s||"path";r[i]=n}return r}function Ec(e){return e.endsWith("/*")}function U({topic:e,condition:t=(_,F)=>!0,transform:s=_=>_,websocket:r=!1,fos:o=!1,bridge:n=!1,skipParse:i=!1,lifecycle:a,destinationAddress:c,debounce:u,throttle:d,buffer:h,filter:f,once:p,replay:b,wildcardName:w,flow:M}){return(_,F,Q)=>{_[ee]=_[ee]||{};let O=Q.value;const W=typeof u=="number"?u:u==null?void 0:u.delay,B=typeof d=="number"?d:d==null?void 0:d.interval;W&&W>0?O=Nf(O,u):B&&B>0?O=Uf(O,d):h?O=jf(O,h):p&&(O=Bf(O));let J=t;if(f){const $e=t;J=(hi,fi,Zr)=>f(Zr)?$e(hi,fi,Zr):!1}const Ue={websocket:r,fos:o,bridge:n,handler:O,condition:J,transform:s,lifecycle:a,skipParse:i,destinationAddress:c,wildcardName:w,flow:M};Array.isArray(e)?e.forEach($e=>{_[ee][$e]=Ue}):_[ee][e]=Ue,b&&Kf(e,b.bufferSize)}}function Nf(e,t){const s=typeof t=="number"?t:t.delay,r=typeof t=="object"?t.discardIntermediate:!1;let o=null,n=[];return function(i){r?(o&&clearTimeout(o),o=setTimeout(()=>{e.call(this,i),o=null},s)):(n.push(i),o&&clearTimeout(o),o=setTimeout(()=>{const a=[...n];n=[],e.call(this,a),o=null},s))}}function Uf(e,t){const s=typeof t=="number"?t:t.interval,r=typeof t=="object"?t.discardIntermediate:!1;let o=0,n=null,i=[],a=!1;const c=function(){if(i.length>0){const u=[...i];i=[],e.call(this,u)}};return function(u){const d=Date.now(),h=d-o;r?h>=s?(o=d,e.call(this,u)):n||(n=setTimeout(()=>{o=Date.now(),e.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 jf(e,t){const s=[];let r=null;const o=t.maxSize||1e3,n=i=>{s.length>0&&(e.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},t.time))}}function Bf(e){let t=!1;return function(s){t||(t=!0,e.call(this,s))}}function Kf(e,t){(Array.isArray(e)?e:[e]).forEach(r=>{Vo(r,t)})}function Mc(e,t){return`${Ho}${e}${t?`/${t}`:`/${e}`}`}function Tc(e){return`${Ho}${e}`}function io(e){const t=[];return new Promise((s,r)=>{for(const{condition:o,onMatch:n}of e){const i=E.when(o,()=>{t.forEach(a=>a());try{n==null||n(),s()}catch(a){r(a)}});t.push(i)}})}const _c=5e3;class Hf extends Error{constructor(s,r){super(s);l(this,"model");this.model=r}}const Oc=(e,t,s)=>{let r;return{promise:new Promise((i,a)=>{r=setTimeout(()=>{m.error(`Model ${t.modelId} - ${t.modelTypeName} - ${s} timed out after ${e}ms`),a(new Hf(`${t.modelId} - ${t.modelTypeName} - ${s}`,t))},e)}),cancel:()=>{r&&clearTimeout(r)}}},Ic=e=>e.fsm.transitionTo(R.GO_ACTIVE,v.ACTIVE),Sc=e=>e.whenReady(),$c=e=>e.fsm.transitionTo(R.LOAD,v.LOADED),zf=e=>e.fsm.transitionTo(R.UNLOAD,v.UNLOADED),Cc=e=>e.fsm.transitionTo(R.INITIALIZE,v.INITIALIZED);var cn=(e=>(e.ACTIVE="active",e.READY="ready",e.LOAD="load",e.UNLOAD="unload",e.INIT="init",e))(cn||{});const Ys={active:Ic,ready:Sc,load:$c,init:Cc},Dc=(e,t)=>{const s=t.id||t.modelType,r=vt({value:s,modelData:e.modelData,modelId:e.modelId});m.debug(`activating dependent model ${t.modelType} with id ${r}`);const o=Object.keys((t==null?void 0:t.options)||{}).reduce((i,a)=>{const c=t.options[a];return i[a]=vt({value:c,modelData:e.modelData,modelId:e.modelId}),i},{});return{dependentModel:I.getInstance().modelManager.createModelInstance(t.modelType,r,o),dataModelId:r}},xc=(e,t=H.READY)=>{var o;const s=((o=e.modelData)==null?void 0:o[k])||{};return Object.keys(s).length===0?(m.debug(`${e.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===t).map(n=>{const i=s[n],{dependentModel:a,dataModelId:c}=Dc(e,i);e.modelData[n]=a.data,m.debug(`waiting for dependent model ${i.modelType} with id ${c} - waiting for WHENREADY`);const u=async(f,p,b)=>{var w;await((w=f.whenReady)==null?void 0:w.call(f)),m.debug(`dependent model ${p} with id ${b} - READY`)},{promise:d,cancel:h}=Oc(_c,e,e.status);return Promise.race([u(a.model,i.modelType,c).then(()=>{h()}).catch(f=>{console.error(`Error waiting for dependent model ${i.modelType} with id ${c}:`,f),h()}),d])}).filter(n=>!!n)},Ac=async(e,t,s,r)=>{if(m.debug(`Execute lifecycle with ${t.length} models`),t.length===0){m.debug(`${e.modelId} has no children. Returning`);return}if(!s){m.error(`${e.modelId} is not transitioning with a valid target ${s}`);return}const o=t.map(a=>{let c;return Ys[s]&&a?c=Ys[s](a):(a||m.error("model is undefined. This shouldn't happen"),Ys[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)),i=(await Promise.allSettled(o.map(a=>{var d;const{promise:c,cancel:u}=Oc(_c,a.model,a.status);return Promise.race([(d=a.promise)==null?void 0:d.then(()=>{u()}).catch(h=>{m.error(`Model ${a.modelId} - ${a.type} failed to transition to ${s}: ${h.message}`),u()}),c])}))).filter(a=>a.status==="rejected");i.length>0&&m.error(`Model ${e.modelId} had ${i.length} failed child models on ${r}`)},Pc=async(e,t,s)=>{await Ac(e,e.getChildren().filter(r=>!!r),t,s)},zt=async(e,t)=>{const r=(await Promise.allSettled(xc(e,t))).filter(o=>o.status==="rejected");r.length&&(m.error(`There were ${r.length} failed dependent models on ${t}`),m.error(r))},Gf=e=>typeof e.toJSON=="function",ls=e=>e[k]!==void 0,ln=e=>e.revision!==void 0&&e.index!==void 0,Rc=e=>{if(e){if(ls(e))return e;if(ln(e))return e.data;if(e instanceof Map||e instanceof E.ObservableMap||e instanceof Set)return Array.from(e.values()).filter(ls);if(Array.isArray(e))return e.filter(ls)}};function Vf(e){const t=`KosModel(${e.modelTypeName}:${e.modelId})`;try{Object.defineProperty(e,Symbol.toStringTag,{value:t,configurable:!0})}catch{e.toString=()=>t}try{Object.defineProperty(e.constructor,"name",{value:`KosModel_${e.modelTypeName}`,configurable:!0})}catch{e.constructor.name=`KosModel_${e.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in e&&Object.defineProperty(e,r,{enumerable:!1});Object.defineProperty(e,"debugState",{enumerable:!1,configurable:!0,get(){var r,o,n;return{id:e.modelId,type:e.modelTypeName,initialized:e.initialized,loaded:e.loaded,status:e.status,onlineStatus:e.onlineStatus,activeStatus:e.activeStatus,companions:(o=(r=e.companionManager)==null?void 0:r.all())==null?void 0:o.map(i=>i.modelTypeName),children:(n=e.getChildren)==null?void 0:n.call(e).map(i=>i.modelId),effects:!!e.effectManager,subs:!!e.subscriptionManager}}}),Yf(e.modelData,e.modelTypeName,e.modelId,e)}function Yf(e,t,s,r){Object.defineProperty(e,Symbol.toStringTag,{value:`KosModelData(${t}:${s})`,configurable:!0});try{Object.defineProperty(e.constructor,"name",{value:`${t}ModelData`,configurable:!0})}catch{e.constructor.name=`${t}ModelData`}Object.defineProperty(e,"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[k]||{};return{id:s,type:t,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=e.toJSON)==null?void 0:u.call(e))||{},subs:!!r.subscriptionManager}}}),Object.defineProperty(e,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const o={};for(const n of Object.keys(e))if(!(n.startsWith("_")||typeof e[n]=="function"))try{const i=e[n];ls(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:ln(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 qf{constructor(t){this.model=t}resolve(){const t=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(t).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 t=((s=this.model.modelData)==null?void 0:s[Be])||{};return Object.keys(t).map(r=>Rc(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var t,s;return((s=(t=this.model.modelData)==null?void 0:t.getChildren)==null?void 0:s.call(t))||[]}}class Wf{constructor(t){l(this,"companions",new E.ObservableMap);this.hostModel=t}add(t){this.companions.set(t.modelTypeName,t)}clear(){this.companions.clear()}get(t){return this.companions.get(t)}all(){return[...this.companions.values()]}get data(){return this.companions}}class Qf{constructor(t,s,r,o){l(this,"disposers",[]);this.modelTypeName=t,this.modelId=s,this.modelData=r,this.log=o}setup(){var s;const t=((s=this.modelData)==null?void 0:s[Ze])||{};for(const r of Object.keys(t)){const{value:o,dependencies:n,options:i}=t[r],a=o.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),E.runInAction(()=>a())},u=n?E.reaction(()=>n(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):E.autorun(c);this.disposers.push(u)}}disposeAll(){for(const t of this.disposers)try{t()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const Zf=m.createLogger({name:"model-active-machine"}),Xf=e=>{const t=y.createMachine(v.INACTIVE,{[v.FAILED]:y.state(y.transition(R.GO_ACTIVE,v.ACTIVATING)),[v.INACTIVE]:y.state(y.transition(R.GO_ACTIVE,v.ACTIVATING)),[v.ACTIVATING]:y.invoke(()=>(e.activeStatus=v.ACTIVATING,e.activate()),y.transition("done",v.ACTIVE,y.action(()=>{e.activeStatus=v.ACTIVE})),y.transition("error",v.FAILED,y.action(()=>{e.activeStatus=v.FAILED}))),[v.ACTIVE]:y.state(y.transition(R.GO_INACTIVE,v.DEACTIVATING)),[v.DEACTIVATING]:y.invoke(()=>(e.activeStatus=v.DEACTIVATING,e.deactivate()),y.transition("done",v.INACTIVE,y.action(()=>{e.activeStatus=v.INACTIVE})),y.transition("error",v.FAILED,y.action(()=>{e.activeStatus=v.FAILED})))});return{service:y.interpret(t,r=>Zf.debug(r.machine.current)),machine:t}},wi=m.createLogger({name:"model-online-machine"}),Jf=e=>{const t=y.createMachine(v.OFFLINE,{[v.ONLINE]:y.state(y.transition(R.GO_OFFLINE,v.OFFLINE,y.action(async()=>{await e.offline(),e.onlineStatus=v.OFFLINE}))),[v.OFFLINE]:y.state(y.transition(R.GO_ONLINE,v.ONLINE,y.action(async()=>{wi.debug(`Going online with model ${e.modelId}`),await e.online(),e.onlineStatus=v.ONLINE,await e.fsm.transitionTo(R.INITIALIZE,v.INITIALIZED)})))}),s=y.interpret(t,r=>wi.debug(r.machine.current));return{machine:t,service:s}},ep=e=>{var r;const t=Xf(e).service,s=Jf(e).service;return y.createMachine(v.CREATING,{[v.CREATING]:y.state(y.transition(R.CREATE,v.CREATED)),[v.CREATED]:y.state(y.immediate(v.INITIALIZING)),[v.INITIALIZING]:y.invoke(()=>(X(()=>{e.status=v.INITIALIZING}),e.init()),y.transition("done",v.INITIALIZED,y.action(()=>{e.status=v.INITIALIZED})),y.transition("error",v.FAILED,y.action(()=>{m.error(`Model ${e.modelId} - ${e.modelTypeName} failed to initialize. Transitioning to FAILED state.`),e.status=v.FAILED}))),[v.INITIALIZED]:y.state(y.immediate(v.LOADING)),[v.LOADING]:y.invoke(()=>(X(()=>{e.status=v.LOADING}),e.load()),y.transition("done",v.LOADED,y.action(()=>{e.status=v.LOADED})),y.transition("error",v.FAILED,y.action(()=>{e.status=v.FAILED}))),[v.LOADED]:y.state(y.immediate(v.READYING),y.transition(R.UNLOAD,v.UNLOADING)),[v.RESETTING]:y.invoke(()=>{var o;return X(()=>{e.status=v.RESETTING}),(o=e.unload)==null||o.call(e),e.load()},y.transition("done",v.LOADED,y.action(()=>{e.status=v.LOADED}))),[v.READYING]:y.invoke(()=>(X(()=>{e.status=v.READYING}),e.ready()),y.transition("done",v.READY,y.action(()=>{X(()=>{e.status=v.READY}),s.send(R.GO_ONLINE)})),y.transition("error",v.FAILED,y.action(()=>{e.status=v.FAILED}))),[v.READY]:y.state(y.transition(R.UNLOAD,v.UNLOADED,y.action((r=e.unload)==null?void 0:r.bind(e))),y.transition(R.RESET,v.RESETTING),y.transition(R.GO_ONLINE,v.READY,y.action(()=>{s.send(R.GO_ONLINE)})),y.transition(R.GO_OFFLINE,v.READY,y.action(()=>{s.send(R.GO_OFFLINE)})),y.transition(R.GO_ACTIVE,v.READY,y.action(()=>{t.send(R.GO_ACTIVE)})),y.transition(R.GO_INACTIVE,v.READY,y.action(()=>{t.send(R.GO_INACTIVE)}))),[v.UNLOADED]:y.state(),[v.FAILED]:y.state()})},tp=m.createLogger({name:"kos-model-lifecycle"}),sp=e=>({service:y.interpret(ep(e),s=>tp.debug(`state machine for model ${e.modelId}: ${s.machine.current});`))});class rp{constructor(t,s){l(this,"disposer");l(this,"service");this.model=t,this.log=s;const r=sp(t);this.service=r.service,this.service.send(R.CREATE)}get current(){return this.service.machine.current}async transitionTo(t,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 ${t} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=E.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 ${t}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(t)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(t){return[v.ACTIVE,v.INACTIVE].includes(t)?this.model.activeStatus:this.model.status}}const kc="browser-router-model";class un{constructor(t,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=t,this.logger=s}registerAll(){var s;if(!er(this.model))return;let t=this.model.__httpBrowserRouter;if(!t)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"){t=o;break}}if(t||(t=(s=_e(kc))==null?void 0:s.model),!t)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(t)}setRouter(t){this.router=t,this.registered||this.registerRoutes()}hasRoutes(){return er(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 t=ic(this.model);t.length!==0&&(this.logger.debug(`Registering ${t.length} HTTP routes`),t.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(t){const s=/\{PROP_([^}]+)\}/g;let r=t;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(t))!==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: ${t}`)}return r}registerRoute(t){if(!this.router)return;const s=this.model[t.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${t.handler}' not found on model`);return}const r=this.resolvePropKey(t.path);this.logger.debug(`Registering ${t.method} ${r} -> ${t.handler}`+(r!==t.path?` (resolved from ${t.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 ${t.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(t.method,r),this.router.use(t.method,r,o),this.registeredRoutes.push({method:t.method,path:r})}checkForDuplicateRoute(t,s){if(!this.router)return;this.router.getRoutes().find(n=>n.method===t&&n.path===s)&&this.logger.warn(`Duplicate route detected: ${t} ${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 t=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);t+=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 ${t} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function op(e,t){if(!er(e))return;const s=_e(kc);if(!(s!=null&&s.model))throw t.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 un(e,t).setRouter(s.model)}class np{constructor(t){l(this,"queue",[]);this.log=t}enqueue(t){this.queue.push(t)}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const t of this.queue)try{t()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class ip{constructor(t,s){l(this,"unsubscribers",[]);this.model=t,this.log=s}register(){const t=this.model.modelId,s=$("/kosCore/online",async()=>{this.log.debug(`Online event received for ${t}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${t} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(R.GO_ONLINE,v.ONLINE)}),r=$("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${t} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(R.GO_OFFLINE,v.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(t=>t()),this.unsubscribers=[]}}class ap{constructor(t){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=t,this.subscription={queue:[],resolvers:[],closed:!1};const s=$(t,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(t=>{this.subscription.closed?t({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{t({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(t=>{t(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(t){throw this.subscription.closed=!0,this.unsubscribe(),t}[Symbol.asyncIterator](){return this}}function Ei(e){return new ap(e)}var Lc=(e=>(e.GET="GET",e.PUT="PUT",e.POST="POST",e.DELETE="DELETE",e))(Lc||{});const Fc=({path:e,requestId:t,method:s,destinationAddress:r})=>{let o=`${Sr}:${s}
|
|
2
|
-
`;return o+=`topic:${
|
|
3
|
-
`,o+=`${
|
|
4
|
-
`,o+=`${
|
|
5
|
-
`,r&&(o+=`${
|
|
6
|
-
`),o+=`${
|
|
1
|
+
"use strict";var _h=Object.defineProperty;var Sh=(t,e,s)=>e in t?_h(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var l=(t,e,s)=>(Sh(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"),je=require("date-fns"),T=require("@emotion/react/jsx-runtime"),Ko=require("@emotion/styled"),ca=require("react-dom"),We=require("@emotion/react"),g=require("react"),Ho=require("mobx-react-lite"),Oh=require("@use-gesture/react"),xr="method",la="topic",Pt="url",Ds="request-id",Ar="response-id",qo="status",Ne="dst-addr",ua="src-addr",Ie="type",zo="ordered",Vo="tracker",da="Content-Type",ha="Cache-Control",fa="requestId",pa=process.env.KOS_LOGIN_URL||"http://localhost",ga=process.env.KOS_APP_PORT||"8080",Ih=`${pa}:${ga}`,sr="{MODEL_ID}";var xs=(t=>(t.SEND="/ws/log/msg/send",t.RECEIVED="/ws/log/msg/receive",t))(xs||{}),ma=(t=>(t.MSG_RECEIVE="/mock/msg/receive",t))(ma||{});const Go="/kos/model/ready/";D.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const z=globalThis.kos.subscriptions,$h=()=>Symbol("eventKey");function Yo(t){return z[t]&&Object.getOwnPropertySymbols(z[t]).length>0}function C(t,e){const s=$h();return z[t]||(D.debug(`Initializing subscription for ${t}`),z[t]={}),D.debug(`Subscribing to ${t} with id ${s.toString()}`),z[t][s]=e,{count:z[t]?Object.getOwnPropertySymbols(z[t]).length:0,unsubscribe:()=>(D.debug(`Unsubscribing from ${t} with id ${s.toString()}`),z[t]&&z[t][s]&&delete z[t][s],z[t]&&Object.getOwnPropertySymbols(z[t]).length===0&&delete z[t],{count:z[t]?Object.getOwnPropertySymbols(z[t]).length:0})}}function V(t,e,s={}){if(!z[t]||Object.getOwnPropertySymbols(z[t]).length===0)return D.debug(`No subscriptions for ${t}. Not publishing.`),{eventType:t,subscribers:0};const r=Object.getOwnPropertySymbols(z[t]).length;return Object.getOwnPropertySymbols(z[t]).forEach(o=>{if(s.sync){const n=s.sync;D.debug(`Performing sync publish for ${t} with sync id ${n}`),z[t][o]({body:e,headers:s}).then(i=>{D.debug(`Response recieved for ${n}, publishing back to source.`),V(n,i)})}else D.debug(`Performing async publish for ${t}`),z[t][o]({body:e,headers:s})}),{eventType:t,subscribers:r}}function Ch(){D.warn("Resetting event bus"),Object.keys(z).forEach(t=>delete z[t])}function ya(t,e){const s=C(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function Wo(t,e){return new Promise((s,r)=>{let o=null;const n=ya(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}const Dh=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:Yo,once:ya,publish:V,reset:Ch,subscribe:C,waitFor:Wo},Symbol.toStringTag,{value:"Module"}));function Rr(t,e){const s=C(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function Pr(t,e){return new Promise((s,r)=>{let o=null;const n=Rr(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}function ba(t,e){const s=t.map(r=>Pr(r,e));return Promise.all(s)}function va(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=Rr(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 wa(t,e,s){return C(t,o=>{o&&e(o)&&s(o)}).unsubscribe}function Ea(t,e,s){return C(t,o=>{if(o){const n=e(o);s(n)}}).unsubscribe}function Ma(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 Ta(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 _a(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 Qo(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 Sa(t,e){const s=t.map(r=>C(r,o=>{o&&e(r,o)}));return()=>{s.forEach(r=>r.unsubscribe())}}function Oa(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 Ia(t,e,s,r){const o=Pr(e,r);return V(t,s),o}async function*$a(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 xh={once:Rr,waitFor:Pr,waitForAll:ba,race:va,filter:wa,map:Ea,debounce:Ma,throttle:Ta,buffer:_a,replay:Qo,merge:Sa,stateMachine:Oa,request:Ia,eventIterator:$a},Ah=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:xh,buffer:_a,debounce:Ma,eventIterator:$a,filter:wa,map:Ea,merge:Sa,once:Rr,race:va,replay:Qo,request:Ia,stateMachine:Oa,throttle:Ta,waitFor:Pr,waitForAll:ba},Symbol.toStringTag,{value:"Module"}));async function kr(t,e){const{getCurrentState:s,transformState:r,shouldUseFetchedState:o,timeout:n}=e,i=Wo(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 Ca(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 Da(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 Zo(t,e){if(typeof t=="string")return kr(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=>Wo(d,n)),u=await Promise.all(c);return u[u.length-1]}function xa(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 Aa(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 kr(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 Rh={waitForOrGetState:kr,subscribeWithInitialState:Ca,createStatefulEventStream:Da,waitForAllWithState:Zo,createResilientEventHandler:xa,createConnectionStateManager:Aa},Ph=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:Rh,createConnectionStateManager:Aa,createResilientEventHandler:xa,createStatefulEventStream:Da,subscribeWithInitialState:Ca,waitForAllWithState:Zo,waitForOrGetState:kr},Symbol.toStringTag,{value:"Module"})),kh=(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 Xo(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 ot(){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 Lh(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 Fh(t,e){const s=t??[],r=e??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const Jo=(t,e)=>{const s=t.map(n=>n.id);return e.map(n=>n.id).filter(n=>!s.includes(n))},Ra=t=>t,Pa=t=>t,Nh=({container:t,onAddItem:e,onUpdateItem:s,onRemoveItem:r=Ra,idMapper:o=Pa})=>n=>{const i=n.map(o),c=Jo(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)},Uh=({container:t,onAddItem:e,onRemoveItem:s=Ra,idMapper:r=Pa})=>o=>{const n=o.map(r);Jo(n,t.models).forEach(s),n.forEach(e)},jh=({items:t,onAddItem:e,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r);Jo(n,t).forEach(s),n.forEach(e)},Bh=(t,e="parent-")=>{let s=t;return s.startsWith(e)&&(s=s.replace(e,"")),s},yi=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),bi=[{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 ka(t){let e=(t.getTime()-Date.now())/1e3;for(let s=0;s<=bi.length;s++){const r=bi[s];if(Math.abs(e)<r.amount)return yi.format(Math.round(e),r.name);e/=r.amount}return yi.format(Math.round(e),"years")}const en=t=>t%4===0&&t%100!==0||t%400===0,tn=(t,e)=>[31,en(t)?29:28,31,30,31,30,31,31,30,31,30,31][e],La=(t,e)=>{const s=new Date(t),r=t.getDate();return s.setDate(1),s.setMonth(s.getMonth()+e),s.setDate(Math.min(r,tn(s.getFullYear(),s.getMonth()))),s},Fa=(t,e)=>{const s=new Date(t);return s.setDate(s.getDate()+e),s},wt="en-US",Na={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"}},Ua={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"}},ja=(t,{dateStyle:e="short",locales:s=wt}={dateStyle:"short",locales:wt})=>{const r=e==="short"?Na.short:{dateStyle:e};return new Intl.DateTimeFormat(s,r).format(t)},Ba=(t,{locales:e=wt,timeStyle:s="short"}={locales:wt,timeStyle:"short"})=>{const r=Ua[s];return new Intl.DateTimeFormat(e,r).format(t)},Ka=(t,{dateStyle:e="short",locales:s=wt,timeStyle:r="short"}={dateStyle:"short",locales:wt,timeStyle:"short"})=>{const o={...e&&Na[e],...r&&Ua[r]};return new Intl.DateTimeFormat(s,o).format(t)},Kh=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Fa,addMonthsToDate:La,formatDate:ja,formatDateSince:ka,formatDateTime:Ka,formatTime:Ba,getDaysInMonth:tn,isLeapYear:en},Symbol.toStringTag,{value:"Module"}));function Ha(t,e,s=300){let r;return(...o)=>{clearTimeout(r),r=setTimeout(()=>{e.apply(t,o)},s)}}const te="canvas-renderer",so=new Map,vi=new Map,ro=new Map,oo=new Map,As=(t,e)=>{qa[t]=e},qa={indexExtension:{registerIndexExtension:(t,e)=>{const s=oo.get(t)||{};Object.assign(s,e),oo.set(t,e)},loadIndexExtensions:t=>oo.get(t)||{}},loader:{registerLoader:(t,e)=>{vi.set(t,e)},executeLoader:async(t,e)=>{const s=vi.get(t);if(s)return await s(e)}},propertyMapper:{registerPropertyMapper:(t,e)=>{ro.set(t,e)},hasMapper:t=>ro.has(t),executeMapper:(t,e,s)=>{const r=ro.get(t);return r?r(e,s):""}},dataMapper:{registerDataMapper:(t,e)=>{const s=so.get(t)||[];s.push(e),so.set(t,s)},executeMapper:async(t,e,s)=>{const r=so.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(!$[te]){console.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${t}".`);return}$[te].register(t,e)}}},$=qa,Hh=async({context:t,extension:e})=>{const s=await $.loader.executeLoader(e,{});return t==null||t.set(e,s),s},qh=async({extension:t,contextData:e,data:s})=>await $.dataMapper.executeMapper(t,s,e),zh=async({extension:t,contextData:e,data:s})=>await $.propertyMapper.executeMapper(t,s,e),Vh=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:qh,executeLoaderExtension:Hh,executePropertyMapperExtension:zh},Symbol.toStringTag,{value:"Module"})),Gh="Extensions";class Yh{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 me=(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),{}),za="studio.tools.preview",Wh="studio.relax.store.validation",Va="studio.log.debug",Ga="studio.log.info",Qh={profiles:[za]};var aa;const Zh=((aa=globalThis.getKosConfig)==null?void 0:aa.call(globalThis))||JSON.stringify(Qh),Ya=JSON.parse(Zh);globalThis.kosConfig=Ya;const sn=Ya,Wa=()=>sn.profiles||[],Eo=t=>Wa().includes(t),Xh=()=>sn.logging||!1,Jh=()=>{const t=Eo(Va),e=Eo(Ga);return t?"DEBUG":e?"INFO":void 0},Qa=()=>{const t=me(),e=Jh(),r=t.kosLogLevel??e??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},Za=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",Xa=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",Ja="ws-log",ef=D.methodFactory,ec=Za(),tf=Xa();D.methodFactory=function(t,e,s){const r=ef(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!==Ja||ec&&tf)&&globalThis.kosLog(`UI: ${i}${a}`)}};let tc=Qa();D.setLevel(tc);window.setKosLogLevel=t=>{tc=t,D.setLevel(t)};const rr=D.getLogger(Ja);window.enableKosMessageLog=()=>{rr.setLevel(D.levels.INFO)};window.disableKosMessageLog=()=>{rr.setLevel(D.levels.ERROR)};ec?window.enableKosMessageLog():window.disableKosMessageLog();const sf=["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(";"),rf=["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(";"),Us=t=>e=>{D.getLevel()<=t&&e()},m={...D,ifDebug:Us(D.levels.DEBUG),ifInfo:Us(D.levels.INFO),ifWarn:Us(D.levels.WARN),ifError:Us(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");rr.info(`%c⬆ ${e}`,sf)},wsReceive:(...t)=>{const e=String(t).replace(/\n/g,"\\n");rr.info(`%c⬇ ${e}`,rf)}},sc="featureFlagResolver",js=new Map;As(sc,{register:(t,e)=>{var s;js.has(t)||js.set(t,[]),(s=js.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=js.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 oc.updateFlags(i),Object.keys(i)}});const of="kos.loader.featureFlag";class rc{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 rc;const oc=window.KosFeatureFlags,nc=(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)}`},ic=t=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(t);if(!s)throw Error("Invalid HSL string");return nc(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},ac=(t,e)=>getComputedStyle(t).getPropertyValue(e),nf=(t,e)=>ic(ac(t,e)),af=(t,e)=>{const s={...t};return s.id&&delete s.id,s},Mo=(t,e,s=af)=>{const r=s(t,e);M.runInAction(()=>{Object.assign(e,r)})},no=new Map,cc={addToDeletionQueue:(t,e)=>{const s=no.get(t)||[];s.push(e),no.set(t,s)},cancelDeletion:t=>{const e=no.get(t);e&&e.forEach(s=>{clearTimeout(s)})}},cf=m.createLogger({name:"kos-dependency-manager"});class lf{constructor(){l(this,"_usedByCache",new Map);l(this,"_usesCache",new Map)}add(e,s){cc.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?(cf.info(`Model ${e} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}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||{}),L=(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))(L||{});const wi=m.createLogger({name:"kos-model-cache"});class uf{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?(wi.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(wi.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),e(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const ee=Symbol("SubscriptionHandlers"),F=Symbol("DependencyModels"),cs=Symbol("FutureService"),Be=Symbol("ChildModels"),ls=Symbol("ParentModel"),us=Symbol("LogConfig"),Qs=Symbol("ReferenceConfig"),rn=Symbol("KosModelSymbol"),Je=Symbol("ModelEffects"),Et=Symbol("CompanionParentModel"),on=Symbol("FutureContainerSetup"),nn=Symbol("MultipleFutureContainerSetup"),ds=Symbol("FutureAliases"),an=Symbol("TroubleAwareSetup"),cn=Symbol("LoggerSetup"),ln=Symbol("ContainerAwareSetup"),$e=(t,e)=>{t[Be]=t[Be]||{},t[Be][e]=!0},nt=t=>`{PROP_${String(t)}}`,df=t=>`{PROP_${String(t)}}`,hf=nt("kosParentId"),Lr=t=>e=>{e[ls]=e[ls]||{};const s=(t==null?void 0:t.parentId)||hf;e[ls]={parentId:s}};function ff(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)||[];return Lr()(e),e.prototype[Et]={mode:s,parentProperty:r,excludeProperties:o},e}}function lc(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[ln]={containerProperty:s,includeMethods:r,includeGetters:o,modelsProperty:n,containerOptions:i,legacy:(t==null?void 0:t.legacy)||!1},e}}function pf(t,e,s){const r=s.value;s.value=function(...o){const n=Y.getContext(this.id);return o.push(n),r.apply(this,o)}}const Fr=Symbol("KosExecutionContext");function un(t){return t&&typeof t=="object"&&Fr in t}function gf(t){return e=>{const s=(t==null?void 0:t.mode)||"full",r=(t==null?void 0:t.handlerProperty)||"futureHandler";return e.prototype[on]={mode:s,handlerProperty:r},e}}function mf(t){return e=>{const s=(t==null?void 0:t.mode)||"full",r=(t==null?void 0:t.handlerProperty)||"futureHandler";return e.prototype[nn]={mode:s,handlerProperty:r},e}}var U=(t=>(t.INIT="init",t.LOAD="load",t.READY="ready",t.ACTIVATE="activate",t.ONLINE="online",t))(U||{});const yf=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:U},Symbol.toStringTag,{value:"Module"})),Re=Symbol("HttpRouteHandlers"),Ei="__httpBrowserRouter";function Nr(t){return function(s){return function(r,o,n){r[Re]=r[Re]||[];const i={method:t,path:s,handler:o};return r[Re].push(i),r[F]=r[F]||{},r[F][Ei]||(r[F][Ei]={modelType:"browser-router-model",lifecycle:U.INIT}),n}}}const uc=Nr("GET"),Rs=Nr("POST"),bf=Nr("PUT"),dc=Nr("DELETE"),vf=dc;function or(t){return!!(t!=null&&t[Re])&&t[Re].length>0}function hc(t){return(t==null?void 0:t[Re])||[]}const wf=({group:t}={group:""})=>e=>{e[us]=e[us]||{},e[us]={group:t}};class fc{static create({modelId:e,modelTypeName:s,component:r}){const o=[r??"kos",s,e].filter(Boolean).join(".");return m.createLogger({name:o})}}function pc(t){return e=>{const s=(t==null?void 0:t.loggerProperty)||"logger",r=t==null?void 0:t.loggerContext;e.prototype[cn]={loggerProperty:s,loggerContext:r};const o=()=>{var i;return(i=e.prototype[rn])==null?void 0:i.type};let n;return Object.defineProperty(e.prototype,s,{get(){if(!n){const i=o();n=fc.create({modelTypeName:r||i,component:"kos-model"})}return n},enumerable:!1,configurable:!1}),e}}function gc(t){return(e,s,r)=>{e[Je]=e[Je]||{},e[Je][s]={dependencies:t==null?void 0:t.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const Ef=t=>(e,s)=>{e[Qs]=e[Qs]||{},e[Qs][s]=t},io=m.createLogger({name:"resolve-parameters"}),Ee=({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]=Ee({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(sr)?r.replace(sr,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?(io.debug(`Resolved ${c} to ${h}`),h):(io[a?"debug":"warn"](`Property ${u} is falsy${a?"":" in composite string"}, marking for undefined return`),i=!0,c)}return io[a?"debug":"warn"](`Property ${u} not found in modelData${a?"":" for composite string"}`),c}),i)return}return n}else return r;return r},et=Symbol("ServiceRequestHandlers"),Mi=new WeakMap;function Mf(t){return(e,s,r)=>{var a;e[et]=e[et]||{};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[et][i]=n,!t.lifecycle){const c=function(...u){const d=u[u.length-1],h=async f=>{const p=Mi.get(c);if(!p)throw new Error("Service request metadata not found for method");try{const{default:y}=await Promise.resolve().then(()=>Hc),w=Ee({value:p.path,modelId:this.id,modelData:this}),E={...typeof p.pathParams=="function"?p.pathParams(this):p.pathParams||{},...(f==null?void 0:f.pathParams)||{}},_={...typeof p.queryParams=="function"?p.queryParams(this):p.queryParams||{},...(f==null?void 0:f.queryParams)||{}},k=(f==null?void 0:f.body)||(typeof p.body=="function"?p.body(this):p.body),R={};Object.keys(E).length>0&&(R.path=E),Object.keys(_).length>0&&(R.query=_);const I=(p.method||"get").toLowerCase(),S=y,[H,q]=I==="get"?await S.get(w,R):I==="post"?await S.post(w,R,k):I==="put"?await S.put(w,R,k):I==="delete"?await S.delete(w,R,k):await S.get(w,R);if(H){if(p.errorHandler)switch(p.errorHandler.strategy){case"log":return console.error(`Service request error: ${H}`),p.errorHandler.onError&&p.errorHandler.onError(new Error(H),this),[null,p.errorHandler.defaultValue];case"ignore":return[null,p.errorHandler.defaultValue];case"default":return[null,p.errorHandler.defaultValue];case"throw":default:return[H,null]}return[H,null]}let J=q;return p.transform&&(J=p.transform(q)),[null,J]}catch(y){return[y.message||"Unknown error",null]}};if(un(d))return d.$request=h,o.apply(this,u);{const f={[Fr]:!0,$request:h};return o.apply(this,[...u,f])}};Mi.set(c,n),r.value=c}return r}}function Tf(t){return e=>{const s=(t==null?void 0:t.pathProperty)||"path";return e.prototype[an]={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 kt=({modelType:t,id:e,options:s,lifecycle:r})=>(o,n)=>{o[F]=o[F]||{},o[F][n]={modelType:t,id:e,options:s,lifecycle:r||U.INIT}};class mc{constructor(e,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=En.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=W(()=>{var o,n;(e.endState||e.progress)&&((n=(o=this.container)==null?void 0:o.onFutureUpdate)==null||n.call(o,e))});this.disposers.set(s||e.id,r)}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 Ur{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=W(()=>{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 yc=(t,e)=>{const s=e.type;return t[s]||(t[s]=[]),t[s].push(e),t},bc=Symbol("KosObservableData");class vc{constructor(){l(this,"map");l(this,"_revision",1);l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(e,s)=>{var r;return s==="_revision"||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()),"_revision"]});this.map=M.observable.map(new Map),M.makeObservable(this,{_revision:M.observable})}setValue(e,s){const r=this.map.has(e);this.map.set(e,s),r||M.action(()=>{this._revision++})()}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._revision,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)}}vc.prototype[bc]=!0;function _f(t,e){return new Proxy(t,{construct:(s,r)=>{const o=new t(...r);return o.setValues(e),o.proxy}})}const Se=t=>{const e=_f(vc,t);return new e(t)};function Sf(t,e){return t.length!==e.length?!1:t.every(s=>e.includes(s))}class dn{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=Se(),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(Sf(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 Of(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 Vt=m.createLogger({name:"kos-container-model"});class Ce{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");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=Se(),this._parentId=e==null?void 0:e.parentId,M.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new dn({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()})}addModel(e,s){this._data.set(e.id||"",e),e.id&&this._parentId&&Y.setParentContext(e.id,this._parentId),s||this.increment();const r=this._disposerMap.get(e.id);r&&(r(),this._disposerMap.delete(e.id));const o=Object.entries(this._optionsMap||{}),n=Object.values(this._optionsMap||{}),i=new Map(o.map(([d,h])=>[h,d])),a=d=>{var f,p;n.includes(d.name)&&((f=this.index.get(i.get(d.name)))==null||f.refresh());const h=o.filter(([,y])=>typeof y=="function");for(const[y]of h)(p=this.index.get(y))==null||p.refresh()},c=Of(e,a,n.filter(d=>typeof d=="string")),u=M.observe(e,a);this._disposerMap.set(e.id||"",()=>[u,...c].forEach(d=>d()))}removeModel(e,s){this._data.delete(e),s||this.increment();const r=this._disposerMap.get(e);r&&(r(),this._disposerMap.delete(e))}updateModel(e){this._data.set(e.id||"",e),this.increment()}getModel(e){return this._data.get(e)}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(Vt.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):(Vt.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return Vt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(e=>{const s=e.id;tt(e).then(()=>{Vt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>Vt.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}))}}}const de=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},tt=async t=>{await O.getInstance().whenReady(),await O.getInstance().modelManager.initiateDestroyModel(t)},If=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(L.UNLOAD,v.UNLOADED)},$f=async t=>{await O.getInstance().whenReady(),await O.getInstance().modelManager.reloadModel(t),m.debug(`reload model initiated for model ${t.id}, model ready: ${nr(t)} - ${Date.now()} `),await de(t),m.debug(`reload model complete for model ${t.id}, model ready: ${nr(t)} - ${Date.now()} `)},Cf=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},wc=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}},Oe=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}},Ec=(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]))},Df=(t,e)=>Ec(t,e)[0],xf=(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},Mc=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)},Af=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},To=(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))},Te=t=>e=>Object.getPrototypeOf(e).modelTypeId===t,nr=t=>{const e=O.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return e.isReady()},Rf=m.createLogger({name:"kos-model-factory"}),hs={byModelType:t=>O.getInstance().modelManager.getModelFactory(t),getModelInstance:(t,e,s)=>{const r=hs.byModelType(e);if(!r)throw Rf.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)}},ie={Factory:{create:t=>e=>(s,r)=>(r&&Y.setParentContext(e,r),hs.getModelInstance(e,t,s))},Singleton:{create:t=>(e,s)=>(s&&Y.setParentContext(t,s),hs.getModelInstance(t,t,e))},Model:{instance:t=>e=>hs.getModelInstance(e,t)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const Ti=window.KosRegistry.coreModels,ao=window.KosRegistry.preloadModels,co=window.KosRegistry.companionModels,Bs=window.KosRegistry.models,x={model:{registerLegacyModel:t=>(e,s)=>(Ti.set(e,s),{preload:x.model.preloadModel(t),model:x.model.register(t),companion:x.companion.register(t),legacy:x.model.registerLegacyModel(t),root:t}),preloadModel:t=>e=>(ao.includes(e)||ao.push(e),{preload:x.model.preloadModel(t),model:x.model.register(t),companion:x.companion.register(t),legacy:x.model.registerLegacyModel(t),root:t}),register:t=>(e,s)=>{const r=lo(e)?e.registration():e;return Bs.set(r.type,r),lo(e)&&e.relatedModels.forEach(o=>Bs.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],lo(e)&&e.relatedModels.forEach(o=>O.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&x.model.preloadModel(t)(r.type),{preload:x.model.preloadModel(t),model:x.model.register(t),companion:x.companion.register(t),legacy:x.model.registerLegacyModel(t),root:t}},get:t=>Bs.get(t),getAll:()=>Array.from(Bs.entries()),getPreloadModels:()=>ao,getLegacyModels:()=>Array.from(Ti.entries()).reduce((t,[e,s])=>(t[e]=s,t),{})},companion:{register:t=>(e,s)=>{const r=co.get(e)||[];return r.push(s),co.set(e,r),{preload:x.model.preloadModel(t),model:x.model.register(t),companion:x.companion.register(t),legacy:x.model.registerLegacyModel(t),root:t}},getAll:()=>Array.from(co.entries())}},Tc=x.model.registerLegacyModel,_c=x.model.register,Pf=x.companion.register,kf=x.model.preloadModel,hn=t=>typeof t.updateModel=="function",lo=t=>t.registration!==void 0&&typeof t.registration=="function";class Sc{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=Te(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(){x.model.register({})(this.registration()),this.registerRelatedModels()}}class ye extends Sc{constructor(e){super({...e,singleton:!1,factory:ie.Factory.create(e.type)})}instance(e){const s=this.factory(e);return{get:()=>{const r=Oe(e);if(!r)throw new Error("Model not found with id "+e);if(this.guard(r))return r;throw new Error("Model is not of type "+this.type)},forceUpdate:{options:r=>({build:()=>{const o=s(r);if(this.guard(o)){if(hn(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 _e extends Sc{constructor(e){super({...e,singleton:!0,factory:ie.Singleton.create(e.type)})}instance(){const e=this.factory;return{get:()=>{const r=Oe(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(hn(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 _o=m.createLogger({group:"decorators",name:"kos-model"});function Lf(t,e,s){var n;const r=(n=t[ls])==null?void 0:n.parentId;if(!r)return;const o=Ee({value:r,modelData:s,modelId:e});o&&typeof o=="string"&&Y.setParentContext(e,o)}function Ff(t){const e=t[cs];e&&Object.entries(e).forEach(([s,{handler:r}])=>{t[s]=r})}function Nf(t,e){const s=t[F]||{};Object.entries(s).forEach(([r,o])=>{const n=Ee({value:o.id||o.modelType,modelData:t,modelId:e}),i=Object.entries((o==null?void 0:o.options)||{}).reduce((a,[c,u])=>(a[c]=Ee({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 Uf(t){const e=t[on];if(!e)return;const{mode:s,handlerProperty:r}=e,o=new Ur(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 jf(t){const e=t[nn];if(!e)return;const{mode:s,handlerProperty:r}=e,o=new mc(t);t[r]=o,Object.defineProperty(t,"future",{get(){return o.future},enumerable:!0,configurable:!0});const n=t[ds];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 Bf(t){const e=t[an];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(yc,{})},enumerable:!0,configurable:!0})}function Kf(t,e){const s=t[ln];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 Ce(u);t[r]=d,t[Be]||(t[Be]={}),t[Be][r]=d,o&&(t.getModel=h=>d.getModel(h),t.addModel=h=>{d.addModel(h)},t.removeModel=h=>{d.removeModel(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 Hf(t,e){const s=t.constructor.prototype[Et];if(!s)return;const{mode:r,parentProperty:o,excludeProperties:n}=s,i=e[o];if(!i){_o.warn(`Companion decorator configured but no parent model found at '${o}'`);return}if(t.getCompanionParent=()=>i,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[ee]||{};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){_o.debug(`Skipping companion proxy for property ${p}:`,y)}}function qf(t){try{return M.makeAutoObservable(t)}catch(e){return _o.error("Failed to make observable:",e),t}}const zf={construct(t,e){var c;const[s,r={}]=e,o=Y.createContext(s);Lf(t,s,r);const i=!!t.prototype[cn]?null:m.createLogger({name:t.prototype.modelTypeId,group:((c=t[us])==null?void 0:c.group)??"kos-model"}),a=new t(s,r,{logger:i,kosContext:o});return Ff(a),Uf(a),jf(a),Bf(a),Kf(a,s),Hf(a,r),Nf(a,s),qf(a)}};function A(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[rn]=!0,(n=s.prototype)[ee]??(n[ee]={}),(i=s.prototype)[F]??(i[F]={}),m.ifDebug(()=>{m.debug(`Registering model with id ${r.modelTypeId}`)});const o=new Proxy(s,zf);if(r.singleton!==void 0){let a;r.singleton?a=new _e({class:o,type:r.modelTypeId}):a=new ye({class:o,type:r.modelTypeId}),Object.defineProperty(o,"Registration",{value:a,writable:!1,enumerable:!0,configurable:!1}),r.autoRegister&&a.register()}return o}}const Vf=({topic:t,handler:e,websocket:s=!1,condition:r=()=>!0})=>o=>{o[ee]=o[ee]||{},Array.isArray(t)?t.forEach(n=>{o[ee][n]={websocket:s,handler:e,condition:r}}):o[ee][t]={websocket:s,handler:Ha(o,M.action(e),200),condition:r}};function Oc(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 Ic(t){return t.endsWith("/*")}function B(t){return(e,s,r)=>{const o=Gf(t,r);Qf(e,t.topic,o),t.replay&&Zf(t.topic,t.replay.bufferSize)}}function Gf(t,e){const{condition:s=(S,H)=>!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,k=e.value,R=Yf(k,{debounce:d,throttle:h,buffer:f,once:y}),I=Wf(p,s);return{websocket:o,fos:n,bridge:i,handler:R,condition:I,transform:r,lifecycle:c,skipParse:a,destinationAddress:u,wildcardName:w,flow:E,requiresBaseline:_}}function Yf(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=Xf(s,e.debounce):o&&o>0?s=sp(s,e.throttle):e.buffer?s=rp(async function(c){for(const u of c)await s.call(this,u)},e.buffer):e.once&&(s=op(s)),s}function Wf(t,e){return t?(s,r,o)=>t(o)?e(s,r,o):!1:e}function Qf(t,e,s){t[ee]=t[ee]||{},Array.isArray(e)?e.forEach(r=>{t[ee][r]=s}):t[ee][e]=s}function Zf(t,e){np(t,e)}function Xf(t,e){const s=typeof e=="number"?e:e.delay;return Jf(e)==="discard"?ep(t,s):tp(t,s)}function Jf(t){return(typeof t=="object"?t.discardIntermediate:!1)?"discard":"accumulate"}function ep(t,e){let s=null;return function(r){s&&clearTimeout(s),s=setTimeout(()=>{t.call(this,r),s=null},e)}}function tp(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 sp(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 rp(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 op(t){let e=!1;return function(s){e||(e=!0,t.call(this,s))}}function np(t,e){(Array.isArray(t)?t:[t]).forEach(r=>{Qo(r,e)})}function $c(t,e){return`${Go}${t}${e?`/${e}`:`/${t}`}`}function Cc(t){return`${Go}${t}`}function uo(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 Dc=5e3;class ip extends Error{constructor(s,r){super(s);l(this,"model");this.model=r}}const xc=(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 ip(`${e.modelId} - ${e.modelTypeName} - ${s}`,e))},t)}),cancel:()=>{r&&clearTimeout(r)}}},Ac=t=>t.fsm.transitionTo(L.GO_ACTIVE,v.ACTIVE),Rc=t=>t.whenReady(),Pc=t=>t.fsm.transitionTo(L.LOAD,v.LOADED),ap=t=>t.fsm.transitionTo(L.UNLOAD,v.UNLOADED),kc=t=>t.fsm.transitionTo(L.INITIALIZE,v.INITIALIZED);var fn=(t=>(t.ACTIVE="active",t.READY="ready",t.LOAD="load",t.UNLOAD="unload",t.INIT="init",t))(fn||{});const Zs={active:Ac,ready:Rc,load:Pc,init:kc},Lc=(t,e)=>{const s=e.id||e.modelType,r=Ee({value:s,modelData:t.modelData,modelId:t.modelId});m.debug(`activating dependent model ${e.modelType} with id ${r}`);const o=Object.keys((e==null?void 0:e.options)||{}).reduce((i,a)=>{const c=e.options[a];return i[a]=Ee({value:c,modelData:t.modelData,modelId:t.modelId}),i},{});return{dependentModel:O.getInstance().modelManager.createModelInstance(e.modelType,r,o),dataModelId:r}},Fc=(t,e=U.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],{dependentModel:a,dataModelId:c}=Lc(t,i);t.modelData[n]=a.data,m.debug(`waiting for dependent model ${i.modelType} with id ${c} - waiting for WHENREADY`);const u=async(f,p,y)=>{var w;await((w=f.whenReady)==null?void 0:w.call(f)),m.debug(`dependent model ${p} with id ${y} - READY`)},{promise:d,cancel:h}=xc(Dc,t,t.status);return Promise.race([u(a.model,i.modelType,c).then(()=>{h()}).catch(f=>{console.error(`Error waiting for dependent model ${i.modelType} with id ${c}:`,f),h()}),d])}).filter(n=>!!n)},Nc=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 Zs[s]&&a?c=Zs[s](a):(a||m.error("model is undefined. This shouldn't happen"),Zs[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)),i=(await Promise.allSettled(o.map(a=>{var d;const{promise:c,cancel:u}=xc(Dc,a.model,a.status);return Promise.race([(d=a.promise)==null?void 0:d.then(()=>{u()}).catch(h=>{m.error(`Model ${a.modelId} - ${a.type} failed to transition to ${s}: ${h.message}`),u()}),c])}))).filter(a=>a.status==="rejected");i.length>0&&m.error(`Model ${t.modelId} had ${i.length} failed child models on ${r}`)},Uc=async(t,e,s)=>{await Nc(t,t.getChildren().filter(r=>!!r),e,s)},Yt=async(t,e)=>{const r=(await Promise.allSettled(Fc(t,e))).filter(o=>o.status==="rejected");r.length&&(m.error(`There were ${r.length} failed dependent models on ${e}`),m.error(r))},cp=t=>typeof t.toJSON=="function",fs=t=>t[F]!==void 0,pn=t=>t.revision!==void 0&&t.index!==void 0,jc=t=>{if(t){if(fs(t))return t;if(pn(t))return t.data;if(t instanceof Map||t instanceof M.ObservableMap||t instanceof Set)return Array.from(t.values()).filter(fs);if(Array.isArray(t))return t.filter(fs)}};function lp(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}}}),up(t.modelData,t.modelTypeName,t.modelId,t)}function up(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];fs(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:pn(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 dp{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{Y.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[Be])||{};return Object.keys(e).map(r=>jc(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 hp{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 fp{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[Je])||{};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 pp=m.createLogger({name:"model-active-machine"}),gp=t=>{const e=b.createMachine(v.INACTIVE,{[v.FAILED]:b.state(b.transition(L.GO_ACTIVE,v.ACTIVATING)),[v.INACTIVE]:b.state(b.transition(L.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(L.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=>pp.debug(r.machine.current)),machine:e}},_i=m.createLogger({name:"model-online-machine"}),mp=t=>{const e=b.createMachine(v.OFFLINE,{[v.ONLINE]:b.state(b.transition(L.GO_OFFLINE,v.OFFLINE,b.action(async()=>{await t.offline(),t.onlineStatus=v.OFFLINE}))),[v.OFFLINE]:b.state(b.transition(L.GO_ONLINE,v.ONLINE,b.action(async()=>{_i.debug(`Going online with model ${t.modelId}`),await t.online(),t.onlineStatus=v.ONLINE,await t.fsm.transitionTo(L.INITIALIZE,v.INITIALIZED)})))}),s=b.interpret(e,r=>_i.debug(r.machine.current));return{machine:e,service:s}},yp=t=>{var r;const e=gp(t).service,s=mp(t).service;return b.createMachine(v.CREATING,{[v.CREATING]:b.state(b.transition(L.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(L.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(L.GO_ONLINE)})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.READY]:b.state(b.transition(L.UNLOAD,v.UNLOADED,b.action((r=t.unload)==null?void 0:r.bind(t))),b.transition(L.RESET,v.RESETTING),b.transition(L.GO_ONLINE,v.READY,b.action(()=>{s.send(L.GO_ONLINE)})),b.transition(L.GO_OFFLINE,v.READY,b.action(()=>{s.send(L.GO_OFFLINE)})),b.transition(L.GO_ACTIVE,v.READY,b.action(()=>{e.send(L.GO_ACTIVE)})),b.transition(L.GO_INACTIVE,v.READY,b.action(()=>{e.send(L.GO_INACTIVE)}))),[v.UNLOADED]:b.state(),[v.FAILED]:b.state()})},bp=m.createLogger({name:"kos-model-lifecycle"}),vp=t=>({service:b.interpret(yp(t),s=>bp.debug(`state machine for model ${t.modelId}: ${s.machine.current});`))});class wp{constructor(e,s){l(this,"disposer");l(this,"service");this.model=e,this.log=s;const r=vp(e);this.service=r.service,this.service.send(L.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 Bc="browser-router-model";class gn{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(!or(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=Oe(Bc))==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 or(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=hc(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 Ep(t,e){if(!or(t))return;const s=Oe(Bc);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 gn(t,e).setRouter(s.model)}var ue=(t=>(t.IMMEDIATE="immediate",t.SINGLE="single",t.TTL="ttl",t.PERMANENT="permanent",t.MANUAL="manual",t))(ue||{}),Xe=(t=>(t.ALL="all",t.AFTER_REQUEST="after-request",t.AFTER_RESPONSE="after-response",t.NONE="none",t))(Xe||{});class Mp{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 Xe.ALL:return[...this.queue];case Xe.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 Xe.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 Xe.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 Tp{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(L.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(L.GO_OFFLINE,v.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}}const Kc=()=>({isMock:!1,URL:exports.BASE_URL}),_p=m.createLogger({name:"kos-service-request"}),Sp="errUnknown";async function Ks(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=>`${h}=${r.query[h]}`).join("&"):"",a=`${Kc().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;_p.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||Sp}`,null]:[null,(await u.json()).data]}function mn(){return{get:(t,e,s)=>Ks(t,"get",s,e),post:(t,e,s,r)=>Ks(t,"post",r,e,s),put:(t,e,s,r)=>Ks(t,"put",r,e,s),delete:(t,e,s,r)=>Ks(t,"delete",r,e,s)}}const De=mn(),Hc=Object.freeze(Object.defineProperty({__proto__:null,default:De},Symbol.toStringTag,{value:"Module"})),Ye=m.createLogger({name:"kos-service-request-manager",group:"Model"});function Op(t,e){return!t.condition||t.condition(e)}function Ip(t,e){return Ee({value:t.path,modelId:e.id,modelData:e})}function $p(t,e){if(t.pathParams)return Ee({value:typeof t.pathParams=="function"?t.pathParams(e):t.pathParams,modelId:e.id,modelData:e})}function Cp(t,e){if(t.queryParams)return Ee({value:typeof t.queryParams=="function"?t.queryParams(e):t.queryParams,modelId:e.id,modelData:e})}function Dp(t,e){if(t.body)return Ee({value:typeof t.body=="function"?t.body(e):t.body,modelId:e.id,modelData:e})}function xp(t){return(t||"get").toLowerCase()}function Si(t,e){return`${e.toUpperCase()}:${t}`}function qc(t){return t==null}function Ap(t,e,s,r){r&&qc(t)&&Ye.warn(`Required field '${e}' is missing in response for ${s}`)}function Rp(t,e){return qc(t)&&e!==void 0?e:t}class Pp{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)[et]||{};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&&Ye.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||(Ye.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 Op(e,this.model)?!0:(Ye.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=Ip(e,this.model),r=$p(e,this.model),o=Cp(e,this.model),n=Dp(e,this.model),i=xp(e.method);return{resolvedPath:s,method:i,pathParams:r,queryParams:o,body:n}}async performRequest(e){return await this.makeRequest(e.resolvedPath,e.method,{path:e.pathParams,query:e.queryParams},e.body)}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:ue.SINGLE},a=Si(r,s.method||"get");this.responseStore.set(a,e,i,o,n),await s.originalHandler.call(this.model,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){const n=De;switch(s){case"get":return await n.get(e,r);case"post":return await n.post(e,r,o);case"put":return await n.put(e,r,o);case"delete":return await n.delete(e,r,o);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;Ap(i,o.from,s.path,o.required||!1);const a=Rp(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 Ye.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):(Ye.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":Ye.error(`Service request failed for ${s.path}:`,e.message);break;case"ignore":break;case"default":if(r.defaultValue!==void 0){const o=Si(s.path,s.method||"get");this.responseStore.set(o,r.defaultValue,s.cache||{retention:ue.SINGLE})}break}}}class kp{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 Oi(t){return new kp(t)}var zc=(t=>(t.GET="GET",t.PUT="PUT",t.POST="POST",t.DELETE="DELETE",t))(zc||{});const Vc=({path:t,requestId:e,method:s,destinationAddress:r})=>{let o=`${xr}:${s}
|
|
2
|
+
`;return o+=`topic:${t}
|
|
3
|
+
`,o+=`${Pt}:${t}
|
|
4
|
+
`,o+=`${Ds}:${e}
|
|
5
|
+
`,r&&(o+=`${Ne}:${r}
|
|
6
|
+
`),o+=`${Ie}:kos.studio.request
|
|
7
7
|
`,o+=`
|
|
8
|
-
`,o},
|
|
9
|
-
`;return i+=`${
|
|
10
|
-
`,i+=`${
|
|
11
|
-
`,i+=`${
|
|
12
|
-
`,r&&(i+=`${
|
|
13
|
-
`),o&&(i+=`${
|
|
14
|
-
`),n&&(i+=`${
|
|
15
|
-
`),i+=`${
|
|
8
|
+
`,o},Gc=({path:t,requestId:e,method:s,destinationAddress:r,ordered:o,tracker:n})=>{let i=`${la}:/http${t}
|
|
9
|
+
`;return i+=`${xr}:${s}
|
|
10
|
+
`,i+=`${Pt}:${t}
|
|
11
|
+
`,i+=`${fa}:${e}
|
|
12
|
+
`,r&&(i+=`${Ne}:${r}
|
|
13
|
+
`),o&&(i+=`${zo}:true
|
|
14
|
+
`),n&&(i+=`${Vo}:${n}
|
|
15
|
+
`),i+=`${Ie}:fos.http.request
|
|
16
16
|
`,i+=`
|
|
17
|
-
`,i},
|
|
18
|
-
`;return c+=`${
|
|
19
|
-
`,c+=`${
|
|
20
|
-
`,r&&(c+=`${
|
|
21
|
-
`),o&&(c+=`${
|
|
22
|
-
`),n&&(c+=`${
|
|
17
|
+
`,i},Yc=({path:t,requestId:e,method:s,destinationAddress:r,ordered:o,tracker:n,bridge:i,headers:a})=>{let c=`${xr}:${s}
|
|
18
|
+
`;return c+=`${Pt}:${t}
|
|
19
|
+
`,c+=`${Ds}:${e}
|
|
20
|
+
`,r&&(c+=`${Ne}:${r}
|
|
21
|
+
`),o&&(c+=`${zo}:true
|
|
22
|
+
`),n&&(c+=`${Vo}:${n}
|
|
23
23
|
`),a&&Object.keys(a).forEach(u=>{c+=`${u}:${a[u]}
|
|
24
|
-
`}),c+=`${
|
|
24
|
+
`}),c+=`${Ie}:${i?"fos":"kos"}.http.request
|
|
25
25
|
`,c+=`
|
|
26
|
-
`,c},
|
|
27
|
-
`;return r+=`${
|
|
28
|
-
`,r+=`${
|
|
29
|
-
`,r+=`${
|
|
30
|
-
`,r+=`${
|
|
26
|
+
`,c},ze=(t,e)=>{let s=t;return e&&(s+=e),s};function Wt(t){const e={...t};return{append(s,r){e[s]=r},delete(s){delete e[s]},get(s){return e[s]},forEach(s){Object.keys(e).forEach(r=>s(e[r],r,this))},has(s){return Object.hasOwn(e,s)},set(s,r){e[s]=r},keys(){return Object.keys(e)},values(){return Object.values(e)},entries(){return Object.entries(e)}}}function Qt(t){let e=!1;return window.ReadableStream?new ReadableStream({start(r){function o(){return Promise.resolve({done:e,value:t}).then(({done:n,value:i})=>{if(n){r.close();return}r.enqueue(i),e=!0,o()})}o()}}):t}const Wc=({path:t,requestId:e,destinationAddress:s})=>{let r=`topic:${t}
|
|
27
|
+
`;return r+=`${Pt}:${t}
|
|
28
|
+
`,r+=`${Ds}:${e}
|
|
29
|
+
`,r+=`${Ne}:${s}
|
|
30
|
+
`,r+=`${Ie}:kos.studio.request
|
|
31
31
|
`,r+=`
|
|
32
|
-
`,r},
|
|
33
|
-
`;return o+=`${
|
|
34
|
-
`,o+=`${
|
|
32
|
+
`,r},Qc=({requestId:t,destinationAddress:e,requestType:s,headers:r})=>{let o=`${Ds}:${t}
|
|
33
|
+
`;return o+=`${Ne}:${e}
|
|
34
|
+
`,o+=`${Ie}:${s}
|
|
35
35
|
`,r&&Object.keys(r).forEach(n=>{o+=`${n}:${r[n]}
|
|
36
36
|
`}),o+=`
|
|
37
|
-
`,o},
|
|
38
|
-
`;return o+=`${
|
|
39
|
-
`,
|
|
40
|
-
`),o+=`${
|
|
41
|
-
`,o+=`${
|
|
42
|
-
`,o+=`${
|
|
37
|
+
`,o},Lp=(t,e)=>{const s=t,r=ze(Qc(e),typeof s=="string"?s:JSON.stringify(s)),o=O.getInstance().transport.socket;o?(m.debug("Sending message",r),o.socket.send(r)):m.error("socket transport is not initialized")},Zc=({path:t,responseId:e,status:s,destinationAddress:r})=>{let o=`topic:${t}
|
|
38
|
+
`;return o+=`${Pt}:${t}
|
|
39
|
+
`,e&&(o+=`${Ar}:${e}
|
|
40
|
+
`),o+=`${qo}:${s}
|
|
41
|
+
`,o+=`${Ne}:${r}
|
|
42
|
+
`,o+=`${Ie}:kos.studio.response
|
|
43
43
|
`,o+=`
|
|
44
|
-
`,o},
|
|
45
|
-
`;return
|
|
46
|
-
`,
|
|
47
|
-
`,
|
|
48
|
-
`;return n+=`${
|
|
49
|
-
`,n+=`${
|
|
50
|
-
`,n+=`${
|
|
51
|
-
`,n+=`${
|
|
52
|
-
`,n+=`${
|
|
53
|
-
`,n+=`${
|
|
44
|
+
`,o},Fp=(t,e)=>{const s=t,r=ze(Wc(e),JSON.stringify(s)),o=O.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},Np=(t,e)=>{const s=e.responseId?{status:e.status,data:t}:t,r=ze(Zc(e),JSON.stringify(s)),o=O.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},Xc=({topic:t})=>{let e=`topic:${t}
|
|
45
|
+
`;return e+=`${Ie}:kos.broker.send
|
|
46
|
+
`,e+=`
|
|
47
|
+
`,e},Jc=({responseId:t,destinationAddress:e,type:s,sourceAddress:r,status:o})=>{let n=`${Ar}:${t}
|
|
48
|
+
`;return n+=`${Ne}:${e}
|
|
49
|
+
`,n+=`${ua}:${r}
|
|
50
|
+
`,n+=`${Ie}:${s??"kos.message.request"}
|
|
51
|
+
`,n+=`${qo}:${o}
|
|
52
|
+
`,n+=`${da}:application/json
|
|
53
|
+
`,n+=`${ha}:no-cache
|
|
54
54
|
`,n+=`
|
|
55
|
-
`,n},
|
|
56
|
-
`;return
|
|
57
|
-
`),o+=`${
|
|
58
|
-
`,o+=`${
|
|
55
|
+
`,n},el=({topic:t,responseId:e,destinationAddress:s,type:r})=>{let o=`topic:${t}
|
|
56
|
+
`;return e&&(o+=`${Ar}:${e}
|
|
57
|
+
`),o+=`${Ne}:${s}
|
|
58
|
+
`,o+=`${Ie}:${r??"kos.message.request"}
|
|
59
59
|
`,o+=`
|
|
60
|
-
`,o},
|
|
60
|
+
`,o},Up=({msg:t,options:e})=>{const s=t,r=ze(Xc(e),JSON.stringify(s)),o=O.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},tl=({msg:t,options:e})=>{const s=t,r=ze(el(e),JSON.stringify(s)),o=O.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},sl=({msg:t,options:e})=>{const s=t,r=ze(Jc(e),JSON.stringify(s)),o=O.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},So=(t,e)=>{try{return e?t.body??t:JSON.parse(t.body)}catch{return t.body||t}};class jp{constructor(e){l(this,"config");l(this,"stats");l(this,"filterHistory",[]);l(this,"activePromises",new Set);l(this,"eventQueue",[]);l(this,"rateLimitWindow",new Map);this.config=e,this.stats={eventsReceived:0,batchesProcessed:0,eventsDropped:0,currentQueueSize:0,averageBatchSize:0,processingRate:0,lastProcessedAt:Date.now()}}async*processEvents(e){const s=this.config.batch||{size:1,window:0};if(s.size===1&&!s.window)for await(const r of e)yield*this.processSingleEvent(r);else yield*this.processBatchedEvents(e,s)}async*processSingleEvent(e){if(this.stats.eventsReceived++,!(this.config.filter&&!this.shouldProcessEvent(e))){if(this.config.rateLimit&&!this.checkRateLimit())if(this.config.rateLimit.onExceeded==="drop"){this.stats.eventsDropped++;return}else this.config.rateLimit.onExceeded==="delay"&&await this.waitForRateLimit();if(this.config.backpressure){this.enqueueEvent(e),await this.waitForCapacity();const s=this.dequeueEvent();s&&(yield this.config.transform?this.config.transform([s]):[s],this.updateProcessingStats([s]))}else yield this.config.transform?this.config.transform([e]):[e],this.updateProcessingStats([e])}}async*processBatchedEvents(e,s){const r=s.size||100,o=s.window||1e3;let n=[],i=Date.now();const a=async()=>{if(n.length===0)return;const c=[...n];n=[],i=Date.now();const u=this.config.filter?c.filter(h=>this.shouldProcessEvent(h)):c;if(u.length===0)return;this.config.backpressure&&await this.waitForCapacity();const d=this.config.transform?this.config.transform(u):u;return this.stats.batchesProcessed++,this.updateProcessingStats(u),d};try{for await(const u of e)if(this.stats.eventsReceived++,this.config.backpressure)for(this.enqueueEvent(u);this.eventQueue.length>0;){const d=this.dequeueEvent();d&&n.push(d);const f=Date.now()-i;if(n.length>=r||f>=o){const p=await a();p!==void 0&&(yield p);break}}else{n.push(u);const h=Date.now()-i;if(n.length>=r||h>=o){const f=await a();f!==void 0&&(yield f)}}const c=await a();c!==void 0&&(yield c)}finally{}}shouldProcessEvent(e){if(!this.config.filter)return!0;const s={history:[...this.filterHistory],currentBatch:[],startTime:Date.now()},r=this.config.filter.predicate(e,s);return this.config.filter.historySize&&(this.filterHistory.push(e),this.filterHistory.length>this.config.filter.historySize&&this.filterHistory.shift()),r}checkRateLimit(){if(!this.config.rateLimit)return!0;const e=Date.now(),s=Math.floor(e/this.config.rateLimit.windowMs),r=this.rateLimitWindow.get(s)||0;if(r>=this.config.rateLimit.maxEvents)return!1;this.rateLimitWindow.set(s,r+1);for(const[o]of this.rateLimitWindow)o<s-1&&this.rateLimitWindow.delete(o);return!0}async waitForRateLimit(){if(!this.config.rateLimit)return;const e=Date.now(),o=(Math.floor(e/this.config.rateLimit.windowMs)+1)*this.config.rateLimit.windowMs-e;o>0&&await new Promise(n=>setTimeout(n,o))}async waitForCapacity(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxConcurrent||5,s=this.config.backpressure.maxQueue||1e3;for(;this.activePromises.size>=e;)await Promise.race(this.activePromises);this.eventQueue.length>=s&&this.handleQueueOverflow()}handleQueueOverflow(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxQueue||1e3,s=this.config.backpressure.dropPolicy||"oldest",r=this.config.backpressure.onQueueFull;if(s==="none")return;const o=this.eventQueue.length-e;if(o<=0)return;let n=[];if(s==="oldest"?n=this.eventQueue.splice(0,o):s==="newest"&&(n=this.eventQueue.splice(-o)),this.stats.eventsDropped+=n.length,this.stats.currentQueueSize=this.eventQueue.length,r&&n.length>0)try{r(n)}catch(i){console.warn("Error in onQueueFull callback:",i)}}enqueueEvent(e){if(this.eventQueue.push(e),this.stats.currentQueueSize=this.eventQueue.length,this.config.backpressure){const s=this.config.backpressure.maxQueue||1e3;this.eventQueue.length>s&&this.handleQueueOverflow()}}dequeueEvent(){const e=this.eventQueue.shift();return this.stats.currentQueueSize=this.eventQueue.length,e}updateProcessingStats(e){const s=Date.now(),r=s-this.stats.lastProcessedAt;this.stats.averageBatchSize=(this.stats.averageBatchSize*this.stats.batchesProcessed+e.length)/(this.stats.batchesProcessed+1),this.stats.processingRate=r>0?e.length/(r/1e3):this.stats.processingRate,this.stats.lastProcessedAt=s,this.stats.currentQueueSize=this.eventQueue.length}trackPromise(e){return this.activePromises.add(e),e.finally(()=>this.activePromises.delete(e)),e}getStats(){return{...this.stats}}}class Bp extends WebSocket{constructor(e){super(e)}}function Ii(t){const e=`
|
|
61
61
|
|
|
62
62
|
`,s=`
|
|
63
|
-
`,r=/:(.*)/s,[o,n]=
|
|
63
|
+
`,r=/:(.*)/s,[o,n]=t.split(e).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[u,d]=c.split(r).map(h=>h.trim());return u&&d&&(a[u]=d),a},{}),body:n}}function Kp(t){const e=`
|
|
64
64
|
|
|
65
65
|
`,s=`
|
|
66
|
-
`,r=/:(.*)/s,[,o,n]=
|
|
66
|
+
`,r=/:(.*)/s,[,o,n]=t.split(e).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[u,d]=c.split(r).map(h=>h.trim());return u&&d&&(a[u]=d),a},{}),body:n}}class yn{constructor({host:e,port:s,protocol:r,alias:o,onConnectionEstablished:n,onConnectionLost:i,Transport:a=Bp}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"socket");l(this,"connectionEstablished");l(this,"alias");l(this,"onConnectionEstablished");l(this,"onConnectionLost");l(this,"offlineMessages",[]);l(this,"oldSend");this.host=e,this.port=s,this.protocol=r,this.onConnectionEstablished=n,this.onConnectionLost=i,this.alias=o,this.socket=new a(`${this.protocol}${this.host}:${this.port}/events`),this.socket.onmessage=this.onMessage.bind(this),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.oldSend=this.socket.send,this.connectionEstablished=!1,C("/mock/msg/receive",c=>{var u,d;if(c!=null&&c.body){m.wsReceive(c==null?void 0:c.body);const h={data:c.body};(d=(u=this.socket)==null?void 0:u.onmessage)==null||d.call(u,h)}}),M.makeObservable(this,{connectionEstablished:M.observable})}addOfflineMessage(e){this.offlineMessages.push({msg:e})}processMessageEvent(e){const{data:s}=e;return Ii(s)}onMessage(e){try{m.debug("webSocketTransport: onMessage received");const{headers:s,body:r}=this.processMessageEvent(e);m.wsReceive(e.data);const o=s.subscription||s[this.RESPONSE_ID_HEADER]||s.topic||s.type;if(o){let n=r,i=s;if(o==="kos.sniffer.msg"){const{headers:a,body:c}=Kp(e.data);n=c,i={...s,...a}}V(o,n,i)}}catch(s){m.error("onMessage exception",s.message,s.stack)}}onOpen(e){m.info("websocket connection opened"),this.socket=e.currentTarget,M.runInAction(()=>{var s;this.connectionEstablished=!0,this.alias&&this.socket.send(`type:kos.addr.alias
|
|
67
67
|
alias:${this.alias}
|
|
68
68
|
|
|
69
|
-
`),m.debug(`sending ${this.offlineMessages.length} offline FOS messages`),this.offlineMessages.forEach(r=>{var o;m.debug(`sending offline message ${r.msg}`),(o=this.socket)==null||o.send(r.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(){this.socket&&this.socket.close(),
|
|
70
|
-
${
|
|
71
|
-
${o(n)}`};(r=(s=this.socket)==null?void 0:s.onmessage)==null||r.call(s,a)}else this.oldSend.call(this.socket,
|
|
72
|
-
`:"",d=r?`subscribe:${
|
|
69
|
+
`),m.debug(`sending ${this.offlineMessages.length} offline FOS messages`),this.offlineMessages.forEach(r=>{var o;m.debug(`sending offline message ${r.msg}`),(o=this.socket)==null||o.send(r.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(){this.socket&&this.socket.close(),M.runInAction(()=>{this.connectionEstablished=!1}),m.debug("websocket disconnected. Attempting calling callback"),this.onConnectionLost&&setTimeout(this.onConnectionLost,2500)}send(e){var s,r;if(m.wsSend(e),window.kosLogEvents){const{headers:o,body:n}=Ii(String(e));V(xs.SEND,{headers:o,body:n})}if(window.kosTopicIntercept&&window.kosEnableMocks){const{handler:o,requestId:n}=window.kosTopicIntercept(e);if(o){e=`mocked:true
|
|
70
|
+
${e}`;const a={data:`mocked:true
|
|
71
|
+
${o(n)}`};(r=(s=this.socket)==null?void 0:s.onmessage)==null||r.call(s,a)}else this.oldSend.call(this.socket,e)}else this.oldSend.call(this.socket,e)}}class Hp{constructor(e){l(this,"addEventListener");l(this,"dispatchEvent");l(this,"removeEventListener");l(this,"_onclose");l(this,"_onerror");l(this,"_onmessage");l(this,"_onopen");l(this,"messageQueue",[]);l(this,"isSending",!1);D.debug(`called Bridge Transport with addr ${e}`);const s=this;globalThis.kosWindowWebsocketRecv=r=>{if(s.onmessage){const o={data:r};s.onmessage(o)}},D.debug("Opening bridge transport"),globalThis.kosWindowWebsocketOpen(),D.debug("Opened bridge transport"),this._onclose=null,this._onerror=null,this._onmessage=null,this._onopen=null,this.addEventListener=()=>D.debug("not implemented"),this.dispatchEvent=()=>D.debug("not implemented"),this.removeEventListener=()=>D.debug("not implemented")}close(){D.debug("closing")}sendNextMessage(){if(this.messageQueue.length>0){const e=this.messageQueue.shift();globalThis.kosWindowWebsocketSend(e),setTimeout(()=>this.sendNextMessage(),1)}else this.isSending=!1}enqueueMessage(e){this.messageQueue.push(e),this.isSending||(this.isSending=!0,this.sendNextMessage())}send(e){globalThis.kosWindowWebsocketSend(e)}get onmessage(){return this._onmessage}set onmessage(e){this._onmessage=e}get onopen(){return this._onopen}set onopen(e){this._onopen=e}get onclose(){return this._onclose}set onclose(e){this._onclose=e}get onerror(){return this._onerror}set onerror(e){this._onopen=e}}class qp extends yn{constructor({host:s,port:r,alias:o}){super({host:s,port:r,Transport:Hp,alias:o,protocol:"kos://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}class zp extends yn{constructor({host:s,port:r}){super({host:s,port:r,protocol:"ws://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="requestId"}}class Vp extends yn{constructor({host:s,port:r,protocol:o,onConnectionEstablished:n,onConnectionLost:i,alias:a}){super({host:s,port:r,onConnectionEstablished:n,onConnectionLost:i,alias:a,protocol:o});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}window.kosEnableMocks=process.env.KOS_MOCK_WS==="true";window.kosLogEvents=process.env.KOS_LOG_WS==="true";class Oo{static build({host:e,port:s,protocol:r,fos:o,alias:n,onConnectionEstablished:i,onConnectionLost:a}){return m.debug("initializing websocket connection"),m.warn(`kosWindowWebsocketOpen: ${globalThis.kosWindowWebsocketOpen?"true":"false"}`),m.warn(`fos: ${o?"true":"false"}`),window.kosMockWs||globalThis.kosWindowWebsocketOpen&&!o?(m.warn("Using bridged message transport"),new qp({host:e,port:s,protocol:r,onConnectionEstablished:i,onConnectionLost:a,alias:n})):o?new zp({host:e,port:s,protocol:r,alias:n,onConnectionEstablished:i,onConnectionLost:a}):new Vp({host:e,port:s,protocol:r,alias:n,onConnectionEstablished:i,onConnectionLost:a})}}const Gp=me();Gp.fos&&(window.kosUseFos=!0);const $i=process.env.KOS_FOS_PORT;window.kosUseFos=!!(window.kosUseFos||process.env.KOS_USE_FOS==="true");window.kosFosPort=$i?parseInt($i):0;const Ge=D.getLogger("web-socket-transport");var rl=(t=>(t.NOT_INITIALIZED="not_initialized",t.INITIALIZED="initialized",t.OFFLINE="OFFLINE",t.ONLINE="ONLINE",t))(rl||{}),ps=(t=>(t.CONNECTED="websocket.connected",t.DISCONNECTED="websocket.disconnected",t.RELOAD="websocket.reload",t))(ps||{});class Mt{constructor({host:e="localhost",port:s=8080,protocol:r="ws://",token:o,initialize:n,alias:i,fos:a}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"_token");l(this,"webSocketSupported",!!globalThis.WebSocket);l(this,"authorized");l(this,"alias");l(this,"socket");l(this,"fosSocket");l(this,"fosPort");l(this,"useFosTransport");this.host=e,this.port=s,this.protocol=r,this._token=o,this.alias=i,this.authorized=process.env.KOS_ALLOW_ANONYMOUS==="true",this.useFosTransport=!!a,this.fosPort=a==null?void 0:a.port,this.socket=void 0,this.fosSocket=void 0;let c=!1;M.makeObservable(this,{authorized:M.observable,socket:M.observable,fosSocket:M.observable,init:M.action,connectionEstablished:M.computed}),M.reaction(()=>this.connectionEstablished,u=>{u&&(Ge.warn("Connection Established"),V("websocket.connected","websocket.connected"),c&&V("websocket.reload","websocket.reload"),c=!0)}),n&&this.init()}get connectionEstablished(){return!this.webSocketSupported||!this.socket||this.useFosTransport&&!this.fosSocket?!1:this.useFosTransport&&this.fosSocket?this.socket.connectionEstablished&&this.fosSocket.connectionEstablished:!this.useFosTransport&&this.socket?this.socket.connectionEstablished:!1}init(){var e,s;if(m.warn(`Initializing WebSocketTransport on ${this.host}:${this.port}`),this.useFosTransport&&(this.fosSocket=Oo.build({host:this.host,port:this.fosPort||9854,protocol:this.protocol,fos:!0})),this.socket=Oo.build({host:this.host,port:this.port,protocol:this.protocol,alias:this.alias,onConnectionLost:()=>{Ge.error("Connection Lost"),V("websocket.disconnected","websocket.disconnected"),this.init()}}),globalThis.kosWindowWebsocketOpen){const r={currentTarget:this.socket.socket};(s=(e=this.socket.socket)==null?void 0:e.onopen)==null||s.call(e,r)}return this}_sendSubscriptionMessage(e,s,r=!1,o=!1,n){var f,p,y,w;Ge.debug(`${s} to topic ${e}`);const i=me(),a=i==null?void 0:i.connId,c=n??a??((f=window==null?void 0:window.kosBridge)==null?void 0:f.call(window,"connId"));Ge.debug(`subscribing with connId ${c}`);const u=c?`dst-addr:${c}
|
|
72
|
+
`:"",d=r?`subscribe:${e}`:o?`type:fos.broker
|
|
73
73
|
cmd:${s}
|
|
74
|
-
${u}topics:${
|
|
74
|
+
${u}topics:${e}
|
|
75
75
|
`:`${u}type:kos.broker.${s}
|
|
76
76
|
|
|
77
|
-
["${t}"]`;if(r?(p=this.fosSocket)==null?void 0:p.connectionEstablished:(b=this.socket)==null?void 0:b.connectionEstablished){const M=r?this.fosSocket:this.socket;(w=M==null?void 0:M.socket)==null||w.send(d)}else{Ye.debug("no connection adding to offline messages");const M=r?this.fosSocket:this.socket;M==null||M.addOfflineMessage(d)}}subscribeTopic({topic:t,callback:s,fos:r,bridge:o,destinationAddress:n}){const{unsubscribe:i,count:a}=$(t,s);return Ye.debug(`Topic ${t} currently has ${a} subscribers`),this._sendSubscriptionMessage(t,"subscribe",r,o,n),()=>{const{count:c}=i();Ye.debug(`Topic ${t} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(t,"unsubscribe",r,o,n)}}async whenReady(){const t=this;return this.webSocketSupported?(await E.when(()=>{var s,r;return!!((s=t.socket)!=null&&s.connectionEstablished)&&(!t.useFosTransport||!!((r=t.fosSocket)!=null&&r.connectionEstablished))&&t.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(t){this._token=t,this.init()}static host(t="localhost"){return this.getInstance().host=t,this}static port(t=8080){return this.getInstance().port=t,this}static alias(t){this.getInstance().alias=t}static getInstance(t=8080,s){if(!this._instance){const r=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:t,token:s,fos:r})}return this._instance}}l(wt,"_instance");class vp{constructor(t){l(this,"config");l(this,"stats");l(this,"filterHistory",[]);l(this,"activePromises",new Set);l(this,"eventQueue",[]);l(this,"rateLimitWindow",new Map);this.config=t,this.stats={eventsReceived:0,batchesProcessed:0,eventsDropped:0,currentQueueSize:0,averageBatchSize:0,processingRate:0,lastProcessedAt:Date.now()}}async*processEvents(t){const s=this.config.batch||{size:1,window:0};if(s.size===1&&!s.window)for await(const r of t)yield*this.processSingleEvent(r);else yield*this.processBatchedEvents(t,s)}async*processSingleEvent(t){if(this.stats.eventsReceived++,!(this.config.filter&&!this.shouldProcessEvent(t))){if(this.config.rateLimit&&!this.checkRateLimit())if(this.config.rateLimit.onExceeded==="drop"){this.stats.eventsDropped++;return}else this.config.rateLimit.onExceeded==="delay"&&await this.waitForRateLimit();if(this.config.backpressure){this.enqueueEvent(t),await this.waitForCapacity();const s=this.dequeueEvent();s&&(yield this.config.transform?this.config.transform([s]):[s],this.updateProcessingStats([s]))}else yield this.config.transform?this.config.transform([t]):[t],this.updateProcessingStats([t])}}async*processBatchedEvents(t,s){const r=s.size||100,o=s.window||1e3;let n=[],i=Date.now();const a=async()=>{if(n.length===0)return;const c=[...n];n=[],i=Date.now();const u=this.config.filter?c.filter(h=>this.shouldProcessEvent(h)):c;if(u.length===0)return;this.config.backpressure&&await this.waitForCapacity();const d=this.config.transform?this.config.transform(u):u;return this.stats.batchesProcessed++,this.updateProcessingStats(u),d};try{for await(const u of t)if(this.stats.eventsReceived++,this.config.backpressure)for(this.enqueueEvent(u);this.eventQueue.length>0;){const d=this.dequeueEvent();d&&n.push(d);const f=Date.now()-i;if(n.length>=r||f>=o){const p=await a();p!==void 0&&(yield p);break}}else{n.push(u);const h=Date.now()-i;if(n.length>=r||h>=o){const f=await a();f!==void 0&&(yield f)}}const c=await a();c!==void 0&&(yield c)}finally{}}shouldProcessEvent(t){if(!this.config.filter)return!0;const s={history:[...this.filterHistory],currentBatch:[],startTime:Date.now()},r=this.config.filter.predicate(t,s);return this.config.filter.historySize&&(this.filterHistory.push(t),this.filterHistory.length>this.config.filter.historySize&&this.filterHistory.shift()),r}checkRateLimit(){if(!this.config.rateLimit)return!0;const t=Date.now(),s=Math.floor(t/this.config.rateLimit.windowMs),r=this.rateLimitWindow.get(s)||0;if(r>=this.config.rateLimit.maxEvents)return!1;this.rateLimitWindow.set(s,r+1);for(const[o]of this.rateLimitWindow)o<s-1&&this.rateLimitWindow.delete(o);return!0}async waitForRateLimit(){if(!this.config.rateLimit)return;const t=Date.now(),o=(Math.floor(t/this.config.rateLimit.windowMs)+1)*this.config.rateLimit.windowMs-t;o>0&&await new Promise(n=>setTimeout(n,o))}async waitForCapacity(){if(!this.config.backpressure)return;const t=this.config.backpressure.maxConcurrent||5,s=this.config.backpressure.maxQueue||1e3;for(;this.activePromises.size>=t;)await Promise.race(this.activePromises);this.eventQueue.length>=s&&this.handleQueueOverflow()}handleQueueOverflow(){if(!this.config.backpressure)return;const t=this.config.backpressure.maxQueue||1e3,s=this.config.backpressure.dropPolicy||"oldest",r=this.config.backpressure.onQueueFull;if(s==="none")return;const o=this.eventQueue.length-t;if(o<=0)return;let n=[];if(s==="oldest"?n=this.eventQueue.splice(0,o):s==="newest"&&(n=this.eventQueue.splice(-o)),this.stats.eventsDropped+=n.length,this.stats.currentQueueSize=this.eventQueue.length,r&&n.length>0)try{r(n)}catch(i){console.warn("Error in onQueueFull callback:",i)}}enqueueEvent(t){if(this.eventQueue.push(t),this.stats.currentQueueSize=this.eventQueue.length,this.config.backpressure){const s=this.config.backpressure.maxQueue||1e3;this.eventQueue.length>s&&this.handleQueueOverflow()}}dequeueEvent(){const t=this.eventQueue.shift();return this.stats.currentQueueSize=this.eventQueue.length,t}updateProcessingStats(t){const s=Date.now(),r=s-this.stats.lastProcessedAt;this.stats.averageBatchSize=(this.stats.averageBatchSize*this.stats.batchesProcessed+t.length)/(this.stats.batchesProcessed+1),this.stats.processingRate=r>0?t.length/(r/1e3):this.stats.processingRate,this.stats.lastProcessedAt=s,this.stats.currentQueueSize=this.eventQueue.length}trackPromise(t){return this.activePromises.add(t),t.finally(()=>this.activePromises.delete(t)),t}getStats(){return{...this.stats}}}class wp{constructor(t,s,r,o,n){l(this,"disposers",[]);l(this,"activatableDisposers",[]);l(this,"flowControllers",new Map);this.model=t,this.modelData=s,this.modelId=r,this.offlineQueue=o,this.log=n}registerAll(t){var o;const s=((o=this.modelData)==null?void 0:o[ee])||{},r=Object.keys(s);this.log.debug(`Found ${r.length} subscriptions in ${this.modelId} (lifecycle: ${t??"any"})`),r.forEach(n=>{const i=s[n],a=i.lifecycle;if(t&&t!==a)return;const c=this.resolvePropKey(n);if(this.log.debug(`Resolved topic: ${n} → ${c}`),i.flow)this.subscribeWithFlowControl(i,c,a);else{const u=this.createHandler(c,i);this.subscribe(i,c,u,a===H.ACTIVATE)}})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const t of this.activatableDisposers)try{t()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const t=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${t.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 t)try{s()}catch(r){this.log.error("Error during subscription disposal",r)}this.disposers=[],this.activatableDisposers=[]}subscribe(t,s,r,o){const n=t.destinationAddress?this.resolvePropKey(t.destinationAddress):null;if(t.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=wt.getInstance().subscribeTopic({topic:s,callback:r,fos:t.fos,bridge:t.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=$(s,r);o?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(t,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(t,r,s);if(this.model.isReady()){const u=Eo(r,s.skipParse),d=s.transform(u);if(a&&s.condition(d,this.modelData,r))return this.callHandlerWithWildcard(s,d,c,r)}else{this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${t}`);const u=()=>{const d=Eo(r,s.skipParse),h=s.transform(d);if(a&&s.condition(h,this.modelData,r))return this.callHandlerWithWildcard(s,h,c,r)};this.offlineQueue.enqueue(u)}}catch(n){this.log.error(`Error handling subscription for ${t}`,n)}}}extractWildcardCapture(t,s,r){var n;if(!r.wildcardName||!Ec(t))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return wc(t,o,r.wildcardName)}callHandlerWithWildcard(t,s,r,o){if(r&&Object.keys(r).length>0){const n={...o,wildcardCapture:r};return t.handler.call(this.modelData,s,n,this.modelData)}else return t.handler.call(this.modelData,s,o,this.modelData)}resolvePropKey(t){const s=/.*({PROP_(.+)})/;let r=t.includes("{MODEL_ID}")?t.replace("{MODEL_ID}",this.modelId):t;const o=r.match(s);return o&&o[2]in this.modelData&&(r=r.replace(o[1],this.modelData[o[2]])),r}async subscribeWithFlowControl(t,s,r){this.log.debug(`Setting up flow control for topic: ${s}`);const o=new vp(t.flow);this.flowControllers.set(s,o);const n=this.createFlowControlHandler(s,t),i=this.startFlowProcessing(t,s,n,o),a=()=>{this.flowControllers.delete(s),i.then(c=>c==null?void 0:c.abort())};r===H.ACTIVATE?this.activatableDisposers.push(a):this.disposers.push(a)}async startFlowProcessing(t,s,r,o){const n=new AbortController;try{let i;if(t.websocket){const a=t.destinationAddress?this.resolvePropKey(t.destinationAddress):null;wt.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:t.fos,bridge:t.bridge,destinationAddress:a}),i=Ei(s)}else i=Ei(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(t,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 ${t}`);const c=()=>s.handler.call(this.modelData,r,r,this.modelData);this.offlineQueue.enqueue(c)}}catch(c){if(this.log.error(`Error in flow control handler for ${t}:`,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(t,s,r){const o=t.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)),t.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 t={};for(const[s,r]of this.flowControllers)t[s]=r.getStats();return t}}function ct(e,t){const s=`[Model:${t}]`;return{debug:(...r)=>e.debug(s,...r),info:(...r)=>e.info(s,...r),warn:(...r)=>e.warn(s,...r),error:(...r)=>e.error(s,...r)}}function Ep(e){return!!(e!=null&&e[Ze])&&Object.keys(e[Ze]).length>0}function Mp(e){return!!(e!=null&&e[ee])&&Object.keys(e[ee]).length>0}function Tp(e){return!!(e!=null&&e[xe])&&e[xe].length>0}class _p{static createAll(t){const{modelId:s,modelTypeName:r,modelData:o}=t,n=ac.create({modelId:s,modelTypeName:r}),i=new rp(t,ct(n,"fsm")),a=new np(ct(n,"offline-queue")),c=new Wf(t),u=new qf(t),d={fsm:i,offlineQueue:a,companionManager:c,childResolver:u};if(Ep(o)&&(d.effectManager=new Qf(r,s,o,ct(n,"effect"))),Mp(o)){const h=ct(n,"subscription");d.subscriptionManager=new wp(t,o,s,a,h),d.onlineLifecycleManager=new ip(t,ct(n,"online"))}return Tp(o)&&(d.httpRouteManager=new un(o,ct(n,"http-routes"))),d}}const L=C.getLogger("kos-model"),Op="kos.extension.model.loader";class Wc{constructor({modelTypeName:t,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,"offlineQueue");l(this,"subscriptionManager");l(this,"effectManager");l(this,"httpRouteManager");l(this,"onlineLifecycleManager");l(this,"companionManager");l(this,"childResolver");l(this,"fsm");this._id=typeof s<"u"?`${s}`:t,this.modelTypeName=t,this.initialized=!1,this.loaded=!1,this.modelData=r,this._status=v.CREATED,this._activeStatus=v.INACTIVE,this._onlineStatus=v.OFFLINE;const o=_p.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.httpRouteManager&&(this.httpRouteManager=o.httpRouteManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),E.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),Vf(this)}get companionModels(){return this.companionManager}set status(t){this._status=t}get status(){return this._status}get modelId(){return this._id}get id(){return this._id}get activeStatus(){return this._activeStatus}set activeStatus(t){this._activeStatus=t}get onlineStatus(){return this._onlineStatus}set onlineStatus(t){this._onlineStatus=t}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 t,s,r;L.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=V.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.deactivate)==null?void 0:s.call(t,o)),L.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw L.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var t,s,r;L.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await zt(this,H.ACTIVATE);try{const o=V.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.activate)==null?void 0:s.call(t,o)),L.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(r=this.subscriptionManager)==null||r.registerAll(H.ACTIVATE),L.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(o){throw L.debug(`Model ${this.modelId} failed to activate`),o}}async whenLoaded(){await io([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{L.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await io([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{L.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await io([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===v.READY,onMatch:()=>{L.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var t,s,r;if(this.fsm.current===v.READY){L.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{L.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await zt(this,H.READY),await Pc(this,cn.READY,H.READY);const o=V.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.ready)==null?void 0:s.call(t,o)),this.offlineQueue.flush(),(r=this.subscriptionManager)==null||r.registerAll(H.READY),L.debug(`Model ${this.modelId} is ready`);const n={modelId:this.modelId,modelType:this.modelTypeName};z(Mc(this.modelTypeName,this.modelId),n),z(Tc(this.modelTypeName),n)}catch(o){throw L.error(o),Error(o)}}async load(){var o,n,i,a,c;const t=this[bt];t&&await t.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===v.LOADED||this.fsm.current===v.LOADING){L.debug(`Model ${s} with id ${r} already loaded or loading`);return}L.debug(`Loading model ${s} with id ${r}`),await zt(this,H.LOAD);try{const u=V.getContext(r),d=`${Op}.${s}`,h=await S.loader.executeLoader(d,{});h&&(L.info(`Setting loaded context for ${r}, type: ${s}`),u==null||u.set(d,h)),await((n=(o=this.modelData)==null?void 0:o.load)==null?void 0:n.call(o,u)),X(()=>{this.loaded=!0}),L.debug(`Model ${s} with id ${r} successfully loaded`),(i=this.subscriptionManager)==null||i.registerAll(H.LOAD),(a=this.httpRouteManager)==null||a.registerAll(),(c=this.effectManager)==null||c.setup()}catch(u){throw L.error(`Model ${r} failed to load`,u),u}}async unload(){var t,s,r,o,n,i;L.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const a=this.getChildren().map(u=>{var d;return(d=u.unload)==null?void 0:d.call(u)}).filter(u=>!!u);await Promise.allSettled(a);const c=V.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.unload)==null?void 0:s.call(t,c)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),L.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(o=this.effectManager)==null||o.disposeAll(),(n=this.subscriptionManager)==null||n.disposeAll(),(i=this.httpRouteManager)==null||i.dispose()}catch(a){throw L.debug(`Model ${this.modelId} failed to unload`),a}}async init(){var n,i,a;const t=this[bt];t&&await t.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=V.getContext(s);L.debug(`Initializing model ${r} with id ${s}`),await zt(this,H.INIT);try{await((i=(n=this.modelData)==null?void 0:n.init)==null?void 0:i.call(n,o)),this.initialized=!0,L.debug(`Model ${r} with id ${s} initialized`),(a=this.onlineLifecycleManager)==null||a.register(),this.registerSubscribers(H.INIT)}catch(c){throw L.error(`Model ${s} failed to initialize`,c),c}}async registerSubscribers(t){var s;L.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(t)}async online(){var s,r;L.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const t=V.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,t))}async offline(){var s,r,o;L.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const t=V.getContext(this.modelId);await((o=(r=this.modelData)==null?void 0:r.offline)==null?void 0:o.call(r,t))}accept(t){t.visit(this)}getChildren(){return this.childResolver.resolve()}addCompanionModel(t){this.companionManager.add(t)}clearCompanionModels(){this.companionManager.clear()}}const Qc=e=>typeof e=="function",_i=m.createLogger({name:"kos-model-instantiator"});class Ip{constructor(t,s){this.registry=t,this.cache=s}createModelInstance(t,s,r={}){const o=this.registry.models[t];if(!o)throw new Error(`No model registered for type ${t}`);const n=o.singleton?t:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){_i.debug(`Creating model instance: ${t} [${n}]`);const a=o.create?o.create({modelTypeId:t,id:n,options:r}):new o.class(n,r),c=new Wc({modelTypeName:t,id:n,modelData:a});this.cache.addModel(c),this._createCompanionModels(c,r)}const i=this.cache.getModelById(n);if(!i)throw _i.error(`Model ${t} [${n}] not found in cache`),new Error(`Model ${t} [${n}] not found in cache`);return{model:i,data:i.modelData}}_createCompanionModels(t,s){var n;const r=t.modelTypeName,o=((n=this.registry.companionModels)==null?void 0:n[r])||[];for(const{type:i}of o){const a=Qc(i)?i(t.modelData,s):i;if(!a)continue;const c=`${a}-${t.modelId}`,u=this.createModelInstance(a,c,{data:s,companionParent:t.modelData,kosParentId:t.modelId});u!=null&&u.model&&(u.model[bt]=t,t.addCompanionModel(u.model))}}}let Sp=class{constructor(t){this._registry=t}get registry(){return this._registry}getModelTypeRegistry(t){const s=this.registry.models[t];if(!s)throw new Error(`No registration for model type ${t}`);return s}registerModel(t){const s=t.type;this.registry.models[s]||(this.registry.models={...this.registry.models,...t.registration})}registerCompanionModel(t,s){var r,o;(r=this.registry).companionModels??(r.companionModels={}),(o=this.registry.companionModels)[t]??(o[t]=[]),this.registry.companionModels[t].some(n=>n.type===s)||this.registry.companionModels[t].push({type:s})}getModelSubscriptions(t){var s;return((s=this.getModelTypeRegistry(t))==null?void 0:s.subscriptions)||{}}getDataModelBuilder(t){var r;const s=(r=this.getModelTypeRegistry(t))==null?void 0:r.builder;if(!s)throw new Error(`No builder found for model type ${t}`);return s}getModelFactory(t){return Rt(t)}};const Zc=10,Oi=m.createLogger({name:"kos-model-manager"});class Xc{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new ef,globalThis.kos.modelManager=this,globalThis.kos.resolveKosModel=t=>{const s=this.getModelById(t);if(s)return s.modelData||{}},globalThis.kos.kosModelJson=t=>{var r,o;const s=this.getModelById(t);if(s)return((o=(r=s.modelData).toJSON)==null?void 0:o.call(r))||{}},globalThis.kos.kosModelDebug=t=>{var r;const s=this.getModelById(t);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(t,s){const r=this.getInstance(s);return r._registry=new Sp(t),r.cache=new tf(t.preloadModels),r.instantiator=new Ip(t,r.cache),r}static getInstance(t){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||t)&&(Oi.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(t=>(Oi.debug(`preloading ${t}`),typeof t=="string"?this.createModelInstance(t).model:this.createModelInstance(t.modelType,t.modelId,t.options).model))}get models(){return this.cache.models}getModelById(t){return this.cache.getModelById(t)}addModel(t){return this.cache.addModel(t)}removeModel(t){this.cache.removeModel(t.modelId)}hasModel(t){return this.cache.hasModel(t)}getModelsByType(t,s){return Array.from(this.models).filter(r=>r.modelTypeName===t).filter(r=>s?s(r.modelData):!0).map(r=>r.modelData)}getModelSubscriptions(t){return this._registry.getModelSubscriptions(t)}getDataModelBuilder(t){return this._registry.getDataModelBuilder(t)}getModelFactory(t){return Rt(t)}addDependency(t,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(t,s)}removeDependency(t,s){this.dependencies.remove(t,s)}async reloadModel(t){if(t.id){const s=this.getModelById(t.id);s&&await s.fsm.transitionTo(R.RESET,v.RESETTING)}}async initiateDestroyModel(t){if(!t.id)throw new Error("Model ID is required");if(!this.dependencies.canDestroy(t.id))return;const s=this.getModelById(t.id);s&&(this.cache.markForDeletion(s),sc.addToDeletionQueue(t.id,setTimeout(()=>this.destroyModel(s),Zc)))}async destroyModel(t){var s;t!=null&&t.modelId&&this.dependencies.canDestroy(t.modelId)&&(await((s=t.unload)==null?void 0:s.call(t)),this.removeModel(t))}createModelInstance(t,s,r={}){return this.instantiator.createModelInstance(t,s,r)}registerCompanionModel(t,s){this._registry.registerCompanionModel(t,s)}registerModel(t){this._registry.registerModel(t)}}var qs=(e=>(e.CREATING="creating",e.CREATED="created",e.INITIALIZING="initializing",e.INITIALIZED="initialized",e.LOADING="loading",e.LOADED="loaded",e.ONLINE="online",e.READYING="readying",e.READY="ready",e.OFFLINE="offline",e.UNLOADING="unloading",e.UNLOADED="unloaded",e.RELOADING="reloading",e))(qs||{}),ft=(e=>(e.CREATE="create",e.INITIALIZE="init",e.READY="ready",e.GO_ONLINE="go_online",e.GO_OFFLINE="go_offline",e.UNLOAD="unload",e.RELOAD="reload",e))(ft||{});const $p=e=>{const t=y.createMachine("offline",{online:y.state(y.transition("go_offline","offline",y.action(()=>{e.offline(),E.runInAction(()=>{e.isOnline=!1})}))),offline:y.state(y.transition("go_online","online",y.action(()=>{e.online(),E.runInAction(()=>{e.isOnline=!0})})))}),s=y.interpret(t,n=>C.debug(n.machine.current)),r=y.createMachine({creating:y.state(y.transition("create","created")),created:y.state(y.immediate("initializing")),initializing:y.invoke(()=>e.init(),y.transition("done","initialized")),initialized:y.state(y.immediate("loading")),loading:y.invoke(()=>e.load(),y.transition("done","loaded")),loaded:y.state(y.immediate("readying"),y.transition("unload","unloading")),readying:y.invoke(()=>e.ready(),y.transition("done","ready",y.action(()=>{E.runInAction(()=>{e.status="ready"})}))),reloading:y.invoke(()=>e.reload(),y.transition("done","loading")),ready:y.state(y.transition("reload","reloading"),y.transition("unload","unloaded",y.action(e.unload.bind(e))),y.transition("go_online","ready",y.action(()=>{s.send("go_online")})),y.transition("go_offline","ready",y.action(()=>{s.send("go_offline")}))),unloaded:y.state()});return{service:y.interpret(r,n=>C.debug(n.machine.current)),online:s}},q=m.createLogger({name:"kos-core"}),Cp=()=>{const e=ge(),t=e==null?void 0:e.alias,s=process.env.KOS_CONNECTION_ALIAS;return t||s||void 0},Dp=()=>{const e=window.location.protocol,t=ge(),s=t==null?void 0:t.host;let r;try{r=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return r||(e==="https:"?"wss://":"ws://")},xp=()=>{const e=window.location.hostname,t=process.env.KOS_HOST,s=ge(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??t??e},Ap=()=>{const e=window.location.port,t=process.env.KOS_PORT,s=ge(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??t??e},Pp=(e,t)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{t?m.error(`Model ${t.modelId} - ${t.modelTypeName} preloading - timed out after ${e}ms`):m.error(`KOS Core preloading timed out after ${e}ms`),i(new Error(`Model ${t==null?void 0:t.modelId} - ${t==null?void 0:t.modelTypeName} - timed out after ${e}ms`))},e)}),cancel:()=>{s&&clearTimeout(s)}}},Ii=e=>typeof e.reload=="function",Rp=e=>typeof e.unload=="function";var Jc=(e=>(e.LOGGED_IN="logged_in",e.LOGGED_OUT="logged_out",e))(Jc||{});class I{constructor(t){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=t,this.loaded=!1,this.isOnline=!1,this.status=qs.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,E.makeAutoObservable(this),$("token",a=>{a&&(this.transport.token=a.body)}),$(us.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(ft.GO_ONLINE)}),$(us.DISCONNECTED,async()=>{this.fsmService.service.send(ft.GO_OFFLINE)}),$("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),$("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),$(us.RELOAD,()=>{q.warn("WebSocket requested reload"),this.fsmService.service.send(ft.RELOAD)}),$("/studio/project/reload",()=>{q.warn("Project requested reload"),this.fsmService.service.send(ft.RELOAD)});const s=wt.getInstance(),r=xp(),o=Ap(),n=Dp();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=Cp()??t;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=$p(this),this.fsmService.service.send(ft.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 t=Date.now();if(this._reloading){q.info("reload already in progress");return}this._reloading=!0,q.warn("reloading KOS Core"),q.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)Ii(c.modelData)&&(q.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),q.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&Ii(c.modelData)&&((i=c.unload)==null||i.call(c),await c.modelData.reload(),(a=c.registerSubscribers)==null||a.call(c));const r=Date.now()-t;setTimeout(()=>{E.runInAction(()=>{q.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){q.debug("KOS Core going online"),await this._transport.whenReady(),q.debug("KOS Transport Ready. Calling online() for models"),z("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){q.debug("KOS Core going offline"),z("/kosCore/offline","/kosCore/offline")}async unload(){var o;q.debug("Unloading KOS Core");const t=Date.now();this._unloading=!0,q.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)Rp(n.modelData)&&((o=n.unload)==null||o.call(n));const r=Date.now()-t;setTimeout(()=>{E.runInAction(()=>{this._unloading=!1})},1e3-r)}async whenReady(){await E.when(()=>this.status===qs.READY)}async ready(){q.debug("Readying KOS Core"),await this._transport.whenReady();const t=this.modelManager.preloadedModels.map(o=>({modelId:o.modelId,model:o,promise:o.whenReady()})),r=(await Promise.allSettled(t.map(o=>{const{promise:n,cancel:i}=Pp(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw q.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);q.debug("leaving kos-core ready() ")}get isReady(){return this.status===qs.READY}set transport(t){this._transport=t}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){q.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,q.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){q.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,q.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(t,s,r){var i,a,c;const o=this.getInstance({reset:s,connectionAlias:r});(i=t.extensions)!=null&&i.dataMapper&&Object.keys(t.extensions.dataMapper).forEach(u=>{var h,f;const d=(f=(h=t.extensions)==null?void 0:h.dataMapper)==null?void 0:f[u];d&&(Array.isArray(d)?d.forEach(p=>{S.dataMapper.registerDataMapper(u,p)}):S.dataMapper.registerDataMapper(u,d))}),(a=t.extensions)!=null&&a.propertyMapper&&Object.keys(t.extensions.propertyMapper).forEach(u=>{var h,f;const d=(f=(h=t.extensions)==null?void 0:h.propertyMapper)==null?void 0:f[u];d&&S.propertyMapper.registerPropertyMapper(u,d)}),(c=t.extensions)!=null&&c.contextLoader&&Object.keys(t.extensions.contextLoader).forEach(u=>{var h,f;const d=(f=(h=t.extensions)==null?void 0:h.contextLoader)==null?void 0:f[u];d&&S.loader.registerLoader(u,d)}),x.model.getAll().forEach(([,u])=>{t.models={...t.models,...u.registration}}),t.models={...t.models,...x.model.getLegacyModels()},x.companion.getAll().forEach(([u,d])=>{t.companionModels={...t.companionModels},t.companionModels[u]=t.companionModels[u]||[];for(const h of d)t.companionModels[u].push({type:h})}),x.model.getPreloadModels().forEach(u=>{t.preloadModels.includes(u)||t.preloadModels.push(u)});const n=Xc.create(t,s);return o.modelManager=n,o}static getInstance(t){return this._instance=window.KosCore,(!this._instance||t!=null&&t.reset)&&(window.KosCore=new this(t==null?void 0:t.connectionAlias),this._instance=window.KosCore),this._instance}}l(I,"_instance");function To(e){const t=new Uint8Array(e);let s="";for(let r=0;r<t.byteLength;r++)s+=String.fromCharCode(t[r]);return btoa(s)}function kp(e){const t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return s.buffer}async function Lp(e){return await e.arrayBuffer()}function Fp(e,t){return new Blob([e],{type:t})}async function Np(e){const t={},s=[],r=[];e.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:To(i)})}else t[o]=n.toString();return{fields:t,files:s}}function Up(e){return new ReadableStream({async start(){},async pull(t){await e(t)},cancel(){}})}async function jp(e){if(!e)return{data:"",contentType:"text/plain"};if(typeof e=="string")return{data:e,contentType:"text/plain"};if(e instanceof ArrayBuffer||e instanceof Uint8Array){let t;return e instanceof Uint8Array?(t=new ArrayBuffer(e.byteLength),new Uint8Array(t).set(e)):t=e,{data:To(t),contentType:"application/octet-stream",encoding:"base64"}}if(e instanceof Blob){const t=await Lp(e);return{data:To(t),contentType:e.type||"application/octet-stream",encoding:"base64"}}if(e instanceof FormData){const t=await Np(e);return{data:JSON.stringify(t),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const Ns=m.createLogger({name:"kos-fetch"}),Bp=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,Kp=()=>new Promise(e=>{setTimeout(()=>{e(!0)},0)}),Hp=e=>e!=null&&e.studio?Fc:e!=null&&e.fos?Nc:Uc,zp=async(e,t)=>{const s=I.getInstance().transport;await s.whenReady();const r=tt(),o=new URL(e),n=`${o.pathname}${o.search}`;Ns.debug(`path: ${n}`);const i=(t==null?void 0:t.timeout)||Bp,a=Hp(t),c=await jp(t==null?void 0:t.body),u={};c.contentType&&(u["content-type"]=c.contentType),c.encoding&&(u["content-encoding"]=c.encoding);const d=Ge(a({path:n,requestId:r,method:(t==null?void 0:t.method)||"GET",destinationAddress:(t==null?void 0:t.destinationAddress)||"",ordered:t==null?void 0:t.ordered,tracker:t==null?void 0:t.tracker,bridge:t==null?void 0:t.bridge,headers:{...t==null?void 0:t.headers,...u}}),c.data);return new Promise(h=>{let f=null,p=null;if(t!=null&&t.signal){if(t.signal.aborted){h({headers:Gt({}),status:0,ok:!1,json:async()=>null,body:Vt(""),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}t.signal.addEventListener("abort",()=>{p&&clearTimeout(p),f&&f(),h({headers:Gt({}),status:0,ok:!1,json:async()=>null,body:Vt(""),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(()=>{Ns.error(`Timeout occurred - url: ${e}`),f&&f(),h({headers:Gt({}),status:404,ok:!1,json:async()=>null,body:Vt(""),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 b=$(r,M=>{p&&clearTimeout(p);const _=(M==null?void 0:M.headers)||{},F=_["content-type"]||"text/plain",Q=_["content-encoding"],D=(M==null?void 0:M.body)||"";let O=D;if(Q==="base64"&&D)try{O=kp(D)}catch(B){Ns.error("Failed to decode base64 response",B)}const W={headers:Gt(_),status:_.status&&parseInt(_.status)||200,ok:_.status==="200",json:async()=>{try{if(typeof O=="string")return O.length?JSON.parse(O):null;{const J=new TextDecoder().decode(O);return J.length?JSON.parse(J):null}}catch{throw Error("Not a JSON response")}},text:async()=>typeof O=="string"?O:new TextDecoder().decode(O),arrayBuffer:async()=>O instanceof ArrayBuffer?O:new TextEncoder().encode(O).buffer,blob:async()=>O instanceof ArrayBuffer?Fp(O,F):new Blob([O],{type:F}),formData:async()=>{const B=new FormData;if(F==="multipart/form-data"&&typeof O=="string")try{const J=JSON.parse(O);J.fields&&Object.entries(J.fields).forEach(([Ue,$e])=>{B.append(Ue,$e)}),J.files&&Ns.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return B},body:t!=null&&t.stream?Up(async B=>{if(O instanceof ArrayBuffer)B.enqueue(new Uint8Array(O));else{const J=new TextEncoder;B.enqueue(J.encode(O))}B.close()}):Vt(typeof O=="string"?O:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};b.unsubscribe(),Kp().then(()=>h(W))});f=b.unsubscribe;const w=t!=null&&t.fos?s.fosSocket:s.socket;if(!w)throw Error(`No web socket transport available: ${t}`);w==null||w.send(d)})};exports.BASE_URL="kos:";exports.kosFetch=zp;if(process.env.KOS_MOCK_FETCH==="true"){const e=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${e}`}const Gp=m.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Vp{constructor(){l(this,"visitedModels",new Set);this.visitedModels=new Set}start(t){var r;if(t.id===void 0)throw new Error("rootModel must have an id");const s=I.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error(`Could not find rootModel with id: ${t.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(t){var r;if(this.visitedModels.has(t.modelId)){Gp.info(`model ${t.modelId} already visited`);return}const s=!!this.visitModel(t.modelData,this);this.visitedModels.add(t.modelId),!s&&((r=t.getChildren)==null||r.call(t).forEach(o=>{var n;(n=o.accept)==null||n.call(o,this)}))}}const el=()=>({isMock:!1,URL:exports.BASE_URL}),Yp=m.createLogger({name:"kos-service-request"}),qp="errUnknown";async function Us(e,t,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(e)):String(e),i=r!=null&&r.query?Object.keys(r.query).map(h=>`${h}=${r.query[h]}`).join("&"):"",a=`${el().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;Yp.debug(`fullUrl: ${a}`);const c={method:String(t).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||qp}`,null]:[null,(await u.json()).data]}function hn(){return{get:(e,t,s)=>Us(e,"get",s,t),post:(e,t,s,r)=>Us(e,"post",r,t,s),put:(e,t,s,r)=>Us(e,"put",r,t,s),delete:(e,t,s,r)=>Us(e,"delete",r,t,s)}}class tl{constructor(){l(this,"middlewares",[])}use(t){this.middlewares.push(t)}async execute(t){let s=0;const r=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](t,r)};await this.middlewares[s](t,r)}}const Wp=async(e,t)=>{const s=new tl;t.forEach(o=>s.use(o));const r={data:e,result:{}};return await s.execute(r),r.result},Rt=e=>({type:e,build:(t,s)=>I.getInstance().modelManager.createModelInstance(e,t,s).data,buildAsync:async(t,s)=>{const r=I.getInstance().modelManager.createModelInstance(e,t,s);return await r.model.whenInitialized(),r.data}}),Qp=e=>{I.getInstance().modelManager.registerModel(e)},Zp=(e,t)=>{I.getInstance().modelManager.registerCompanionModel(e,t)},Si="/kos/ui/internal/heartbeat/",Xp=({relationshipId:e,destinationAddress:t,onAbort:s,waitTime:r,beatTime:o})=>{const n=I.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${Si}${e}`,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(()=>{Vc({msg:{},options:{topic:`${Si}${e}`,destinationAddress:t}})},h),p=()=>{window.clearInterval(f),window.clearInterval(d),c()},b=()=>{p(),s&&s(),i.signal.removeEventListener("abort",b)};return i.signal.addEventListener("abort",b),{cleanUpHeartbeat:p}},sl=(...e)=>t=>e.reduce((s,r)=>r(s),t),Jp={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function eg(e,t){let s=1;const r={...Jp,...t},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await e()}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 tg=m.createLogger({name:"kos-service-request"}),ae=e=>({isMock:!1,URL:exports.BASE_URL}),sg=(e,t,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:c,bridge:u,destinationAddress:d})=>{const h={method:"DELETE"};e&&(h.destinationAddress=e),o&&(h.tracker=o),kt(h,{ordered:i,studio:a,fos:c,bridge:u,destinationAddress:d});const f=await s(n||`${t}/${r}`,h);if(!f.ok)throw Error(`There was a problem deleting the model; returned status ${f.status}`);return await f.json()},kt=(e,{ordered:t,studio:s,fos:r,destinationAddress:o,bridge:n,timeout:i})=>(i&&(e.timeout=i),t&&(e.ordered=t),s&&(e.studio=s),r&&(e.fos=r),n&&(e.bridge=n),(o||o==="")&&(e.destinationAddress=o),e),rg=(e,t,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:c,destinationAddress:u})=>{const d={method:"GET"};e&&(d.destinationAddress=e),kt(d,{timeout:c,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:u});const f=await s(r||t,d);if(!f.ok){let b;try{b=await f.json()}catch{}throw new pe(`There was a problem retrieving the model; returned status ${f.status}`,b)}return await f.json()},og=(e,t,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:c,timeout:u,destinationAddress:d})=>{const h={method:"GET"};e&&(h.destinationAddress=e),c&&(h.tracker=c),kt(h,{timeout:u,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:d});const f=r||t;tg.debug(`resolvedUrl: ${f}`);const p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new pe(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()},ng=(e,t,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:c,timeout:u,destinationAddress:d})=>{const h={method:"GET"};e&&(h.destinationAddress=e),kt(h,{timeout:u,ordered:n,studio:i,fos:a,bridge:c,destinationAddress:d});const f=r||`${t}/${o}`,p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new pe(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()};class pe extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const $i=(e,t,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)};e&&(f.destinationAddress=e),i&&(f.tracker=i),kt(f,{timeout:d,ordered:n,studio:a,fos:c,bridge:u,destinationAddress:h});const p=await s(o||t,f);if(!p.ok){let w;try{w=await p.json()}catch{}throw new pe(`There was a problem sending the POST data; returned status ${p.status}`,w)}return await p.json()},Ci=(e="POST",t,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:c,fos:u,bridge:d,timeout:h,destinationAddress:f})=>{const p={method:e};o&&(p.body=JSON.stringify(o)),t&&(p.destinationAddress=t),kt(p,{timeout:h,ordered:a,studio:c,fos:u,bridge:d,destinationAddress:f});const b=await r(i||`${s}/${n}`,p);if(!b.ok){let M;try{M=await b.json()}catch{}throw new pe(`There was a problem modifying the model; returned status ${b.status}`,M)}return await b.json()},oe={build:({destinationAddress:e="",basePath:t,getAllPath:s,getOnePath:r,deleteModelPath:o,addModelPath:n,modifyModelPath:i,mock:a=!1})=>{const c=a?fetch:exports.kosFetch;return{getAll:rg(e,s||t,c),getModelById:ng(e,r||t,c),getOne:og(e,r||t,c),addModel:$i(e,n||t,c),deleteModel:sg(e,o||t,c),modifyModel:Ci("POST",e,i||t,c),putModel:Ci("PUT",e,i||t,c),postModel:$i(e,n||t,c)}}},ig=tt(),rl=()=>`kos-${ig}`,ag=e=>!!e&&!e.includes("VM_SERVICE")&&e.startsWith(rl()),fn=async(e,t=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=$(e,i=>{C.debug(`recieved response for refId ${e}: ${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 ${e} timed out. Cancelling.`))},t)}),cg=async(e,t,s)=>{const r=fn(s),o=await Promise.allSettled([e(t),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)},lg=async({topic:e,msg:t,requestId:s})=>{const r=s??tt(),o=fn(r);z(e,t,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},de=new Map;class ol{constructor(t){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=t,this._context=new E.ObservableMap({}),this._parent="",E.makeAutoObservable(this)}setParent(t){X(()=>{this._parent=t})}get id(){return this._id}get context(){return this._context}get parentModel(){var t;if(this._parent)return(t=_e(this._parent))==null?void 0:t.model}get companionModels(){const t=_e(this._id);return t!=null&&t.model?mc(t.model):[]}get(t){var s,r;if(this._context.has(t))return this._context.get(t);if(this.companionModels.length>0){const o=this.companionModels.find(n=>{var i;return!n.id||!de.has(n.id)?!1:(i=de.get(n.id))==null?void 0:i.context.has(t)});if(o)return(s=de.get(o.id))==null?void 0:s.get(t)}if(this._parent)return(r=de.get(this._parent))==null?void 0:r.get(t)}set(t,s){this._context.set(t,s)}remove(t){this._context.delete(t)}clear(){this._context.clear()}}const V={createContext:(e,t)=>{const s=de.get(e)??new ol(e);if(t){if(!de.has(t))throw new Error(`Parent context ${t} does not exist`);s.setParent(t)}else e!=="root"&&s.setParent("root");return de.set(e,s),s},getContext:e=>de.get(e),deleteContext:e=>{de.delete(e)},setParentContext:(e,t)=>{var s;if(!de.has(t))throw new Error(`Parent context ${t} does not exist`);(s=de.get(e))==null||s.setParent(t)},rootContext:()=>de.get("root")};V.createContext("root");const ug=e=>V.getContext(e.id),ao=m.createLogger({name:"kos-data-container"});class pn{constructor(t){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"idx");this._data=E.observable.map(new Map),this._sortKey=t==null?void 0:t.sortKey,this._revision=1,this._optionsMap=(t==null?void 0:t.indexMap)||{};const s=t!=null&&t.indexMap?Object.keys(t.indexMap).reduce((r,o)=>(r[o]=void 0,r),{}):{};this._index=E.observable.map(s),this.idx=Te(),E.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],r=new nn({container:this,key:s});this._index.set(t,r),this.idx[t]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get indexKeys(){return Array.from(this.index.keys()).reduce((t,s)=>{var r;return t[s]=(r=this.index.get(s))==null?void 0:r.keys,t},{})}get revision(){return this._revision}addAll(t){E.runInAction(()=>{t.forEach(s=>this.addModel(s))})}removeAll(t){E.runInAction(()=>{t.forEach(s=>this.removeModel(s))})}sortFn(t,s){const r=this._sortKey;return r?String(t[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const t=Array.from(this._data.values());return this._sortKey&&t.sort(this.sortFn.bind(this)),t}increment(){E.runInAction(()=>{this._revision=this._revision+1})}addModel(t,s){const r=E.isObservable(t)?t:E.observable.object(t),o=this._disposerMap.get(t.id);o&&(o(),this._disposerMap.delete(t.id)),this._data.set(r.id||"",r),s||this.increment();const n=E.observe(r,i=>{Object.values(this._optionsMap||{}).includes(i.name)&&this.increment()});this._disposerMap.set(r.id||"",n)}removeModel(t){this._data.delete(t),this.increment();const s=this._disposerMap.get(t);s&&(s(),this._disposerMap.delete(t))}updateModel(t){const s=E.observable.object(t);this._data.set(s.id||"",s),this.increment()}getModel(t){return this._data.get(t)}getIndexKeys(t){return this.index.has(t)?this.index.get(t).keys??[]:(ao.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(t,s){if(this.index.has(t)){const r=this.index.get(t);return r.index.has(s)?r.getByKey(s):(ao.info(`key ${s} not found in ${t} index: ${Array.from(r.index.keys())}`),[])}else return ao.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.clear(),this.increment()}filter(t,s){return this.data.filter(t,s)}sort(t){return this.data.sort(t)}map(t,s){return this.data.map(t,s)}forEach(t,s){this.data.forEach(t,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id}))}}}class dg{constructor({type:t,model:s,childRegistration:r}){l(this,"type");l(this,"childRegistration");l(this,"model");this.type=t,this.model=s,this.childRegistration=r}get factory(){return ie.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return Ee(this.type)}}class hg{constructor({type:t,model:s,childRegistration:r}){l(this,"type");l(this,"model");l(this,"childRegistration");this.type=t,this.model=s,this.childRegistration=r}get factory(){return ie.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return Ee(this.type)}}class nl{constructor(){l(this,"_token");E.makeAutoObservable(this),$("token",t=>{this.token=t==null?void 0:t.body})}get token(){return this._token}set token(t){this._token=t}}class il{constructor(){l(this,"routes",[]);l(this,"openApiRoutes",[])}use(t,s,...r){this.routes.push({method:t,path:s,middlewares:r});const o=this.extractOpenApiParams(s);this.openApiRoutes.push({method:t,path:s,parameters:o})}remove(t,s){const r=this.routes.length;return this.routes=this.routes.filter(o=>!(o.method===t&&o.path===s)),this.openApiRoutes=this.openApiRoutes.filter(o=>!(o.method===t&&o.path===s)),r-this.routes.length}removeAllForPath(t){const s=this.routes.length;return this.routes=this.routes.filter(r=>r.path!==t),this.openApiRoutes=this.openApiRoutes.filter(r=>r.path!==t),s-this.routes.length}getRoutes(){return this.routes.map(t=>({method:t.method,path:t.path}))}async handle(t,s){var a;const{path:r,query:o,params:n}=this.extractPathParams(t.path),i={...t,params:n,query:o};for(const c of this.routes){const u=this.matchRoute(c.path,r);if(c.method===t.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(t){return t.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const t={};for(const s of this.openApiRoutes)t[s.path]||(t[s.path]={}),t[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:t}}extractPathParams(t){const[s,r]=t.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(t,s){const r=t.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(t){return t?t.split("&").reduce((s,r)=>{const[o,n]=r.split("=").map(decodeURIComponent);return s[o]=n??"",s},{}):{}}}const al=m.createLogger({name:"intent-service"}),fg=e=>{zo(`/kos/intent/${e.type}`)?z(`/kos/intent/${e.type}`,e.options,{"kos.intent.type":e.type}):al.info(`No subscribers for intent ${e.type}. Intent not sent.`)},pg=async e=>new Promise(t=>{const{type:s,options:r}=e;if(zo(`/kos/intent/${e.type}`)){const o=tt(),{unsubscribe:n}=$(o,a=>{clearTimeout(i),n(),a&&(a.headers=a.headers||{},a.headers["kos.intent.type"]=s,a.headers.responseId=o),t([null,{body:a==null?void 0:a.body,payload:a}])}),i=setTimeout(()=>{n(),t([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);z(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else al.info(`No subscribers for intent ${e.type}. Intent not sent.`),t([null,{body:void 0,payload:void 0}])}),De=m.createLogger({name:"app-startup-service"});async function cl(e,t={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=t;if(e.length===0)return De.warn("No app IDs provided to waitForAppsToStart"),!0;De.debug(`Waiting for apps to start: ${e.join(", ")}`);try{const n=e.map(c=>`/kos/app/started/${c}`),i=await Yo(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>by),[u,d]=await c.get("/api/kos/apps/started");return u?(De.error("Error fetching started apps:",u),[]):d}catch(c){De.error("Failed to fetch app startup status:",c)}return[]},shouldUseFetchedState:c=>e.every(u=>{const d=c.find(h=>h.appId===u);return!(!d||!d.started||o&&!d.postStarted)}),timeout:s}),a=e.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(De.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return De.info(`All apps started successfully: ${e.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${e.join(", ")}`;if(De.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function gg(e,t={}){return cl([e],t)}async function mg(e,t=!1){const s={};try{const r=await exports.kosFetch("kos:///api/kos/apps/started");if(!r.ok)return e.forEach(i=>s[i]=!1),s;const o=await r.json(),n=(o==null?void 0:o.data)??[];e.forEach(i=>{const a=n.find(c=>c.appId===i);s[i]=(a==null?void 0:a.started)===!0&&(!t||(a==null?void 0:a.postStarted)===!0)})}catch(r){De.error("Failed to check app startup status:",r),e.forEach(o=>s[o]=!1)}return s}async function yg(){try{const e=await exports.kosFetch("kos:///api/kos/apps/started");if(!e.ok)return[];const t=await e.json();return(t==null?void 0:t.data)??[]}catch(e){return De.error("Failed to fetch started apps:",e),[]}}const _o=E.when,gn=E.computed,X=E.runInAction,Y=E.autorun,ll=E.reaction,mn=E.observable,yn="Not Assigned",bg="kos.trouble.added",vg="kos.trouble.removed";var be=(e=>(e.TroubleRank="kos.trouble.rank.mapper",e.TroubleColor="kos.trouble.color.mapper",e.TroubleRole="kos.trouble.role.mapper",e))(be||{}),ds=(e=>(e.TIME_CHANGE="/kos/internal/time/time",e.DAY_CHANGE="/kos/internal/time/day",e.TIMEZONE_CHANGE="/kos/internal/time/timezone",e))(ds||{});const ul=m.createLogger({name:"config-bean-service",group:"Services"}),bn=exports.BASE_URL,dl=e=>(e==null?void 0:e.decimals)!==void 0,{postModel:wg,getOne:Eg}=oe.build({destinationAddress:"",basePath:`${bn}/kos/config/`}),hl=async(e,t,s="/api/kos/config")=>(ul.debug(`sending modify request for ConfigBean: ${e}`),wg({model:t,urlOverride:`${bn}${s}/${e}`})),fl=async(e,t="/api/kos/config")=>(ul.debug(`sending get request for ConfigBean: ${e}`),await Eg({urlOverride:`${bn}${t}/details/${e}/15`})),vn=e=>e.toLowerCase()==="true"||e.toLowerCase()==="false",kr=e=>{try{const t=Number(e);return!isNaN(t)}catch{return!1}};function pl(e=[]){return e.reverse().reduce((t,s)=>{const{overrides:r}=s;return r&&(t={...t,...r}),t},{})}function gl(e,t="",s={}){for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)){const o=t?`${t}.${r}`:r;typeof e[r]=="object"&&e[r]!==null&&!Array.isArray(e[r])?gl(e[r],o,s):s[o]=e[r]}return s}const ml=(e,t)=>{const s=e.details[0].bean||pl(e.details[0].scopes),r=gl(s);E.runInAction(()=>{const o={...r};t.props.setValues(o)})},yl=(e,t)=>{E.runInAction(()=>{e.changes.forEach(s=>{const r=s.attr;let o=s.currentValue,n=s.previousValue;typeof o=="string"&&vn(o)&&(o=o.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof o=="string"&&kr(o)&&(o=Number(o),n=Number(n)),t.props[r]=o,t.prevProps[r]=n})})},bl=e=>Object.fromEntries(e.props.entries),Mg=e=>t=>s=>e.build(t,s);var Tg=Object.defineProperty,_g=Object.getOwnPropertyDescriptor,vl=(e,t,s,r)=>{for(var o=r>1?void 0:r?_g(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Tg(t,s,o),o};function Og(e,t){for(const s of e)if(new RegExp(`^${s}$`).test(t))return s}const wn="config-bean-model",js=m.getLogger(wn),Ig=st("path");let sr=class{constructor(e,t){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,t),this.id=e,this.path=t.path,this.serviceBasePath=t.serviceBasePath;const{modifyConfigBean:s=hl,getConfigBean:r=fl}=t;this._modifyConfigBean=s,this._getConfigBean=r,this.props=Te(),this.prevProps=Te()}get values(){return this.props.values}async ready(){js.debug(`readying config bean ${this.path}`),js.debug(`complete readying config bean ${this.path}`)}async load(){js.debug(`loading config bean ${this.path}`);const e=await this._getConfigBean(this.path,this.serviceBasePath);if(e!=null&&e.data){const t=e.data;ml(t,this),js.debug(this.values);const s=e==null?void 0:e.data.details[0].schema;X(()=>{s&&(this._schema=s)})}}get schemaKeys(){var e;return Object.keys(((e=this._schema)==null?void 0:e.schema)||{})}getSchemaForProperty(e){var s,r;if(this.schemaKeys.includes(e))return(s=this._schema)==null?void 0:s.schema[e];const t=Og(this.schemaKeys,e);if(t)return(r=this._schema)==null?void 0:r.schema[t]}async updateProperty(e,t){this.props[e]=t,await this.updateConfigBean()}async updateConfigBean(){const e=bl(this);await this._modifyConfigBean(this.path,e,this.serviceBasePath)}handleConfigBeanUpdated(e){yl(e,this)}};vl([U({topic:`/kos/config/${Ig}`,websocket:!0})],sr.prototype,"handleConfigBeanUpdated",1);sr=vl([A(wn)],sr);const ps=new me({class:sr,type:wn}),Lr=({path:e,lazy:t,serviceBasePath:s})=>(r,o)=>{r[k]=r[k]||{},r[k][o]={modelType:ps.type,id:`${ps.type}-${e}`,options:{path:e,serviceBasePath:s},lifecycle:H.INIT,lazy:t}},{URL:wl}=ae(),{getOne:Sg,getAll:$g}=oe.build({basePath:`${wl}/api/kos/regions/info`}),El=async()=>{try{return await Sg({})}catch{return}},Ml=async()=>{try{return await $g({urlOverride:`${wl}/api/kos/regions`})}catch{return}},Cg=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:El,getRegions:Ml},Symbol.toStringTag,{value:"Module"}));var le=(e=>(e[e.family=0]="family",e[e.scale=1]="scale",e[e.offset=2]="offset",e[e.decimals=3]="decimals",e[e.alias=4]="alias",e[e.system=5]="system",e))(le||{});const Tl={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 Dg(e,t){const s=t.id,r=t.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},{...Tl});return{...e,...r}}function xg(e,t){const s=t.id,r=t.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,Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,n.alias&&(o[n.alias]=i),o},{time:{[s]:{...Tl}}});return Object.keys(r).forEach(o=>{e[o]={...e[o],...r[o]}}),e}function Ag(e,t){const s=t.id,r=t.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=>{e[o]={...e[o],...r[o]}}),e}var Pg=Object.defineProperty,Rg=Object.getOwnPropertyDescriptor,En=(e,t,s,r)=>{for(var o=r>1?void 0:r?Rg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Pg(t,s,o),o};const Ws="region-info-model",Ht=m.createLogger({name:"region-info-model"});let gs=class{constructor(e){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=e,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 e=this.regionSource.props.timeFormatId;if(!e)return"";const t=String(e),s=this.timeFormats[t];return s?String(s.id):""}get selectedTimeFormat(){const e=this.timeFormatId;return e?String(this.timeFormats[e].format):"HH:mm:ss"}get is12HourTimeFormat(){const e=this.timeFormatId;return e?this.timeFormats[e].ampm:!0}get dateFormatId(){const e=this.regionSource.props.dateFormatId;if(!e)return"";const t=String(e);return t?this.dateFormats[t].id:""}get selectedDateFormat(){const e=this.dateFormatId;return e?this.dateFormats[e].format:""}get selectedDateOrder(){const e=this.dateFormatId;return e?this.dateFormats[e].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(e=>({id:e,format:this.timeFormats[e].format,ampm:this.timeFormats[e].ampm}))}get dateFormatOptions(){return Object.keys(this.dateFormats).map(e=>({id:e,format:this.dateFormats[e].format,order:this.dateFormats[e].order}))}get unitSystemOptions(){return Object.keys(this.unitSystems).map(e=>({id:e,name:e}))}setSelectedTimeFormat(e){if(!this.timeFormatOptions.find(t=>t.id===e))throw Error(`Invalid time format id. Must be one of ${this.timeFormatOptions.map(t=>t.id).join(", ")}`);this.regionSource.updateProperty("timeFormatId",e)}setSelectedDateFormat(e){if(!this.dateFormatOptions.find(t=>t.id===e))throw Error(`Invalid date format id. Must be one of ${this.dateFormatOptions.map(t=>t.id).join(", ")}`);this.regionSource.updateProperty("dateFormatId",e)}setSelectedUnitSystem(e){if(!this.unitSystemOptions.find(t=>t.id===e))throw Error(`Invalid date format id. Must be one of ${this.unitSystemOptions.map(t=>t.id).join(", ")}`);this.regionSource.updateProperty("unitSystemId",e)}getUnitSystem(e){if(!e)return this.defaultUnitSystem;const t=e==="drt"?"second":e,s=this.unitSystemMap[t];if(!s)throw Error(`No unit found with name: ${t}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[le.system]}getUnitMeasure(e){const t=e==="drt"?"second":e,s=this.unitSystemMap[t];if(!s)throw Error(`No unit found with name: ${t}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[le.family]}getDefaultUnitDecimalPlaces(e,t,s){if(!e||!t)throw Error("Measure and unit system are required");const r=s==="drt"?"second":s,o=this.measureMap[e];if(!o)throw Error(`No unit systems found for measure: ${e}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const n=o[t.toLowerCase()];if(!n)throw Error(`No unit system found for measure: ${e} and unit system: ${t}. 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: ${e} and unit system: ${t}. Unit should come from list of units: ${Object.keys(n).join(", ")}`);return i[le.decimals]}getDefaultUnitForMeasure(e,t){if(!e||!t)throw Error("Measure and unit system are required");const s=this.defaultMeasureMap[e];if(!s)throw Error(`No unit systems found for measure: ${e}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const r=s[t.toLowerCase()];if(!r)throw Error(`No unit system found for measure: ${e} and unit system: ${t}. Unit system should come form list of unit systems: ${Object.keys(s).join(", ")}`);return r}convertByUnit(e,t,s){if(t[le.family]!==s[le.family])throw new Error(`Cannot convert between units of different families: ${t[le.family]} and ${s[le.family]}`);const r=t[le.offset],o=t[le.scale],n=s[le.scale],i=s[le.offset],a=s[le.decimals];return((e-r)/(o/n)+i).toFixed(a)}convertByUnitName(e,t,s){const r=this.unitSystemMap[t],o=this.unitSystemMap[s];if(!r||!o)throw new Error(`No unit found with name: ${t} or ${s}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return this.convertByUnit(e,r,o)}convert(e,t,s){var a,c;if(t.unit&&s.unit)return this.convertByUnitName(e,t.unit,s.unit);const r=t.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||Ht.info("Could not find default unit for measure",s.measure)}if(!n&&t.measure&&t.system){const u=this.measureMap[t.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(c=u[t.system])==null?void 0:c.default,n||Ht.info("Could not find default unit for measure",t.measure)}return!n||!i?(Ht.warn("Could not find unit to convert to or from. Return value as is"),String(e)):this.convertByUnit(e,n,i)}async init(){Ht.debug("initializing region info")}async load(){Ht.debug("loading region info");const e=await Ml();e&&(this.regions=e.data.map(s=>s.id),this.timeZoneMap=e.data.reduce((s,r)=>({...s,[r.id]:r.timeZones}),this.timeZoneMap),this.regionMap=e.data.reduce((s,r)=>({...s,[r.id]:r}),{}));const t=await El();t&&(this.unitSystems=t.data.unitSystems.reduce((s,r)=>{const o={id:r.id,name:r.id};return s[r.id]=o,s},this.unitSystems),this.unitSystemMap=t.data.unitSystems.reduce(Dg,{}),this.measureMap=t.data.unitSystems.reduce(xg,{}),this.defaultMeasureMap=t.data.unitSystems.reduce(Ag,{}),this.timeFormats=t.data.timeFormats.reduce((s,r)=>({...s,[r.id]:r}),{}),this.dateFormats=t.data.dateFormats.reduce((s,r)=>({...s,[r.id]:r}),{}))}async ready(){var e,t;await((t=(e=this.regionSource).ready)==null?void 0:t.call(e))}};En([Lr({path:"kos:service:region:settings"})],gs.prototype,"regionSource",2);En([Lr({path:"kos:service:region"})],gs.prototype,"region",2);gs=En([A(Ws)],gs);const re={registration:{[Ws]:{class:gs,singleton:!0}},type:Ws,factory:ie.Singleton.create(Ws)},rr=({source:e,defaultSystem:t="si",defaultMeasure:s})=>{let r={system:t,measure:s};return typeof e=="string"?r={...r,unit:e}:r={...r,...e},r},Mn=(e,t,s)=>{const{model:r}=_e(re.type);if(!r)throw new Error("RegionInfo model not found");if(!tr(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=rr({source:t}),i=rr({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(e,n,i)};function Di(e,t,s){const r=t.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(e)}catch{return t}}const kg=(e,t,s,r)=>{const o=Mn(e,t,s),n=rr({source:t}),{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=rr({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:Di(o,d||n.unit||"",{...f,mode:"long"}),shortDisplay:Di(o,d||n.unit||"",{...f,mode:"short"})}};function xi({start:e,end:t,count:s,decimals:r=0}){if(typeof e!="number"||typeof t!="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(e>=t)throw new Error("Start should be less than end.");const o=(t-e)/(s-1),n=[];for(let i=0;i<s;i++){const a=Math.round(e+i*o);n.push(a.toFixed(r))}return n}function Ai({start:e,end:t,interval:s,decimals:r=0}){if(typeof e!="number"||typeof t!="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(e>=t)throw new Error("Start should be less than end.");const o=[];let n=e;for(;n<=t;)o.push(n.toFixed(r)),n+=s;return o[o.length-1]!==t.toString()&&o.push(t.toString()),o}const lt=(e,t)=>s=>!e||!t?s:kr(s)?Mn(Number(s),e,t):s,Lg=(e,t,s,r)=>{if((e==null?void 0:e.type)==="enum"||!(e!=null&&e.options))return[];if(e.options.type==="rangeCount")return xi(e.options).map(lt(s,r));if(e.options.type==="rangeInterval")return Ai(e.options).map(lt(s,r));if(e.options.type==="list"){const{list:o}=e.options;return o.map(lt(s,r))}else{if(e.options.type==="unitSystemRangeCount"&&t)return xi(e.options.unitSystems[t]).map(lt(s,r));if(e.options.type==="unitSystemRangeInterval"&&t)return Ai(e.options.unitSystems[t]).map(lt(s,r));if(e.options.type==="unitSystemList"&&t){const{list:o}=e.options.unitSystems[t];return o.map(lt(s,r))}}return[]},Fg=(e,t)=>{if(!((e==null?void 0:e.type)==="enum"||!(e!=null&&e.options)))return e.options.type==="unitSystemRangeCount"&&t?{type:"rangeCount",...e.options.unitSystems[t]}:e.options.type==="unitSystemRangeInterval"&&t?{type:"rangeInterval",...e.options.unitSystems[t]}:e.options.type==="unitSystemList"&&t?{type:"list",...e.options.unitSystems[t]}:e.options.type==="unitSystemKeypad"&&t?{type:"keypad",...e.options.unitSystems[t]}:e.options};var Ng=Object.defineProperty,Ug=Object.getOwnPropertyDescriptor,Tn=(e,t,s,r)=>{for(var o=r>1?void 0:r?Ug(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Ng(t,s,o),o};function jg(e){return(e==null?void 0:e.type)==="enum"}function Bg(e){switch(e){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 e}}function Kg(e,t){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+e*1e3);return je.format(r,t)}const Qs="config-bean-prop-model",ut=m.createLogger({name:"config-bean-prop-model"}),Hg=st("path"),zg=st("serviceBasePath");let ms=class{constructor(e,t){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=e,this.path=t.path,this.attribute=t.attribute,this.converter=t.converter,this.formatter=t.formatter,this.serviceBasePath=t.serviceBasePath,this.optionsExpander=t.optionsExpander}getDefaultUnitDecimalPlaces(e,t,s){if(!e)throw new Error("measure is required");if(!t)throw new Error("unitSystem is required");return dl(this.displayOptions)?this.displayOptions.decimals:this.regionInfo.getDefaultUnitDecimalPlaces(e,t,s)}getDefaultUnitForMeasure(e,t){if(!e)throw new Error("measure is required");if(!t)throw new Error("unitSystem is required");return this.regionInfo.getDefaultUnitForMeasure(e,t)}get schemaType(){const e=this.bean.getSchemaForProperty(this.attribute);return e!=null&&e.type?e.type:"String"}get schemaFormat(){const e=this.bean.getSchemaForProperty(this.attribute);return e!=null&&e.format?Bg(e.format):""}get options(){var i;const e=this.regionInfo.defaultUnitSystem,t=this.getConverter(),s=((i=t==null?void 0:t.to)==null?void 0:i.system)??e,r=this.bean.getSchemaForProperty(this.attribute),o=jg(r)?r.values:Lg(r,s,t==null?void 0:t.from,t==null?void 0:t.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(e,t,s){const r=(e==null?void 0:e.measure)||s,o=(e==null?void 0:e.system)||t,n=e==null?void 0:e.unit;return{measure:r,system:o,unit:n}}getConverterUnits(){const e=this.regionInfo.defaultUnitSystem,t=this.getConverter();if(!t)throw Error("No converter defined");const s=t.measure,r=this.convertUnit(t.from,"si",s),o=this.convertUnit(t.to,e,s);return{backend:r,display:o}}set value(e){this.updateProperty(e)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var o,n;const e=this.value,t=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(e)&&s&&r){const i=this.getDefaultUnitDecimalPlaces(r,t,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const c=this.getFormatterOptions(s);if(c){let u=String(e);return u=c.formatToParts(Number(e))[0].value,Number(u)}}catch(c){ut.info(`error formatting value ${e}`,c)}return Number(e).toFixed(i)}return e}get previousValue(){return this.getValue(!1)}getValue(e){const t=this.bean[e?"props":"prevProps"][this.attribute];if(typeof t=="boolean")return t;if(this.getConverter()&&!isNaN(t)){const{backend:r,display:o}=this.getConverterUnits();return this.regionInfo.convert(Number(t),r,o)}return t||""}async activate(){ut.debug(`activating config bean ${this.id}`)}get displayValue(){const e=this.value;if(typeof e=="boolean")return String(e);if(this.schemaFormat==="drt"){const s=this.regionInfo.is12HourTimeFormat?"h:mm:ss a":"HH:mm:ss";return Kg(e,s)}if(!isNaN(e))try{const t=this.getConverter(),s=this.getFormatterOptions(t);if(s){let r=String(e);return r=s.format(Number(e)),r}}catch(t){ut.error(`error formatting value ${e}`,t)}return String(e)}get unit(){const e=this.getConverter();if(!isNaN(this.value)){const t=this.getFormatterOptions(e);if(t){const r=t.formatToParts(Number(this.value)).find(o=>o.type==="unit");return(r==null?void 0:r.value)??this.getDefaultUnit(e)}}return this.getDefaultUnit(e)}get displayOptions(){var o;const e=this.bean.getSchemaForProperty(this.attribute),t=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=((o=s==null?void 0:s.to)==null?void 0:o.system)??t;return Fg(e,r)}getMeasureFromFormat(){const e=this.schemaFormat;return e?this.regionInfo.getUnitMeasure(e):""}getConverterFromFormat(){const e=this.getMeasureFromFormat();if(e){const t=this.regionInfo.selectedUnitSystem;return{unit:this.schemaFormat||this.regionInfo.getDefaultUnitForMeasure(e,t),measure:e}}return{}}getDefaultUnit(e){var r,o;const t=this.regionInfo.defaultUnitSystem,s=e==null?void 0:e.measure;return s?((r=e==null?void 0:e.to)==null?void 0:r.unit)||this.getDefaultUnitForMeasure(s,((o=e==null?void 0:e.to)==null?void 0:o.system)||t):this.getConverterFromFormat().unit}getFormatterOptions(e){var n,i,a;const t=this.regionInfo.defaultUnitSystem,s=e==null?void 0:e.measure,r=new Intl.NumberFormat().resolvedOptions().locale;let o=null;if(s||this.formatter){const c=s?{style:"unit",unit:this.getDefaultUnit(e)}:null,u=this.formatter||c;if(u){let d=typeof u=="function"?u(((n=e==null?void 0:e.to)==null?void 0:n.system)||t):u;s&&(d={unit:this.getDefaultUnit(e),...d},d.style==="unit"&&(d.maximumFractionDigits=d.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=e==null?void 0:e.to)==null?void 0:i.system)||t,(a=e==null?void 0:e.to)==null?void 0:a.unit)));try{o=new Intl.NumberFormat(r,{...d})}catch(h){ut.error(`error creating formatter ${d}. Returning the raw value`,h)}}else ut.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:e,measure:t}=this.getConverterFromFormat(),s=e==="drt"?"second":e;if(this.converter){const b=(r=this.converter)==null?void 0:r.measure,w=(n=(o=this.converter)==null?void 0:o.to)==null?void 0:n.measure,M=(a=(i=this.converter)==null?void 0:i.from)==null?void 0:a.measure,_=b||w||M||t,F=((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),Q=((p=(f=this.converter)==null?void 0:f.to)==null?void 0:p.system)??this.regionInfo.getUnitSystem(F),D=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:D,...this.converter.from},to:{...this.converter.to,unit:F,system:Q},measure:_}}if(s&&t){const b=this.regionInfo.getDefaultUnitForMeasure(t,this.regionInfo.defaultUnitSystem),w=this.regionInfo.getUnitSystem(s),M=this.regionInfo.getUnitSystem(b);return{measure:t,to:{unit:w===M?s:b}}}}async updateProperty(e){ut.debug(`updating property ${this.attribute} with value ${e}`);let t=e;if(this.getConverter()&&!isNaN(t)){const{backend:o,display:n}=this.getConverterUnits();t=this.regionInfo.convert(Number(t),n,o)}const r=Array.isArray(t)?JSON.stringify(t):String(t);await this.bean.updateProperty(this.attribute,r)}};Tn([Pt({modelType:re.type})],ms.prototype,"regionInfo",2);Tn([Lr({path:Hg,serviceBasePath:zg})],ms.prototype,"bean",2);ms=Tn([A(Qs)],ms);const rt={registration:{[Qs]:{class:ms,singleton:!1}},type:Qs,factory:ie.Factory.create(Qs)};function Gg(e){const{path:t,attribute:s,converter:r,formatter:o,lazy:n,optionsExpander:i,serviceBasePath:a}=e,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[k]=u[k]||{},u[k][d]={modelType:rt.type,id:`${t}-${s}`,options:{path:t,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:H.INIT,lazy:n}}}const _l="future-model",Lt=Rt(_l),Fr=m.createLogger({name:"future-service",group:"Services"}),{isMock:Vg,URL:Ds}=ae();var Ke=(e=>(e.Success="SUCCESS",e.Fail="FAIL",e.Aborted="ABORT",e.Canceled="CANCEL",e))(Ke||{});const{getAll:Yg,modifyModel:qg,addModel:Wg,deleteModel:Qg,postModel:Zg}=oe.build({destinationAddress:"",basePath:`${Ds}/api/future`,mock:Vg}),Xg=async()=>await Yg({}),Ol=async(e,t="/api/kos/future")=>(Fr.info(`sending delete request for Future: ${e}`),await Qg({id:e,urlOverride:`${Ds}${t}/${e}`})),Il=async(e,t="/api/kos/future")=>(Fr.info("sending add request for Future"),await Wg({model:e,urlOverride:`${Ds}${t}`})),Jg=async(e,t,s="/api/kos/future")=>(Fr.info(`sending modify request for Future: ${e}`),qg({model:t,id:e,urlOverride:`${Ds}${s}/${e}`})),Sl=async(e,t="/api/kos/future")=>(Fr.info(`sending cancel request for Future: ${e}`),Zg({urlOverride:`${Ds}${t}/${e}/cancel`,ordered:!0,model:{}})),_n=e=>({id:String(e.id),progress:e.progress,remainingTimeMs:e.remainingTimeMs,endState:e.endState,reason:e.reason,clientData:e.clientData,reasonData:e.reasonData,note:e.note,tracker:e.tracker}),On=(e,t)=>{m.debug(`future dto ${e.id} end state ${e.endState}`),m.debug(`future model ${t.id} end state ${t.endState}`),t.endState?m.debug(`future model ${t.id} is already complete`):(m.debug(`updating future model ${t.id}`),E.runInAction(()=>{const s=_n(e);X(()=>{Object.keys(s).forEach(r=>{r==="id"?(t.futureId=s.id,s.tracker||(t.id=s.id)):r==="tracker"?t.id=s.tracker:t[r]=s[r]})})}))},$l=e=>t=>s=>e.build(String(t),s),In=e=>t=>sl(_n,$l(e)(t.tracker||t.id))(t);var em=Object.defineProperty,tm=Object.getOwnPropertyDescriptor,Cl=(e,t,s,r)=>{for(var o=r>1?void 0:r?tm(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&em(t,s,o),o};const co=m.getLogger(Lt.type);let or=class{constructor(e,t,s){l(this,"logger");l(this,"_cancelFuture");l(this,"futureId");Object.assign(this,t),this.logger=s.logger,this.id=e,this.futureId=t.id,this.namespace=t.namespace||"kos",this._cancelFuture=Sl,_o(()=>this.status===Ke.Success||this.status===Ke.Fail,()=>{co.info(`Future ${this.id} has completed with status ${this.status}`),Xe(this)})}async load(){co.debug(`loading Future ${this.id}`)}unload(){co.info(`unloading Future ${this.id}`)}async cancelFuture(){const e=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await _o(()=>this.futureId!==yn),await this._cancelFuture(this.futureId,e)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,c;const e=this.remainingTimeMs||-1;if(e<0)return"";const t={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(t))if(Math.abs(e)>=d){s=u,r=Math.round(e/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(e){this.logger.debug(`Future ${this.id} updated. future: ${e.id} endState: ${e.endState} progress: ${e.progress} remainingTimeMs: ${e.remainingTimeMs}`),On(e,this)}};Cl([U({topic:`kos.future/${Xs}`})],or.prototype,"handleFutureUpdated",1);or=Cl([A(Lt.type)],or);const Dl=or,xl=hn();var sm=Object.defineProperty,rm=Object.getOwnPropertyDescriptor,Al=(e,t,s,r)=>{for(var o=r>1?void 0:r?rm(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&sm(t,s,o),o};const Pl="browser-router-model",om="kos.http.request",nm="kos.http.response";let nr=class{constructor(e,t,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=e,this.logger=s.logger,this.router=new il}get id(){return this._id}async handleRequest(e,t){const s=t.headers["src-addr"],r=t.headers["dst-addr"],o=t.headers.url,n=t.headers.method,i=t.headers["request-id"],a={id:i,method:n,path:o,body:e};let c=200;const u={send:d=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(d),Yc({msg:d,options:{responseId:i,destinationAddress:s,type:nm,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(e,t,...s){this.router.use(e,t,...s)}remove(e,t){return this.router.remove(e,t)}removeAllForPath(e){return this.router.removeAllForPath(e)}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}`)}};Al([U({topic:om})],nr.prototype,"handleRequest",1);nr=Al([A(Pl)],nr);const Sn=new Me({class:nr,type:Pl}),Rl="future-container-model",He=Rt(Rl),kl=e=>In(Lt)(e),im=e=>{const t=kl(e);return He.build(He.type,{}).addFutureModel(t),t},am=e=>He.build(He.type,{}).getFuture(String(e)),Je={buildFutureModel:kl,initiateFuture:im,getFuture:am};var cm=Object.defineProperty,lm=Object.getOwnPropertyDescriptor,$n=(e,t,s,r)=>{for(var o=r>1?void 0:r?lm(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&cm(t,s,o),o};const Bs=m.getLogger(He.type);let ys=class{constructor(e,t,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=Ol,addFuture:o=Il}=t;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=e,this._futures=new Se,this.createModel=this.createFuture,this.deleteModel=this.removeFuture}get futures(){return this._futures.data}get models(){return this.futures}getFuture(e){return this._futures.getModel(e)}addFutureModel(e){this._futures.addModel(e)}removeFutureModel(e){this._futures.removeModel(e)}async removeFuture(e){try{await this._deleteFuture(e)}catch(t){Bs.error("error deleting a Future"),Bs.error(t)}}async createFuture(e){try{const t=await this._addFuture(e),s=t==null?void 0:t.data;if(s){const r=In(Lt)(s);return this.addFutureModel(r),r}}catch(t){throw Bs.error("error creating a Future"),Bs.error(t),t}}handleFutureUpdated(e,t){const s=Je.buildFutureModel(e);this.addFutureModel(s);const r=`kos.future/${e.tracker||e.id}`;this.logger.debug(`publishing future update to ${r}`),z(r,t.body,t.headers)}};$n([Ie],ys.prototype,"_futures",2);$n([U({topic:"kos.future"})],ys.prototype,"handleFutureUpdated",1);ys=$n([A(He.type)],ys);const Ll=ys,{URL:xs}=ae(),{getOne:um,postModel:dm,deleteModel:Fl}=oe.build({basePath:`${xs}/api/keyVal`}),Oo=m.createLogger({name:"key-value-service",group:"Services"}),Nl=async(e,t)=>{await Fl({urlOverride:`${xs}/api/keyVal/${e}/${t}`,id:t})},Ul=async(e,t,s)=>{const r=await dm({urlOverride:`${xs}/api/keyVal/${e}/${t}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw Oo.error("Failed to update key-value data",r),new Error(`Failed to update key-value data for namespace ${e}`);return r.data},jl=async(e="studio")=>{Oo.debug(`Retrieving all key-value data for namespace: ${e}`);const t=await um({urlOverride:`${xs}/api/keyVal/${e}`});if((t==null?void 0:t.status)!==200)throw Oo.error("Failed to retrieve key-value data",t),new Error(`Failed to retrieve key-value data for namespace ${e}`);return t.data},hm=async e=>{await Fl({urlOverride:`${xs}/api/keyVal/${e}`,id:""})},fm=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Nl,deleteKeyValueNamespace:hm,getKeyValue:jl,updateKeyValue:Ul},Symbol.toStringTag,{value:"Module"}));var pm=Object.defineProperty,gm=Object.getOwnPropertyDescriptor,Cn=(e,t,s,r)=>{for(var o=r>1?void 0:r?gm(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&pm(t,s,o),o};const Bl="key-value-model";let bs=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"namespace");l(this,"data");this.id=e,this.logger=s.logger,this.data=Te(),this.namespace=t.namespace||"studio"}async init(){this.logger.debug(`initializing studio-state ${this.id}`)}async updateState(e,t){this.logger.debug(`updating studio-state ${e} with value ${t}`),t!==void 0?(await Ul(this.namespace,e,t),this.data[e]=t):(await Nl(this.namespace,e),this.data[e]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const e=await jl(this.namespace);this.data.setValues(e)}handleStateUpdate(e){e.namespace===this.namespace&&(this.data[e.key]=e.value)}handleStateDelete(e){e.namespace===this.namespace&&(this.data[e.key]=void 0)}};Cn([U({topic:"/keyVal/set"})],bs.prototype,"handleStateUpdate",1);Cn([U({topic:"/keyVal/remove"})],bs.prototype,"handleStateDelete",1);bs=Cn([A(Bl)],bs);const Dn=new me({class:bs,type:Bl});var he="INUMBER",Ft="IOP1",Nt="IOP2",Ut="IOP3",Ae="IVAR",et="IVARNAME",Et="IFUNCALL",Nr="IFUNDEF",ne="IEXPR",xn="IEXPREVAL",ot="IMEMBER",Ur="IENDSTATEMENT",Mt="IARRAY";function P(e,t){this.type=e,this.value=t??0}P.prototype.toString=function(){switch(this.type){case he:case Ft:case Nt:case Ut:case Ae:case et:case Ur:return this.value;case Et:return"CALL "+this.value;case Nr:return"DEF "+this.value;case Mt:return"ARRAY "+this.value;case ot:return"."+this.value;default:return"Invalid Instruction"}};function jr(e){return new P(Ft,e)}function Fe(e){return new P(Nt,e)}function Kl(e){return new P(Ut,e)}function Io(e,t,s,r,o){for(var n=[],i=[],a,c,u,d,h=0;h<e.length;h++){var f=e[h],p=f.type;if(p===he||p===et)Array.isArray(f.value)?n.push.apply(n,Io(f.value.map(function(b){return new P(he,b)}).concat(new P(Mt,f.value.length)),t,s,r,o)):n.push(f);else if(p===Ae&&o.hasOwnProperty(f.value))f=new P(he,o[f.value]),n.push(f);else if(p===Nt&&n.length>1)c=n.pop(),a=n.pop(),d=s[f.value],f=new P(he,d(a.value,c.value)),n.push(f);else if(p===Ut&&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(he,d(a.value,c.value,u.value)),n.push(f));else if(p===Ft&&n.length>0)a=n.pop(),d=t[f.value],f=new P(he,d(a.value)),n.push(f);else if(p===ne){for(;n.length>0;)i.push(n.shift());i.push(new P(ne,Io(f.value,t,s,r,o)))}else if(p===ot&&n.length>0)a=n.pop(),n.push(new P(he,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 Hl(e,t,s){for(var r=[],o=0;o<e.length;o++){var n=e[o],i=n.type;if(i===Ae&&n.value===t)for(var a=0;a<s.tokens.length;a++){var c=s.tokens[a],u;c.type===Ft?u=jr(c.value):c.type===Nt?u=Fe(c.value):c.type===Ut?u=Kl(c.value):u=new P(c.type,c.value),r.push(u)}else i===ne?r.push(new P(ne,Hl(n.value,t,s))):r.push(n)}return r}function We(e,t,s){var r=[],o,n,i,a,c,u;if(An(e))return Ce(e,s);for(var d=e.length,h=0;h<d;h++){var f=e[h],p=f.type;if(p===he||p===et)r.push(f.value);else if(p===Nt)n=r.pop(),o=r.pop(),f.value==="and"?r.push(o?!!We(n,t,s):!1):f.value==="or"?r.push(o?!0:!!We(n,t,s)):f.value==="="?(a=t.binaryOps[f.value],r.push(a(o,We(n,t,s),s))):(a=t.binaryOps[f.value],r.push(a(Ce(o,s),Ce(n,s))));else if(p===Ut)i=r.pop(),n=r.pop(),o=r.pop(),f.value==="?"?r.push(We(o?n:i,t,s)):(a=t.ternaryOps[f.value],r.push(a(Ce(o,s),Ce(n,s),Ce(i,s))));else if(p===Ae)if(f.value in t.functions)r.push(t.functions[f.value]);else if(f.value in t.unaryOps&&t.parser.isOperatorEnabled(f.value))r.push(t.unaryOps[f.value]);else{var b=s[f.value];if(b!==void 0)r.push(b);else throw new Error("undefined variable: "+f.value)}else if(p===Ft)o=r.pop(),a=t.unaryOps[f.value],r.push(a(Ce(o,s)));else if(p===Et){for(u=f.value,c=[];u-- >0;)c.unshift(Ce(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===Nr)r.push(function(){for(var w=r.pop(),M=[],_=f.value;_-- >0;)M.unshift(r.pop());var F=r.pop(),Q=function(){for(var D=Object.assign({},s),O=0,W=M.length;O<W;O++)D[M[O]]=arguments[O];return We(w,t,D)};return Object.defineProperty(Q,"name",{value:F,writable:!1}),s[F]=Q,Q}());else if(p===ne)r.push(mm(f,t));else if(p===xn)r.push(f);else if(p===ot)o=r.pop(),r.push(o[f.value]);else if(p===Ur)r.pop();else if(p===Mt){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:Ce(r[0],s)}function mm(e,t,s){return An(e)?e:{type:xn,value:function(r){return We(e.value,t,r)}}}function An(e){return e&&e.type===xn}function Ce(e,t){return An(e)?e.value(t):e}function Pn(e,t){for(var s=[],r,o,n,i,a,c,u=0;u<e.length;u++){var d=e[u],h=d.type;if(h===he)typeof d.value=="number"&&d.value<0?s.push("("+d.value+")"):Array.isArray(d.value)?s.push("["+d.value.map(Pi).join(", ")+"]"):s.push(Pi(d.value));else if(h===Nt)o=s.pop(),r=s.pop(),i=d.value,t?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===Ut)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===Ae||h===et)s.push(d.value);else if(h===Ft)r=s.pop(),i=d.value,i==="-"||i==="+"?s.push("("+i+r+")"):t?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===Et){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());i=s.pop(),s.push(i+"("+a.join(", ")+")")}else if(h===Nr){for(o=s.pop(),c=d.value,a=[];c-- >0;)a.unshift(s.pop());r=s.pop(),t?s.push("("+r+" = function("+a.join(", ")+") { return "+o+" })"):s.push("("+r+"("+a.join(", ")+") = "+o+")")}else if(h===ot)r=s.pop(),s.push(r+"."+d.value);else if(h===Mt){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());s.push("["+a.join(", ")+"]")}else if(h===ne)s.push("("+Pn(d.value,t)+")");else if(h!==Ur)throw new Error("invalid Expression")}return s.length>1&&(t?s=[s.join(",")]:s=[s.join(";")]),String(s[0])}function Pi(e){return typeof e=="string"?JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"):e}function gt(e,t){for(var s=0;s<e.length;s++)if(e[s]===t)return!0;return!1}function Rn(e,t,s){s=s||{};for(var r=!!s.withMembers,o=null,n=0;n<e.length;n++){var i=e[n];i.type===Ae||i.type===et?!r&&!gt(t,i.value)?t.push(i.value):(o!==null&&(gt(t,o)||t.push(o)),o=i.value):i.type===ot&&r&&o!==null?o+="."+i.value:i.type===ne?Rn(i.value,t,s):o!==null&&(gt(t,o)||t.push(o),o=null)}o!==null&&!gt(t,o)&&t.push(o)}function ve(e,t){this.tokens=e,this.parser=t,this.unaryOps=t.unaryOps,this.binaryOps=t.binaryOps,this.ternaryOps=t.ternaryOps,this.functions=t.functions}ve.prototype.simplify=function(e){return e=e||{},new ve(Io(this.tokens,this.unaryOps,this.binaryOps,this.ternaryOps,e),this.parser)};ve.prototype.substitute=function(e,t){return t instanceof ve||(t=this.parser.parse(String(t))),new ve(Hl(this.tokens,e,t),this.parser)};ve.prototype.evaluate=function(e){return e=e||{},We(this.tokens,this,e)};ve.prototype.toString=function(){return Pn(this.tokens,!1)};ve.prototype.symbols=function(e){e=e||{};var t=[];return Rn(this.tokens,t,e),t};ve.prototype.variables=function(e){e=e||{};var t=[];Rn(this.tokens,t,e);var s=this.functions;return t.filter(function(r){return!(r in s)})};ve.prototype.toJSFunction=function(e,t){var s=this,r=new Function(e,"with(this.functions) with (this.ternaryOps) with (this.binaryOps) with (this.unaryOps) { return "+Pn(this.simplify(t).tokens,!0)+"; }");return function(){return r.apply(s,arguments)}};var vs="TEOF",N="TOP",Br="TNUMBER",zl="TSTRING",Pe="TPAREN",Tt="TBRACKET",Kr="TCOMMA",kn="TNAME",Ln="TSEMICOLON";function Gl(e,t,s){this.type=e,this.value=t,this.index=s}Gl.prototype.toString=function(){return this.type+": "+this.value};function G(e,t){this.pos=0,this.current=null,this.unaryOps=e.unaryOps,this.binaryOps=e.binaryOps,this.ternaryOps=e.ternaryOps,this.consts=e.consts,this.expression=t,this.savedPosition=0,this.savedCurrent=null,this.options=e.options,this.parser=e}G.prototype.newToken=function(e,t,s){return new Gl(e,t,s??this.pos)};G.prototype.save=function(){this.savedPosition=this.pos,this.savedCurrent=this.current};G.prototype.restore=function(){this.pos=this.savedPosition,this.current=this.savedCurrent};G.prototype.next=function(){if(this.pos>=this.expression.length)return this.newToken(vs,"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)+'"')};G.prototype.isString=function(){var e=!1,t=this.pos,s=this.expression.charAt(t);if(s==="'"||s==='"')for(var r=this.expression.indexOf(s,t+1);r>=0&&this.pos<this.expression.length;){if(this.pos=r+1,this.expression.charAt(r-1)!=="\\"){var o=this.expression.substring(t+1,r);this.current=this.newToken(zl,this.unescape(o),t),e=!0;break}r=this.expression.indexOf(s,r+1)}return e};G.prototype.isParen=function(){var e=this.expression.charAt(this.pos);return e==="("||e===")"?(this.current=this.newToken(Pe,e),this.pos++,!0):!1};G.prototype.isBracket=function(){var e=this.expression.charAt(this.pos);return(e==="["||e==="]")&&this.isOperatorEnabled("[")?(this.current=this.newToken(Tt,e),this.pos++,!0):!1};G.prototype.isComma=function(){var e=this.expression.charAt(this.pos);return e===","?(this.current=this.newToken(Kr,","),this.pos++,!0):!1};G.prototype.isSemicolon=function(){var e=this.expression.charAt(this.pos);return e===";"?(this.current=this.newToken(Ln,";"),this.pos++,!0):!1};G.prototype.isConst=function(){for(var e=this.pos,t=e;t<this.expression.length;t++){var s=this.expression.charAt(t);if(s.toUpperCase()===s.toLowerCase()&&(t===this.pos||s!=="_"&&s!=="."&&(s<"0"||s>"9")))break}if(t>e){var r=this.expression.substring(e,t);if(r in this.consts)return this.current=this.newToken(Br,this.consts[r]),this.pos+=r.length,!0}return!1};G.prototype.isNamedOp=function(){for(var e=this.pos,t=e;t<this.expression.length;t++){var s=this.expression.charAt(t);if(s.toUpperCase()===s.toLowerCase()&&(t===this.pos||s!=="_"&&(s<"0"||s>"9")))break}if(t>e){var r=this.expression.substring(e,t);if(this.isOperatorEnabled(r)&&(r in this.binaryOps||r in this.unaryOps||r in this.ternaryOps))return this.current=this.newToken(N,r),this.pos+=r.length,!0}return!1};G.prototype.isName=function(){for(var e=this.pos,t=e,s=!1;t<this.expression.length;t++){var r=this.expression.charAt(t);if(r.toUpperCase()===r.toLowerCase()){if(t===this.pos&&(r==="$"||r==="_")){r==="_"&&(s=!0);continue}else if(t===this.pos||!s||r!=="_"&&(r<"0"||r>"9"))break}else s=!0}if(s){var o=this.expression.substring(e,t);return this.current=this.newToken(kn,o),this.pos+=o.length,!0}return!1};G.prototype.isWhitespace=function(){for(var e=!1,t=this.expression.charAt(this.pos);(t===" "||t===" "||t===`
|
|
78
|
-
`||
|
|
79
|
-
`;break;case"r":s+="\r";break;case"t":s+=" ";break;case"u":var o=
|
|
80
|
-
`,s+1);while(s>=0&&s<this.pos);return{line:e,column:t}};G.prototype.parseError=function(e){var t=this.getCoordinates();throw new Error("parse error ["+t.line+":"+t.column+"]: "+e)};function j(e,t,s){this.parser=e,this.tokens=t,this.current=null,this.nextToken=null,this.next(),this.savedCurrent=null,this.savedNextToken=null,this.allowMemberAccess=s.allowMemberAccess!==!1}j.prototype.next=function(){return this.current=this.nextToken,this.nextToken=this.tokens.next()};j.prototype.tokenMatches=function(e,t){return typeof t>"u"?!0:Array.isArray(t)?gt(t,e.value):typeof t=="function"?t(e):e.value===t};j.prototype.save=function(){this.savedCurrent=this.current,this.savedNextToken=this.nextToken,this.tokens.save()};j.prototype.restore=function(){this.tokens.restore(),this.current=this.savedCurrent,this.nextToken=this.savedNextToken};j.prototype.accept=function(e,t){return this.nextToken.type===e&&this.tokenMatches(this.nextToken,t)?(this.next(),!0):!1};j.prototype.expect=function(e,t){if(!this.accept(e,t)){var s=this.tokens.getCoordinates();throw new Error("parse error ["+s.line+":"+s.column+"]: Expected "+(t||e))}};j.prototype.parseAtom=function(e){var t=this.tokens.unaryOps;function s(o){return o.value in t}if(this.accept(kn)||this.accept(N,s))e.push(new P(Ae,this.current.value));else if(this.accept(Br))e.push(new P(he,this.current.value));else if(this.accept(zl))e.push(new P(he,this.current.value));else if(this.accept(Pe,"("))this.parseExpression(e),this.expect(Pe,")");else if(this.accept(Tt,"["))if(this.accept(Tt,"]"))e.push(new P(Mt,0));else{var r=this.parseArrayList(e);e.push(new P(Mt,r))}else throw new Error("unexpected "+this.nextToken)};j.prototype.parseExpression=function(e){var t=[];this.parseUntilEndStatement(e,t)||(this.parseVariableAssignmentExpression(t),!this.parseUntilEndStatement(e,t)&&this.pushExpression(e,t))};j.prototype.pushExpression=function(e,t){for(var s=0,r=t.length;s<r;s++)e.push(t[s])};j.prototype.parseUntilEndStatement=function(e,t){return this.accept(Ln)?(this.nextToken&&this.nextToken.type!==vs&&!(this.nextToken.type===Pe&&this.nextToken.value===")")&&t.push(new P(Ur)),this.nextToken.type!==vs&&this.parseExpression(t),e.push(new P(ne,t)),!0):!1};j.prototype.parseArrayList=function(e){for(var t=0;!this.accept(Tt,"]");)for(this.parseExpression(e),++t;this.accept(Kr);)this.parseExpression(e),++t;return t};j.prototype.parseVariableAssignmentExpression=function(e){for(this.parseConditionalExpression(e);this.accept(N,"=");){var t=e.pop(),s=[],r=e.length-1;if(t.type===Et){if(!this.tokens.isOperatorEnabled("()="))throw new Error("function definition is not permitted");for(var o=0,n=t.value+1;o<n;o++){var i=r-o;e[i].type===Ae&&(e[i]=new P(et,e[i].value))}this.parseVariableAssignmentExpression(s),e.push(new P(ne,s)),e.push(new P(Nr,t.value));continue}if(t.type!==Ae&&t.type!==ot)throw new Error("expected variable for assignment");this.parseVariableAssignmentExpression(s),e.push(new P(et,t.value)),e.push(new P(ne,s)),e.push(Fe("="))}};j.prototype.parseConditionalExpression=function(e){for(this.parseOrExpression(e);this.accept(N,"?");){var t=[],s=[];this.parseConditionalExpression(t),this.expect(N,":"),this.parseConditionalExpression(s),e.push(new P(ne,t)),e.push(new P(ne,s)),e.push(Kl("?"))}};j.prototype.parseOrExpression=function(e){for(this.parseAndExpression(e);this.accept(N,"or");){var t=[];this.parseAndExpression(t),e.push(new P(ne,t)),e.push(Fe("or"))}};j.prototype.parseAndExpression=function(e){for(this.parseComparison(e);this.accept(N,"and");){var t=[];this.parseComparison(t),e.push(new P(ne,t)),e.push(Fe("and"))}};var bm=["==","!=","<","<=",">=",">","in"];j.prototype.parseComparison=function(e){for(this.parseAddSub(e);this.accept(N,bm);){var t=this.current;this.parseAddSub(e),e.push(Fe(t.value))}};var vm=["+","-","||"];j.prototype.parseAddSub=function(e){for(this.parseTerm(e);this.accept(N,vm);){var t=this.current;this.parseTerm(e),e.push(Fe(t.value))}};var wm=["*","/","%"];j.prototype.parseTerm=function(e){for(this.parseFactor(e);this.accept(N,wm);){var t=this.current;this.parseFactor(e),e.push(Fe(t.value))}};j.prototype.parseFactor=function(e){var t=this.tokens.unaryOps;function s(o){return o.value in t}if(this.save(),this.accept(N,s)){if(this.current.value!=="-"&&this.current.value!=="+"){if(this.nextToken.type===Pe&&this.nextToken.value==="("){this.restore(),this.parseExponential(e);return}else if(this.nextToken.type===Ln||this.nextToken.type===Kr||this.nextToken.type===vs||this.nextToken.type===Pe&&this.nextToken.value===")"){this.restore(),this.parseAtom(e);return}}var r=this.current;this.parseFactor(e),e.push(jr(r.value))}else this.parseExponential(e)};j.prototype.parseExponential=function(e){for(this.parsePostfixExpression(e);this.accept(N,"^");)this.parseFactor(e),e.push(Fe("^"))};j.prototype.parsePostfixExpression=function(e){for(this.parseFunctionCall(e);this.accept(N,"!");)e.push(jr("!"))};j.prototype.parseFunctionCall=function(e){var t=this.tokens.unaryOps;function s(n){return n.value in t}if(this.accept(N,s)){var r=this.current;this.parseAtom(e),e.push(jr(r.value))}else for(this.parseMemberExpression(e);this.accept(Pe,"(");)if(this.accept(Pe,")"))e.push(new P(Et,0));else{var o=this.parseArgumentList(e);e.push(new P(Et,o))}};j.prototype.parseArgumentList=function(e){for(var t=0;!this.accept(Pe,")");)for(this.parseExpression(e),++t;this.accept(Kr);)this.parseExpression(e),++t;return t};j.prototype.parseMemberExpression=function(e){for(this.parseAtom(e);this.accept(N,".")||this.accept(Tt,"[");){var t=this.current;if(t.value==="."){if(!this.allowMemberAccess)throw new Error('unexpected ".", member access is not permitted');this.expect(kn),e.push(new P(ot,this.current.value))}else if(t.value==="["){if(!this.tokens.isOperatorEnabled("["))throw new Error('unexpected "[]", arrays are disabled');this.parseExpression(e),this.expect(Tt,"]"),e.push(Fe("["))}else throw new Error("unexpected symbol: "+t.value)}};function Em(e,t){return Number(e)+Number(t)}function Mm(e,t){return e-t}function Tm(e,t){return e*t}function _m(e,t){return e/t}function Om(e,t){return e%t}function Im(e,t){return Array.isArray(e)&&Array.isArray(t)?e.concat(t):""+e+t}function Sm(e,t){return e===t}function $m(e,t){return e!==t}function Cm(e,t){return e>t}function Dm(e,t){return e<t}function xm(e,t){return e>=t}function Am(e,t){return e<=t}function Pm(e,t){return!!(e&&t)}function Rm(e,t){return!!(e||t)}function km(e,t){return gt(t,e)}function Lm(e){return(Math.exp(e)-Math.exp(-e))/2}function Fm(e){return(Math.exp(e)+Math.exp(-e))/2}function Nm(e){return e===1/0?1:e===-1/0?-1:(Math.exp(e)-Math.exp(-e))/(Math.exp(e)+Math.exp(-e))}function Um(e){return e===-1/0?e:Math.log(e+Math.sqrt(e*e+1))}function jm(e){return Math.log(e+Math.sqrt(e*e-1))}function Bm(e){return Math.log((1+e)/(1-e))/2}function Ri(e){return Math.log(e)*Math.LOG10E}function Km(e){return-e}function Hm(e){return!e}function zm(e){return e<0?Math.ceil(e):Math.floor(e)}function Gm(e){return Math.random()*(e||1)}function ki(e){return Fn(e+1)}function Vm(e){return isFinite(e)&&e===Math.round(e)}var Ym=4.7421875,lo=[.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 Fn(e){var t,s;if(Vm(e)){if(e<=0)return isFinite(e)?1/0:NaN;if(e>171)return 1/0;for(var r=e-2,o=e-1;r>1;)o*=r,r--;return o===0&&(o=1),o}if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*Fn(1-e));if(e>=171.35)return 1/0;if(e>85){var n=e*e,i=n*e,a=i*e,c=a*e;return Math.sqrt(2*Math.PI/e)*Math.pow(e/Math.E,e)*(1+1/(12*e)+1/(288*n)-139/(51840*i)-571/(2488320*a)+163879/(209018880*c)+5246819/(75246796800*c*e))}--e,s=lo[0];for(var u=1;u<lo.length;++u)s+=lo[u]/(e+u);return t=e+Ym+.5,Math.sqrt(2*Math.PI)*Math.pow(t,e+.5)*Math.exp(-t)*s}function qm(e){return Array.isArray(e)?e.length:String(e).length}function Li(){for(var e=0,t=0,s=0;s<arguments.length;s++){var r=Math.abs(arguments[s]),o;t<r?(o=t/r,e=e*o*o+1,t=r):r>0?(o=r/t,e+=o*o):e+=r}return t===1/0?1/0:t*Math.sqrt(e)}function Fi(e,t,s){return e?t:s}function Wm(e,t){return typeof t>"u"||+t==0?Math.round(e):(e=+e,t=-+t,isNaN(e)||!(typeof t=="number"&&t%1===0)?NaN:(e=e.toString().split("e"),e=Math.round(+(e[0]+"e"+(e[1]?+e[1]-t:-t))),e=e.toString().split("e"),+(e[0]+"e"+(e[1]?+e[1]+t:t))))}function Qm(e,t,s){return s&&(s[e]=t),t}function Zm(e,t){return e[t|0]}function Xm(e){return arguments.length===1&&Array.isArray(e)?Math.max.apply(Math,e):Math.max.apply(Math,arguments)}function Jm(e){return arguments.length===1&&Array.isArray(e)?Math.min.apply(Math,e):Math.min.apply(Math,arguments)}function ey(e,t){if(typeof e!="function")throw new Error("First argument to map is not a function");if(!Array.isArray(t))throw new Error("Second argument to map is not an array");return t.map(function(s,r){return e(s,r)})}function ty(e,t,s){if(typeof e!="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 e(r,o,n)},t)}function sy(e,t){if(typeof e!="function")throw new Error("First argument to filter is not a function");if(!Array.isArray(t))throw new Error("Second argument to filter is not an array");return t.filter(function(s,r){return e(s,r)})}function ry(e,t){if(!(Array.isArray(t)||typeof t=="string"))throw new Error("Second argument to indexOf is not a string or array");return t.indexOf(e)}function oy(e,t){if(!Array.isArray(t))throw new Error("Second argument to join is not an array");return t.join(e)}function ny(e){return(e>0)-(e<0)||+e}var Ni=1/3;function iy(e){return e<0?-Math.pow(-e,Ni):Math.pow(e,Ni)}function ay(e){return Math.exp(e)-1}function cy(e){return Math.log(1+e)}function ly(e){return Math.log(e)/Math.LN2}function nt(e){this.options=e||{},this.unaryOps={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh||Lm,cosh:Math.cosh||Fm,tanh:Math.tanh||Nm,asinh:Math.asinh||Um,acosh:Math.acosh||jm,atanh:Math.atanh||Bm,sqrt:Math.sqrt,cbrt:Math.cbrt||iy,log:Math.log,log2:Math.log2||ly,ln:Math.log,lg:Math.log10||Ri,log10:Math.log10||Ri,expm1:Math.expm1||ay,log1p:Math.log1p||cy,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc||zm,"-":Km,"+":Number,exp:Math.exp,not:Hm,length:qm,"!":ki,sign:Math.sign||ny},this.binaryOps={"+":Em,"-":Mm,"*":Tm,"/":_m,"%":Om,"^":Math.pow,"||":Im,"==":Sm,"!=":$m,">":Cm,"<":Dm,">=":xm,"<=":Am,and:Pm,or:Rm,in:km,"=":Qm,"[":Zm},this.ternaryOps={"?":Fi},this.functions={random:Gm,fac:ki,min:Jm,max:Xm,hypot:Math.hypot||Li,pyt:Math.hypot||Li,pow:Math.pow,atan2:Math.atan2,if:Fi,gamma:Fn,roundTo:Wm,map:ey,fold:ty,filter:sy,indexOf:ry,join:oy},this.consts={E:Math.E,PI:Math.PI,true:!0,false:!1}}nt.prototype.parse=function(e){var t=[],s=new j(this,new G(this,e),{allowMemberAccess:this.options.allowMemberAccess});return s.parseExpression(t),s.expect(vs,"EOF"),new ve(t,this)};nt.prototype.evaluate=function(e,t){return this.parse(e).evaluate(t)};var Vl=new nt;nt.parse=function(e){return Vl.parse(e)};nt.evaluate=function(e,t){return Vl.parse(e).evaluate(t)};var Ui={"+":"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 uy(e){return Ui.hasOwnProperty(e)?Ui[e]:e}nt.prototype.isOperatorEnabled=function(e){var t=uy(e),s=this.options.operators||{};return!(t in s)||!!s[t]};var dy=Object.defineProperty,hy=Object.getOwnPropertyDescriptor,fy=(e,t,s)=>t in e?dy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,py=(e,t,s,r)=>{for(var o=r>1?void 0:r?hy(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o},gy=(e,t,s)=>(fy(e,t+"",s),s);const my="kos-expression-evaluator-model";class yy{constructor(t,s,r,o){l(this,"name");l(this,"expression");l(this,"expr");l(this,"getContextData",null);l(this,"_lastResult",{value:void 0});this.name=t,this.expression=s,this.expr=r,this.getContextData=o,this._lastResult={value:void 0,error:void 0}}get result(){return this._lastResult}updateResult(t){this._lastResult=t}evaluate(t){try{return{value:this.expr.evaluate(t),error:void 0}}catch(s){return{value:void 0,error:s instanceof Error?s.message:String(s)}}}}let ir=class{constructor(e,t,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=e,this.logger=s.logger,this._data=Te(),this._results=Te(),this.parser=new nt}get data(){return this._data}get contextRevision(){return this._contextRevision}setContextData(e){this._data.setValues(e),X(()=>{this._contextRevision++,this.logger.debug("Context revision incremented to:",this._contextRevision)})}updateContextValue(e,t){this._data[e]=t}updateNestedValue(e,t){const s=e.split("."),r=s.pop();if(!r){this.logger.error(`Invalid path "${e}" - 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]=t,this.logger.debug(`Updated nested context value "${e}" to:`,t)}addModelToContext(e,t){this._data[e]=t}addExpression(e,t){try{const s=this.parser.parse(t),r=new yy(e,t,s,()=>this.data);this._expressions.set(e,r),this.evaluateExpression(e),this.logger.debug(`Added expression "${e}": ${t}`)}catch(s){throw this.logger.error(`Failed to parse expression "${e}"`,s),s}}removeExpression(e){const t=this._expressions.delete(e);return t?(delete this._results[e],this.logger.debug(`Removed expression "${e}"`)):this.logger.warn(`Attempted to remove non-existent expression "${e}". Available expressions: [${this.expressionNames.join(", ")}]`),t}getExpression(e){const t=this._expressions.get(e);return t||this.logger.warn(`Expression "${e}" not found. Available expressions: [${this.expressionNames.join(", ")}]`),t}getExpressionValue(e){const t=this._expressions.get(e);if(!t){this.logger.warn(`Expression "${e}" not found. Available expressions: [${this.expressionNames.join(", ")}]`);return}return t.result}getCachedExpressionValue(e){const t=this._expressions.get(e);if(t)return t.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(t=>{this._expressions.get(t)&&this.evaluateExpression(t)})}evaluateExpression(e){this.logger.debug(`Evaluating expression: ${String(e)}`);const t=this._expressions.get(e);if(!t){this.logger.warn(`Expression "${String(e)}" not found`);return}const s=t.evaluate(this.data);this.logger.debug(`Expression "${String(e)}" evaluated to:`,s);const r=t.result;(s.value!==r.value||s.error!==r.error)&&(this.logger.debug(`Expression "${String(e)}" result changed from`,r,"to",s),t.updateResult(s),this.updateResult(e,s))}updateResult(e,t){this.logger.debug(`ExpressionEvaluator.updateResult called for "${e}":`,t),X(()=>{this._results[e]=t})}createExpression(e){const t=tt();return this.addExpression(t,e),t}};gy(ir,"Registration");ir=py([A({modelTypeId:my,singleton:!1})],ir);const Yl=ir.Registration,Ne=hn(),by=Object.freeze(Object.defineProperty({__proto__:null,default:Ne},Symbol.toStringTag,{value:"Module"})),vy=m.createLogger({name:"kos-log-manager-service",group:"Services"}),wy="/api/kos/logs/overrides",ql=async()=>(vy.debug("sending GET for kos-log-manager"),await Ne.get(wy)),Ey=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:ql},Symbol.toStringTag,{value:"Module"}));var My=Object.defineProperty,Ty=Object.getOwnPropertyDescriptor,Hr=(e,t,s,r)=>{for(var o=r>1?void 0:r?Ty(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&My(t,s,o),o};const Wl="kos-log-manager-model",_y="/kos/logs/override/add/*",Oy="/kos/logs/override/remove/*",Iy=e=>{if(typeof e=="string")return e;if(typeof e=="number")switch(e){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 _t=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=e,this.logger=s.logger,this._overrides=new pn}updateModel(e){}resolveLoggers(){const e=m.getLoggers(),s=Object.entries(e).map(([r,o])=>({name:r,level:Iy(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(e,t){const s=Object.values(this.resolveLoggers());return t==null||t.send(s),s}setLogLevels(e){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(e.name)).forEach(r=>{const o=m.getLoggers()[r.name];if(!o){this.logger.debug(`Logger ${r.name} not found`);return}o.setLevel(e.level)});const s=m.getLoggers()[e.name];if(!s){this.logger.debug(`Logger ${e.name} not found`);return}s.setLevel(e.level),globalThis.kos.logOverrides=this._overrides.data}resetLogLevels(e){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(e.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()[e.name];s||this.logger.debug(`Logger ${e.name} not found`),s==null||s.resetLevel(),globalThis.kos.logOverrides=this._overrides.data}handleOverrideAdded(e,t){var s;this.logger.debug(`Override received for node type ${((s=t.wildcardCapture)==null?void 0:s.nodeType)??"unknown"}`),this._overrides.addModel({...e,id:e.name}),this.setLogLevels(e)}handleOverrideRemoved(e){this._overrides.removeModel(e.name),this.resetLogLevels(e)}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[e,t]=await ql();if(e){this.logger.error("Failed to load log overrides",e);return}const s=(t==null?void 0:t.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)})}};Hr([oc("/api/kos/ui/loggers")],_t.prototype,"getAllLoggers",1);Hr([U({topic:_y,websocket:!0,wildcardName:"nodeType"})],_t.prototype,"handleOverrideAdded",1);Hr([U({topic:Oy,websocket:!0,wildcardName:"nodeType"})],_t.prototype,"handleOverrideRemoved",1);_t=Hr([A(Wl)],_t);const Ql=new Me({class:_t,type:Wl}),{URL:As}=ae(),{postModel:Nn,getOne:Sy}=oe.build({basePath:`${As}/api/kos-time`});m.createLogger({name:"kos-time-service",group:"Services"});const Zl=async e=>{const t=await Nn({model:e,urlOverride:`${As}/api/kos/time/time`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},Xl=async e=>{const t=await Nn({model:e,urlOverride:`${As}/api/kos/time/date`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},Jl=async e=>{const t=await Nn({model:{},urlOverride:`${As}/api/kos/time/timezone?tz=${e}`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data},eu=async()=>{const e=await Sy({urlOverride:`${As}/api/kos/time/timezone`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data.timeZone},$y=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:eu,setDate:Xl,setTime:Zl,setTimezone:Jl},Symbol.toStringTag,{value:"Module"}));var Cy=Object.defineProperty,Dy=Object.getOwnPropertyDescriptor,zr=(e,t,s,r)=>{for(var o=r>1?void 0:r?Dy(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Cy(t,s,o),o};const Yt="kos-time-model",xy="/kos/time/time",Ay="/kos/time/day",Py="/kos/time/timezone";let Ot=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"timezone");this.id=e,this.logger=s.logger,this.timezone=""}async updateSystemTime(e){await Zl(e)}async updateSystemDate(e){await Xl(e)}async updateSystemTimezone(e){await Jl(e)}handleTimeChange(){z(ds.TIME_CHANGE,{})}handleDayChange(){z(ds.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),z(ds.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const e=await eu();this.setTimezone(e)}setTimezone(e){this.timezone=e}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};zr([U({topic:xy,websocket:!0})],Ot.prototype,"handleTimeChange",1);zr([U({topic:Ay,websocket:!0})],Ot.prototype,"handleDayChange",1);zr([U({topic:Py,websocket:!0})],Ot.prototype,"handleTimeZoneChange",1);Ot=zr([A(Yt)],Ot);const ar={registration:{[Yt]:{class:Ot,singleton:!0}},type:Yt,predicate:Ee(Yt),factory:ie.Singleton.create(Yt)};var Ry=Object.defineProperty,ky=Object.getOwnPropertyDescriptor,tu=(e,t,s,r)=>{for(var o=r>1?void 0:r?ky(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Ry(t,s,o),o};const su="log-block-container-model";let cr=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e,sortKey:"blockNum"})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing log-block-container container ${this.id}`)}async load(){this.logger.debug(`loading log-block-container container ${this.id}`)}};tu([Ie],cr.prototype,"_models",2);cr=tu([A(su)],cr);const Ly=m.createLogger({name:"log-stream-container-service",group:"Services"}),ru=()=>{var r;const e=ge(),s=(e==null?void 0:e.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return m.error(`getKosConnectionId: ${s}`),s},jt=ru(),Fy="/api/kos/logs/node/{nodeId}/streams",ou=async()=>(Ly.debug("sending GET for log-stream-container"),await Ne.get(Fy,{path:{nodeId:"primary"}},{destinationAddress:jt})),nu=async(e,t="primary")=>{await Ne.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:t,stream:e}},void 0,{destinationAddress:jt})},iu=async e=>{await Ne.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:e}},void 0,{destinationAddress:jt})},Ny=async()=>{await Ne.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:jt})},au=async e=>await Ne.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:e}},{destinationAddress:jt}),cu=async(e,t)=>await Ne.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:e,blockId:t}},{destinationAddress:jt}),Uy=Object.freeze(Object.defineProperty({__proto__:null,createOverride:Ny,getKosConnectionId:ru,getLogStreamBlock:cu,getLogStreamBlocks:au,getLogStreams:ou,subscribeToLogStream:nu,unsubscribeFromLogStream:iu},Symbol.toStringTag,{value:"Module"}));var jy=Object.getOwnPropertyDescriptor,By=(e,t,s,r)=>{for(var o=r>1?void 0:r?jy(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const lu="log-block-model";let So=class{constructor(e,t,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=e,this.logger=s.logger,this.nodeId=t.nodeId,this.stream=t.stream,this.blockNum=t.blockNum,this.startLineNum=t.startLineNum,this.endLineNum=t.endLineNum,this.startTime=t.startTime,this.endTime=t.endTime,this.lineCount=t.lineCount,this.lines=[],this.inc=0}async syncLines(){const[e,t]=await cu(this.stream,this.blockNum);if(e){this.logger.error(`Failed to get log block ${this.blockNum}`);return}t&&this.addLines(t.lines,!0)}updateModel(e){this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount}addLines(e,t){const s=t?[]:this.lines;this.lines=[...s,...e],this.inc+=1}async init(){this.logger.debug(`initializing log-block ${this.id}`)}async load(){this.logger.debug(`loading log-block ${this.id}`)}};So=By([A(lu)],So);const ws=new me({class:So,type:lu}),Gr=new me({class:cr,type:su});Gr.addRelatedModel(ws);var Ky=Object.defineProperty,Hy=Object.getOwnPropertyDescriptor,uu=(e,t,s,r)=>{for(var o=r>1?void 0:r?Hy(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Ky(t,s,o),o};const du="log-stream-model";let lr=class{constructor(e,t,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=e,this.logger=s.logger,this.currentBlockId="",this.name=t.name,this.nodeId=t.nodeId,this.isResetting=!0,this._blocks=Gr.instance(`${e}-blocks`).options({}).build()}get firstLineNum(){const e=this.populated[0];return e?e.startLineNum:0}get currentBlock(){const e=this.currentBlockId;return this._blocks.getModel(e)}get populated(){return this._blocks.data.filter(e=>e.lines.length>0)}get blocks(){return this._blocks.data}get totalLineCount(){return this.populated.reduce((e,t)=>e+t.lineCount,0)}accept(e){e.visit(this)}updateBlock(e){var r;let t=this._blocks.models.getModel(`${e.stream}-block-${e.blockNum}`);const s={nodeId:e.nodeId,blockNum:e.blockNum,endLineNum:e.endLineNum,lineCount:e.lineCount,startLineNum:e.startLineNum,stream:this.name,endTime:new Date(e.endTime),startTime:new Date(e.startTime)};t||(t=ws.instance(`${e.stream}-block-${e.blockNum}`).options(s).build(),this._blocks.addModel(t)),t&&t.updateModel(s),(!this.currentBlock||e.blockNum>=((r=this.currentBlock)==null?void 0:r.blockNum))&&(this.currentBlockId=`${e.stream}-block-${e.blockNum}`)}addBlock(e){var s;const t=ws.instance(`${e.stream}-block-${e.blockNum}`).options({nodeId:e.nodeId,blockNum:e.blockNum,endLineNum:e.endLineNum,lineCount:e.lineCount,startLineNum:e.startLineNum,stream:this.name,endTime:new Date(e.endTime),startTime:new Date(e.startTime)}).build();this._blocks.addModel(t),(!this.currentBlock||e.blockNum>=((s=this.currentBlock)==null?void 0:s.blockNum))&&(this.currentBlockId=`${e.stream}-block-${e.blockNum}`)}removeBlock(e){this._blocks.models.removeModel(`${this.name}-block-${e}`)}async subscribe(){await nu(this.name)}async unsubscribe(){await iu(this.name)}async reset(){if(this.isResetting=!0,this.populated.length>0)return;this.logger.debug(`resetting log-stream ${this.id}`);for(const t of this._blocks.models.data)t.lines=[];const e=this._blocks.data[this._blocks.data.length-1];e&&await e.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[e,t]=await au(this.name);if(e){this.logger.error(`Error loading log stream: ${e}`);return}if(t)for(const r of t)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 e;this.shouldStop=!0,(e=this.generatorInstance)==null||e.next(),console.log("Requested generator stop.")}async*streamLogs(){const e=[];let t=null,s=0,r=this.currentBlockId;const o=ll(()=>{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,e.push(...i.lines);else{const a=i.lines.slice(s);e.push(...a),s+=a.length}t&&(t(),t=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(e.length===0&&await new Promise(n=>t=n);e.length>0;)yield e.shift()}finally{o()}}};uu([Ie],lr.prototype,"_blocks",2);lr=uu([A(du)],lr);const hs=new me({class:lr,type:du});var zy=Object.defineProperty,Gy=Object.getOwnPropertyDescriptor,it=(e,t,s,r)=>{for(var o=r>1?void 0:r?Gy(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&zy(t,s,o),o};const hu="log-stream-container-model",Vy="/kos/logs/subscription/addBlock/*",Yy="/kos/logs/subscription/updateBlock/*",qy="/kos/logs/subscription/removeBlock/*",Wy="/kos/logs/subscription/lines/*",fu="/kos/logs/streams/add/*";let Re=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"selectedStream");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e}),this.selectedStream=void 0}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}updateModel(e){}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}updateSelectedStream(e){this.selectedStream=e}handleStreamAdded(e){this.logger.debug(`Received topic: ${fu}`);const t=e.stream,s=hs.instance(t).options({name:t,nodeId:"primary"}).build();this.addModel(s)}handleAddBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,r=this.models.getModel(s);r&&r.addBlock(e)}handleRemoveBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,r=this.models.getModel(s);r&&r.removeBlock(e.blockNum)}handleUpdateBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,r=this.models.getModel(s);r&&r.updateBlock(e)}handleLogLine(e,t){var o;this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,r=this.models.getModel(s);r&&((o=r.currentBlock)==null||o.addLines(e.lines))}async init(){this.logger.debug(`initializing log-stream-container container ${this.id}`)}async subscribeToLogStream(e){const t=hs.instance(e).options({name:e,nodeId:"primary"}).build();this.addModel(t),await t.subscribe()}async load(){this.logger.debug(`loading log-stream-container container ${this.id}`);const[e,t]=await ou();if(e){this.logger.error(`Error loading log-streams: ${e}`);return}t&&t.forEach(s=>{const r=hs.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};it([Ie],Re.prototype,"_models",2);it([U({topic:[fu],websocket:!0})],Re.prototype,"handleStreamAdded",1);it([U({topic:[Vy],websocket:!0})],Re.prototype,"handleAddBlock",1);it([U({topic:[qy],websocket:!0})],Re.prototype,"handleRemoveBlock",1);it([U({topic:[Yy],websocket:!0})],Re.prototype,"handleUpdateBlock",1);it([U({topic:[Wy],websocket:!0})],Re.prototype,"handleLogLine",1);Re=it([A(hu)],Re);const Ps=new Me({class:Re,type:hu});Ps.addRelatedModel(hs);Ps.addRelatedModel(Gr);Ps.addRelatedModel(ws);const Qy=e=>e.rank!==void 0,Zy=e=>e.visibleRole!==void 0,Xy=e=>e.color!==void 0,Jy=e=>{const t=e.info;return Qy(t)?t.rank:0},eb=e=>{const t=e.info;return Xy(t)?t.color:"orange"},tb=e=>{const t=e.info;return Zy(t)?t.visibleRole:"TECHNICIAN"},{URL:Vr}=ae(),{getAll:sb,postModel:pu}=oe.build({basePath:`${Vr}/api/kos/troubles`}),gu=async e=>await sb({urlOverride:`${Vr}${e}`}),mu=async(e,t="/api/kos/troubles",s)=>{try{const r=await pu({model:{},urlOverride:`${Vr}${t}/resolve/${e}`,tracker:s});return r!=null&&r.data&&Je.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:Ke.Fail,tracker:s,reason:"Failed to resolve trouble"};return Je.initiateFuture(o),o}},rb=async(e,t="/api/kos/troubles",s)=>{try{const r=await pu({model:e,urlOverride:`${Vr}${t}/resolve/`,tracker:s});return r!=null&&r.data&&Je.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:Ke.Fail,tracker:s,reason:"Failed to resolve troubles"};return Je.initiateFuture(o),o}},ob=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:rb,getTroubles:gu,resolveTrouble:mu},Symbol.toStringTag,{value:"Module"})),ur="troubleDataMapper",Ks=new Map;$s(ur,{register:(e,t)=>{var s;Ks.has(e)||Ks.set(e,[]),(s=Ks.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Ks.get(e);if(!s)return{...t.data};const r=s.map(i=>i(t));return(await Promise.allSettled(r)).reduce((i,a)=>(a.status==="fulfilled"?i={...i,...a.value}:m.info(`Trouble mapper ${e} failed: ${a.reason}`),i),{...t.data})}});const Rs="troubleMapper",Hs=new Map;$s(Rs,{register:(e,t)=>{var s;Hs.has(e)||Hs.set(e,[]),(s=Hs.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Hs.get(e);if(!s)return[];const r=s.map(i=>i(t)),n=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(m.info(`Trouble mapper ${e} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});S[Rs].register("nozzle",async e=>[e.data.nozzlePath]);S[Rs].register("path",async e=>[e.data.path]);const nb=async e=>{const t=new Set,s=e.ifaces,r=s==null?void 0:s.map(n=>S[Rs].execute(n,e));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>t.add(i))}),Array.from(t)},yu=async e=>{const t=e.ifaces,s=t==null?void 0:t.map(i=>S[ur].execute(i,e)),r=S[ur].execute(e.type,e);s.push(r);const n=(await Promise.allSettled(s)).reduce((i,a)=>(a.status==="fulfilled"&&(i={...i,...a.value}),i),{});return{...e.data,...n}};class ib{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class ab{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class dt{static getHandler(t){switch(t){case"ResolvableTrouble":return new ib;case"BlockPumpTrouble":return new ab;default:return}}}var cb=Object.defineProperty,lb=Object.getOwnPropertyDescriptor,bu=(e,t,s,r)=>{for(var o=r>1?void 0:r?lb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&cb(t,s,o),o};const qt="trouble-model";function zs(e){return typeof e.shouldDefer=="boolean"}let dr=class{constructor(e,{resolvable:t,tags:s,info:r,id:o,clientData:n,rank:i,ifaces:a,type:c,group:u,createTime:d,role:h,color:f,servicePath:p,...b},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=e,this.logger=w.logger,this.type=c,this._troubleId=o,this._resolvable=!!t,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,b),this.futureHandler=new Rr(this)}getTitleWithContext(e){var s,r;const t=e?(r=(s=dt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[e]:dt.getHandler(this.type);return(t==null?void 0:t.title)||"Trouble"}getSubtitleWithContext(e){var s,r;const t=e?(r=(s=dt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[e]:dt.getHandler(this.type);return(t==null?void 0:t.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var e;return((e=dt.getHandler(this.type))==null?void 0:e.title)||"Trouble"}get subtitle(){var e;return((e=dt.getHandler(this.type))==null?void 0:e.subtitle)||"Trouble"}get troubleId(){return this._troubleId}get resolvable(){return this._resolvable}get future(){return this.futureHandler.future}async resolveMappedData(){return await yu(this)}get deferredCompanion(){const e=vo(this.id,t=>zs(t));if(e&&zs(e.modelData))return e.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const e=vo(this.id,t=>zs(t));return e&&zs(e.modelData)?e.modelData.shouldDefer:!1}clearDefer(){var e;(e=this.deferredCompanion)==null||e.clearDefer()}defer(){var e;(e=this.deferredCompanion)==null||e.defer()}getChildren(){return[...this.futureHandler.allFutures]}async resolve(e){var t;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){(t=this.deferredCompanion)==null||t.defer();return}return await mu(this._troubleId,this.servicePath,e)}};bu([si()],dr.prototype,"resolve",1);dr=bu([A(qt)],dr);const Es={registration:{[qt]:{class:dr,singleton:!1}},type:qt,predicate:Ee(qt),factory:ie.Factory.create(qt)};var vu=Object.defineProperty,ub=Object.getOwnPropertyDescriptor,db=(e,t,s)=>t in e?vu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Un=(e,t,s,r)=>{for(var o=r>1?void 0:r?ub(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&vu(t,s,o),o},hb=(e,t,s)=>(db(e,t+"",s),s);function ji(e){return S.propertyMapper.hasMapper(be.TroubleRank)?S.propertyMapper.executeMapper(be.TroubleRank,e):Jy(e)}function Bi(e){return(S.propertyMapper.hasMapper(be.TroubleColor)?S.propertyMapper.executeMapper(be.TroubleColor,e):eb(e)).toLowerCase()}function Ki(e){return(S.propertyMapper.hasMapper(be.TroubleRole)?S.propertyMapper.executeMapper(be.TroubleRole,e):tb(e)).toLowerCase()}const fb="trouble-container-model";class fe{}l(fe,"INDEX_TROUBLES_BY_IFACE","byIface"),l(fe,"INDEX_TROUBLES_BY_TYPE","byType"),l(fe,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(fe,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(fe,"SORT_KEY_RANK","rank"),l(fe,"TROUBLES_DEFERRED","true");let It=class{constructor(e,t){l(this,"id");l(this,"servicePath","/api/kos/troubles");this.id=e,this.servicePath=t.servicePath??this.servicePath}async load(){this.logger.debug("loading trouble container");const e=await gu(this.servicePath);try{e==null||e.data.forEach(t=>{const s={...t,servicePath:this.servicePath,rank:ji(t),color:Bi(t),role:Ki(t),id:String(t.id)},r=Es.factory(`trouble-${t.id}`)(s);this.troubles.addModel(r)})}catch(t){throw this.logger.error(t),t}}handleTroubleRemoved(e){const t=`trouble-${e}`,s=this.troubles.getModel(t);this.troubles.removeModel(t),s&&Xe(s)}handleTroubleAdded(e){const t={...e,servicePath:this.servicePath,rank:ji(e),color:Bi(e),role:Ki(e),id:String(e.id)};if(t.role==="NONE")return;const s=Es.factory(`trouble-${e.id}`)(t);this.troubles.addModel(s)}};hb(It,"Registration");Un([U({topic:"/kos/trouble/remove",websocket:!0,lifecycle:H.INIT})],It.prototype,"handleTroubleRemoved",1);Un([U({topic:"/kos/trouble/add",websocket:!0})],It.prototype,"handleTroubleAdded",1);It=Un([A({modelTypeId:fb,singleton:!0}),cc(),rc({containerProperty:"troubles",containerOptions:{indexMap:{[fe.INDEX_TROUBLES_BY_IFACE]:nb,[fe.INDEX_TROUBLES_BY_TYPE]:"type",[fe.INDEX_TROUBLES_BY_GROUP]:"group",[fe.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:fe.SORT_KEY_RANK}})],It);const St=It.Registration,{URL:wu}=ae(),{getAll:pb}=oe.build({basePath:`${wu}/api/kos/ota`}),Hi=m.createLogger({name:"ota-service",group:"Services"}),gb=async()=>{Hi.debug("sending GET request to /api/kos/ota/artifacts");const e=await pb({urlOverride:`${wu}/api/kos/ota/artifacts`});return Hi.debug("getArtifacts - response:",e),e==null?void 0:e.data};var mb=Object.defineProperty,yb=Object.getOwnPropertyDescriptor,Yr=(e,t,s,r)=>{for(var o=r>1?void 0:r?yb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&mb(t,s,o),o};const Eu="ota-model",bb=e=>{let t=null;for(const s in e){const r=e[s],o=r.lastUpdateTime;(!t||t.lastUpdateTime<o)&&(t=r)}return t},uo=e=>{const t=e.artifactInfo,s=bb(e.requests),r=(t==null?void 0:t.identifier)||(s==null?void 0:s.kabId);if(!r)return;let o;switch(e.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=t===void 0;return{id:r,manifest:n,label:t==null?void 0:t.version,name:t==null?void 0:t.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/(t==null?void 0:t.size)*100:void 0,size:t==null?void 0:t.size}};let $t=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"data",new pn);l(this,"troubleContainer");this.id=e,this.logger=s.logger}get downloadInProgressTrouble(){var t;return(t=this.troubleContainer.troubles.getIndexByKey("byType","OTADownloadInProgressTrouble"))==null?void 0:t[0]}get updatePendingTrouble(){var t;return(t=this.troubleContainer.troubles.getIndexByKey("byType","OTAUpdatePendingTrouble"))==null?void 0:t[0]}get pausedDueToErrorsTrouble(){var t;return(t=this.troubleContainer.troubles.getIndexByKey("byType","OTAPausedDueToErrorsTrouble"))==null?void 0:t[0]}get updates(){return this.data}get status(){return this.pausedDueToErrorsTrouble?"error":this.downloadInProgressTrouble?"downloading":this.updatePendingTrouble?"pending":"idle"}installAndReboot(){var e;this.updatePendingTrouble||this.logger.error("installAndReboot - OTAUpdatePendingTrouble not present"),this.logger.debug("installAndReboot - resolve OTAUpdatePendingTrouble"),(e=this.updatePendingTrouble)==null||e.resolve()}async init(){this.logger.debug(`initializing ota ${this.id}`)}async load(){this.logger.debug(`loading ota ${this.id}`);try{const e=await gb();e&&e.forEach(t=>{const s=uo(t);s&&this.data.addModel(s)})}catch(e){this.logger.error(`loading ota ${this.id} - error:`,e)}}async handleAllArtifacts(e){this.logger.debug("handleAllArtifacts:",e),await this.data.clear();try{e.forEach(t=>{const s=uo(t);s&&this.data.addModel(s)})}catch(t){this.logger.error(`handleAllArtifacts ${this.id} - error:`,t)}}handleChangedArtifacts(e){this.logger.debug("handleChangedArtifacts:",e);try{e.forEach(t=>{const s=uo(t);s&&this.data.updateModel(s)})}catch(t){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,t)}}};Yr([Pt({modelType:St.type})],$t.prototype,"troubleContainer",2);Yr([U({topic:"/kos/ota/artifacts/all",websocket:!0})],$t.prototype,"handleAllArtifacts",1);Yr([U({topic:"/kos/ota/artifacts/changed",websocket:!0})],$t.prototype,"handleChangedArtifacts",1);$t=Yr([A(Eu)],$t);const hr=new Me({class:$t,type:Eu});function vb(e){let t;const s=async(...r)=>{t&&t.abort(),t=new AbortController;const o=t;try{return await e(...r,o.signal)}finally{t===o&&(t=void 0)}};return s.cancel=()=>{t&&(t.abort(),t=void 0)},s.getController=()=>t,s.isActive=()=>!!t,s}const ho=m.createLogger({name:"software-info-service",group:"Services"}),jn=async e=>{ho.debug("sending GET for software-info");const[t,s]=await xl.get("/api/kos/manifest/info",void 0,{signal:e});if(!s)throw e!=null&&e.aborted?(ho.debug("Request was aborted"),new pe("Request was aborted")):(ho.error("Failed to fetch software-info",t),new pe("Failed to fetch software-info"));return s},wb=vb(jn),Eb=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:jn,getSoftwareInfosWithCancel:wb},Symbol.toStringTag,{value:"Module"}));var Mb=Object.getOwnPropertyDescriptor,Tb=(e,t,s,r)=>{for(var o=r>1?void 0:r?Mb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const Wt="software-info-model";let $o=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"nodes");this.id=e,this.logger=s.logger,this.nodes=[]}async init(){this.logger.debug(`initializing software-info ${this.id}`)}groupBy(e,t){return e.reduce((s,r)=>(s[r[t]]=[...s[r[t]]||[],r],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const e=await jn(),t=(e==null?void 0:e.nodes)||{};X(()=>{const r=Object.keys(t).map(o=>t[o][0]).map(o=>({nodeName:o.nodeType,kosVersion:o.kosVersion,group:this.groupBy(o.artifacts,"group")}));this.nodes=r})}catch(e){e instanceof pe&&this.logger.error("Failed to fetch software-info",e)}}};$o=Tb([A(Wt)],$o);const fr={registration:{[Wt]:{class:$o,singleton:!1}},type:Wt,predicate:Ee(Wt),factory:ie.Factory.create(Wt)},{URL:Mu}=ae(),{getOne:_b}=oe.build({basePath:`${Mu}/api/kos/state`}),Ob=m.createLogger({name:"state-bean-service",group:"Services"}),Tu=async({path:e})=>(Ob.debug("sending GET for state-bean"),await _b({urlOverride:`${Mu}/api/kos/state/${e}`})),Ib=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:Tu},Symbol.toStringTag,{value:"Module"}));var Sb=Object.defineProperty,$b=Object.getOwnPropertyDescriptor,_u=(e,t,s,r)=>{for(var o=r>1?void 0:r?$b(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Sb(t,s,o),o};const Qt="state-bean-model",Cb=st("path");let pr=class{constructor(e,t,s){l(this,"id");l(this,"path");l(this,"props");l(this,"logger");this.id=e,this.logger=s.logger,this.props=mn.map(new Map),bo(t,this)}updateModel(e){bo(e,this)}handleConfigBeanUpdated(e){Object.entries(e).forEach(([t,s])=>{let r=s;typeof r=="string"&&vn(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&kr(r)&&(r=Number(r)),this.props.set(t,r)})}async init(){this.logger.debug(`initializing state-bean ${this.id}`)}updateProps(e){Object.entries(e).forEach(([t,s])=>{this.props.set(t,s)})}async load(){this.logger.debug(`loading state-bean ${this.id}`);const e=await Tu({path:this.path});e!=null&&e.data&&this.updateProps(e.data)}};_u([U({topic:`/kos/state/${Cb}`,websocket:!0})],pr.prototype,"handleConfigBeanUpdated",1);pr=_u([A(Qt)],pr);const Ms={registration:{[Qt]:{class:pr,singleton:!1}},type:Qt,predicate:Ee(Qt),factory:ie.Factory.create(Qt)};var Db=Object.defineProperty,xb=Object.getOwnPropertyDescriptor,Ou=(e,t,s,r)=>{for(var o=r>1?void 0:r?xb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Db(t,s,o),o};const Zt="state-prop-model",zi=st("path");let gr=class{constructor(e,t,s){l(this,"id");l(this,"path");l(this,"attribute");l(this,"logger");l(this,"stateBean");this.id=e,this.logger=s.logger,this.path=t.path,this.attribute=t.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 e;return((e=this.value)==null?void 0:e.toString())??""}};Ou([Pt({modelType:Ms.type,id:`state-bean-${zi}`,options:{path:zi}})],gr.prototype,"stateBean",2);gr=Ou([A(Zt)],gr);const Bn={registration:{[Zt]:{class:gr,singleton:!1}},type:Zt,predicate:Ee(Zt),factory:ie.Factory.create(Zt)},{URL:Ab}=ae(),{getAll:Pb}=oe.build({basePath:`${Ab}/api/state-prop`}),Rb=m.createLogger({name:"state-prop-service",group:"Services"}),kb=async()=>(Rb.debug("sending GET for state-prop"),await Pb({})),Lb=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:kb},Symbol.toStringTag,{value:"Module"})),{URL:Kn}=ae(),{getOne:Iu}=oe.build({basePath:`${Kn}/api/translation`}),fs=m.createLogger({name:"translation-service",group:"Services"}),Fb=()=>{const e=window.location.origin,t=ge();return(t==null?void 0:t.host)||e},Su=async(e,t)=>{fs.debug(`Loading translations from: ${e}`);const s=t??Fb();try{const r=await fetch(`${s}${e}`);return r.status!==200?(fs.warn(`Failed to fetch translations at ${e}: ${r.status}`),{}):await r.json()}catch(r){throw fs.error("Error fetching translations",r),r}},Nb=async()=>{fs.debug("Getting system localization descriptor");const e=await Iu({urlOverride:`${Kn}/api/system/kos/localization`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get localization descriptor ${e==null?void 0:e.status}`);return e.data},$u=e=>async()=>{fs.debug(`Getting KOS localization descriptor for context: ${e}`);const t=await Iu({urlOverride:`${Kn}/api/kos/localization/contexts`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get KOS localization descriptor ${t==null?void 0:t.status}`);return t.data[e]},Cu="langResolver";var Ub=Object.getOwnPropertyDescriptor,jb=(e,t,s,r)=>{for(var o=r>1?void 0:r?Ub(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const Xt="translation-model";function Bb(e){const t=typeof e=="string",s=t?!1:!!(e!=null&&e.data)&&typeof(e==null?void 0:e.data)!="string",r=t?e:e==null?void 0:e.defaultValue,o=t||e==null?void 0:e.context,n=t?void 0:s?e==null?void 0:e.data:e;return{isBasicOptions:t,defaultValue:r,context:o,data:n}}function Du(e,t=""){return Object.keys(e).reduce((s,r)=>{const o=t?`${t}.${r}`:r;if(typeof e[r]=="object"&&e[r]!==null){const n=Du(e[r],o);return{...s,...n}}else return{...s,[o]:e[r]}},{})}function xu(e,t){const s={...e};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(typeof t[r]=="object"&&t[r]!==null&&typeof e[r]=="object"&&e[r]!==null?s[r]=xu(e[r],t[r]):s[r]=t[r]);return s}const Co=(e,t)=>{const s=/__(.*?)__/g,r=e.replace(s,(o,n)=>Object.prototype.hasOwnProperty.call(t||{},n.trim())?t==null?void 0:t[n.trim()]:o);return r===e?r:s.test(r)?Co(r,t):r},Gs=(e,t,s)=>{const r=/{{(.*?)}}/g,n=Co(e,t).replace(r,(a,c)=>Object.prototype.hasOwnProperty.call(s||{},c.trim())?s==null?void 0:s[c.trim()]:a);return Co(n,t)},Gi=(e,t)=>{if(t.includes(":")){const[s,r]=t.split(":");return{namespace:s,key:r}}else return{namespace:e,key:t}};let Do=class{constructor(e,t,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=e,this.defaultLocale=t.defaultLocale||"en",this.currentLocale=t.currentLocale||"en",this.namespace=t.namespace,this.descriptor=t.descriptor,this.rootUrl=t.rootUrl,this.data={},this.resolver=t.resolver||s.kosContext.get(Cu),this.bundleResolver=t.bundleResolver,this.logger=s.logger,this.context=s.kosContext.parentModel}getTranslationLocales(e){const t=this.descriptor[e];if(!e||!t)return[this.defaultLocale];if(!this.defaultLocale&&!t.fallbacks)return[e];let s=t.fallbacks||[this.defaultLocale];return s.includes(e)||(s=[e,...s]),s}async loadTranslations(){const e=this.getTranslationLocales(this.currentLocale).reverse(),t=e.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 Su(o,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(t);X(()=>{const r=s.reduce((o,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${e[i]}`,n.value),n.value&&(o=xu(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${e[i]}`),o),{});this.data=Du(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(e){const{namespace:t,key:s}=Gi(this.namespace,e);if(t!==this.namespace){const r=this.context.getModel(t);return r?r.exists(s):!1}return!!this.data[s]}resolveKey(e,t){if(!e)return this.logger.debug("key is empty"),"";const{defaultValue:s,context:r,data:o}=Bb(t),{namespace:n,key:i}=Gi(this.namespace,e),a=`${i}_${r}`;if(n!==this.namespace){const c=this.context.getModel(n);return c?c.resolveKey(i,t):i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(u=>Gs(u,this.data,o)):Gs(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[a];return Array.isArray(c)?c.map(u=>Gs(u,this.data,o)):Gs(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=E.reaction(()=>this.currentLocale,(e,t)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${t} to ${e}`),this.loadTranslations()})}};Do=jb([Ar(),A(Xt)],Do);const mr={registration:{[Xt]:{class:Do,singleton:!1}},type:Xt,predicate:Ee(Xt),factory:ie.Factory.create(Xt)};var Kb=Object.defineProperty,Hb=Object.getOwnPropertyDescriptor,Au=(e,t,s,r)=>{for(var o=r>1?void 0:r?Hb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Kb(t,s,o),o};const Jt="translation-container-model",zb=(e,t="/")=>e.join(t).replace(new RegExp(t+"{1,}","g"),t);function Gb(e,t){const s=this.descriptor.namespaces[e];if(!s)throw new Error("namespace "+e+" not found in descriptor");const r=s.basePath,o=s.locales[t].file;return zb([r,o])}let yr=class{constructor(e,t,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=e,this.lang=t.lang||"en",this.descriptor=t.descriptor,this._defaultNamespace=t.defaultNamespace,this.descriptorUrl=t.descriptorUrl,this.rootUrl=t.rootUrl,this.resolver=t.resolver||Gb.bind(this),s.kosContext.set(Cu,this.resolver),this.logger=s.logger,this._models=new Se({parentId:e})}set currentLocale(e){this.lang=e,this.models.data.forEach(t=>{t.currentLocale=e})}get defaultNamespace(){return this._defaultNamespace?this.getModel("translation-"+this._defaultNamespace):void 0}getModel(e){return this.logger.debug("getting model "+e),this._models.getModel("translation-"+e)}get models(){return this._models}get data(){return this._models.data}async reload(){for(const e of this.namespaces){const t=this.resolveNamespace(e);await ue(t)}}resolveNamespace(e){var s;if((s=this.descriptor.namespaces)==null?void 0:s[e]){const r=Object.keys(this.descriptor.namespaces[e].locales)[0],o=this.descriptor.namespaces[e].locales[r].defaultLocale,n=mr.factory("translation-"+e)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:o,descriptor:this.descriptor.namespaces[e].locales,resolver:this.resolver});return this.addModel(n),this.namespaces.includes(e)||X(()=>{this.namespaces.push(e)}),n}else{this.logger.warn("namespace "+e+" not found in descriptor");const r=mr.factory("translation-"+e)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(r),r}}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug("initializing translation-container container "+this.id)}async load(){this.logger.debug("loading translation-container container "+this.id)}};Au([Ie],yr.prototype,"_models",2);yr=Au([A(Jt)],yr);const ke={registration:{[Jt]:{class:yr,singleton:!0}},type:Jt,predicate:Ee(Jt),factory:ie.Singleton.create(Jt)},Vb={set(e,t){const s=V.getContext(ke.type);s&&s.set(e,t)},get(e){const t=V.getContext(ke.type);return t==null?void 0:t.get(e)}},Pu={async init(e){const t=ke.factory(e);return await ue(t),{translations:t}}};function Yb(e){return(e==null?void 0:e.troubles)!==void 0&&(e==null?void 0:e.troubles)instanceof Array&&(e==null?void 0:e.troublesByType)!==void 0&&typeof(e==null?void 0:e.troublesByType)=="object"}const Ru="kos-ws-event",Hn=Rt(Ru);var qb=Object.defineProperty,Wb=Object.getOwnPropertyDescriptor,zn=(e,t,s,r)=>{for(var o=r>1?void 0:r?Wb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&qb(t,s,o),o};const Qb=({headers:e,body:t})=>Object.entries(e).map(([r,o])=>`${r}:${o}`).join("\\n")+"\\n\\n"+t;exports.WsEventModel=class{constructor(t){l(this,"id");l(this,"events");l(this,"_topicMap");this.id=t,this.events=E.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(t,s){this.processEvent(s,!0)}handleReceiveEvent(t,s){this.processEvent(s)}processEvent(t,s=!1){m.debug("kos event received");const{body:r,headers:o}=t.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:Qb({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),m.debug(`logged ${this.events.size} events`)}}};zn([U({topic:[Ss.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);zn([U({topic:[Ss.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=zn([A(Hn.type)],exports.WsEventModel);const Vi=ge(),Zb=Vi.debug==="true"||Vi.debug===!0,Xb="/api/system/canvas",ku=async(e,t)=>{const s=t||Xb,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:Zb?"false":"true"},body:e})},Jb=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:ku},Symbol.toStringTag,{value:"Module"}));function Yi(e,t,s){{const r=e.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var ev=Object.defineProperty,tv=Object.getOwnPropertyDescriptor,Lu=(e,t,s,r)=>{for(var o=r>1?void 0:r?tv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&ev(t,s,o),o};const Fu="canvas-renderer-model";function fo(e){return typeof e.onDone=="function"}let br=class{constructor(e,t,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=e,this.logger=s.logger,this.width=t.width??50,this.height=t.height??30,this.fps=t.fps??10,this.durationMs=t.durationMs??null,this.apiPath=t.apiPath??"/api/system/canvas",this.endpointName=t.endpoint}set onFrame(e){this._onFrame=e}set renderer(e){var t,s;this._renderer&&(this.stopStreaming(),(s=(t=this._renderer).dispose)==null||s.call(t)),this._renderer=e,this.isStreaming&&this.startStreaming()}setClearOnComplete(e){this._clearOnComplete=e}sendDataFrame(e,t){ku(e,t)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const e=this.isOneShotDone();this.stopStreaming(!e)});return}}handleFrame(e){var s;const t=Yi(e);this.sendDataFrame(t,this.apiPath),(s=this._onFrame)==null||s.call(this,t)}stopStreaming(e=!0){var t,s;this.logger.debug(`stopStreaming called with clearCanvas=${e}`),this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(s=(t=this._renderer)==null?void 0:t.pause)==null||s.call(t),e&&(this.logger.debug("Clearing canvas..."),this.clearCanvas())}clearCanvas(){var s;const e=this.width>0?this.width:50,t=this.height>0?this.height:30;if(e>0&&t>0){const r=e*t*4,o=new Uint8ClampedArray(r);for(let i=3;i<r;i+=4)o[i]=255;const n=Yi(o);this.logger.debug(`Sending clear frame: ${e}x${t}, apiPath: ${this.apiPath}`),this.sendDataFrame(n,this.apiPath),(s=this._onFrame)==null||s.call(this,n)}}isOneShotDone(){var e,t;return fo(this._renderer)&&((t=(e=this._renderer).isOneShot)==null?void 0:t.call(e))===!0&&this._renderer.isOneShotDone}startStreaming(){var e,t,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(),(t=(e=this._renderer).play)==null||t.call(e);const o=fo(this._renderer);fo(this._renderer)&&this._renderer.onDone(()=>{var c,u,d;this.logger.debug(`Renderer completed for ${this.id}`),z("/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(e,t)=>{this.logger.debug(`HTTP stop endpoint called for ${this.endpointName}`),this.stopStreaming(),t.send({status:"OK"})}),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/start`,async(e,t)=>{this.startStreaming(),t.send({status:"OK"})})}};Lu([Pt({modelType:Sn.type})],br.prototype,"router",2);br=Lu([A(Fu)],br);const Gn=new me({class:br,type:Fu});class Nu{constructor({src:t}){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=t,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(t,s){this.canvas.width=t,this.canvas.height=s,this.video.readyState>=2&&this.ctx.drawImage(this.video,0,0,t,s)}readPixels(t,s){return this.ctx.getImageData(0,0,t,s).data}onDone(t){this.doneCallback=t}dispose(){this.video.pause(),this.video.removeAttribute("src"),this.video.load(),this.video.remove(),this.video.removeEventListener("ended",this.handleEnded),this.doneCallback=null}shouldStep(t){const s=performance.now();return s-this.lastUpdate>=t?(this.lastUpdate=s,!0):!1}}class sv{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 t=this.canvas.getContext("webgl");if(!t)throw new Error("WebGL not supported");this.gl=t}shouldStep(t){const s=performance.now();return s-this.lastUpdate>=t?(this.lastUpdate=s,!0):!1}readPixels(t=this.lastWidth,s=this.lastHeight){const r=new Uint8Array(t*s*4);this.gl.readPixels(0,0,t,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*t*4,a=(s-1-n)*t*4;o.set(r.subarray(i,i+t*4),a)}return o}}class rv extends sv{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=`
|
|
77
|
+
["${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{Ge.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 Ge.debug(`Topic ${e} currently has ${a} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,o,n),()=>{const{count:c}=i();Ge.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(Mt,"_instance");class Yp{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[ee])||{},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===U.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=Mt.getInstance().subscribeTopic({topic:s,callback:r,fos:e.fos,bridge:e.bridge,destinationAddress:n});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=So(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=So(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||!Ic(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return Oc(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 jp(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===U.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;Mt.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a}),i=Oi(s)}else i=Oi(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||Xe.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 dt(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 Wp(t){return!!(t!=null&&t[Je])&&Object.keys(t[Je]).length>0}function Qp(t){return!!(t!=null&&t[ee])&&Object.keys(t[ee]).length>0}function Zp(t){return!!(t!=null&&t[Re])&&t[Re].length>0}function Xp(t){const e=Object.getPrototypeOf(t);return!!(e!=null&&e[et])&&Object.keys(e[et]).length>0}function Jp(t){return t.retention===ue.TTL&&t.extendOnRefresh===!0&&t.ttl!==void 0}function eg(t,e){return t.has(e)}function tg(t){return!t.expiresAt||Date.now()<t.expiresAt}function Ci(t,e,s,r){const o=setTimeout(()=>r(t),e);s.set(t,o)}class sg{constructor(){l(this,"responses",new Map);l(this,"retentionPolicies",new Map);l(this,"cleanupTimers",new Map)}set(e,s,r={retention:ue.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)===ue.IMMEDIATE}shouldExtendTTL(e,s){if(!Jp(s)||!eg(this.responses,e))return!1;const r=this.responses.get(e);return tg(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),Ci(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===ue.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 ue.IMMEDIATE:break;case ue.TTL:s.ttl&&Ci(e,s.ttl,this.cleanupTimers,r=>this.delete(r));break;case ue.SINGLE:break;case ue.PERMANENT:case ue.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 rg{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=fc.create({modelId:s,modelTypeName:r}),i=new wp(e,dt(n,"fsm")),a=new Mp(dt(n,"offline-queue")),c=new hp(e),u=new dp(e),d=new sg;o.serviceResponses=d;const h={fsm:i,offlineQueue:a,serviceResponseStore:d,companionManager:c,childResolver:u};if(Wp(o)&&(h.effectManager=new fp(r,s,o,dt(n,"effect"))),Qp(o)){const f=dt(n,"subscription");h.subscriptionManager=new Yp(e,o,s,a,f),h.onlineLifecycleManager=new Tp(e,dt(n,"online"))}return Zp(o)&&(h.httpRouteManager=new gn(o,dt(n,"http-routes"))),Xp(o)&&(h.serviceRequestManager=new Pp(o,d)),h}}const N=D.getLogger("kos-model"),og="kos.extension.model.loader";class ol{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,"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.modelData=r,this._status=v.CREATED,this._activeStatus=v.INACTIVE,this._onlineStatus=v.OFFLINE;const o=rg.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}),lp(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=Y.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 Yt(this,U.ACTIVATE);try{await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(U.ACTIVATE));const n=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.activate)==null?void 0:r.call(s,n)),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(U.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 uo([{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 uo([{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 uo([{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 Yt(this,U.READY),await Uc(this,fn.READY,U.READY),await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(U.READY));const n=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.ready)==null?void 0:r.call(s,n)),this.offlineQueue.flush(),(o=this.subscriptionManager)==null||o.registerAll(U.READY),N.debug(`Model ${this.modelId} is ready`);const i={modelId:this.modelId,modelType:this.modelTypeName};V($c(this.modelTypeName,this.modelId),i),V(Cc(this.modelTypeName),i)}catch(n){throw N.error(n),Error(n)}}async load(){var o,n,i,a,c,u;const e=this[Et];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===v.LOADED||this.fsm.current===v.LOADING){N.debug(`Model ${s} with id ${r} already loaded or loading`);return}N.debug(`Loading model ${s} with id ${r}`),await Yt(this,U.LOAD);try{const d=Y.getContext(r),h=`${og}.${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(U.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`),(a=this.subscriptionManager)==null||a.registerAll(U.LOAD),(c=this.httpRouteManager)==null||c.registerAll(),(u=this.effectManager)==null||u.setup()}catch(d){throw N.error(`Model ${r} failed to load`,d),d}}async unload(){var e,s,r,o,n,i;N.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const a=this.getChildren().map(u=>{var d;return(d=u.unload)==null?void 0:d.call(u)}).filter(u=>!!u);await Promise.allSettled(a);const c=Y.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.unload)==null?void 0:s.call(e,c)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(o=this.effectManager)==null||o.disposeAll(),(n=this.subscriptionManager)==null||n.disposeAll(),(i=this.httpRouteManager)==null||i.dispose()}catch(a){throw N.debug(`Model ${this.modelId} failed to unload`),a}}async init(){var n,i,a,c;const e=this[Et];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=Y.getContext(s);N.debug(`Initializing model ${r} with id ${s}`),await Yt(this,U.INIT);try{await((n=this.serviceRequestManager)==null?void 0:n.executeForLifecycle(U.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.registerSubscribers(U.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)}async online(){var s,r;N.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e))}async offline(){var s,r,o;N.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=Y.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 nl=t=>typeof t=="function",Di=m.createLogger({name:"kos-model-instantiator"});class ng{constructor(e,s){this.registry=e,this.cache=s}createModelInstance(e,s,r={}){const o=this.registry.models[e];if(!o)throw new Error(`No model registered for type ${e}`);const n=o.singleton?e:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){Di.debug(`Creating model instance: ${e} [${n}]`);const a=o.create?o.create({modelTypeId:e,id:n,options:r}):new o.class(n,r),c=new ol({modelTypeName:e,id:n,modelData:a});this.cache.addModel(c),this._createCompanionModels(c,r)}const i=this.cache.getModelById(n);if(!i)throw Di.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){var n;const r=e.modelTypeName,o=((n=this.registry.companionModels)==null?void 0:n[r])||[];for(const{type:i}of o){const a=nl(i)?i(e.modelData,s):i;if(!a)continue;const c=`${a}-${e.modelId}`,u=this.createModelInstance(a,c,{data:s,companionParent:e.modelData,kosParentId:e.modelId});u!=null&&u.model&&(u.model[Et]=e,e.addCompanionModel(u.model))}}}let ig=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 Lt(e)}};const il=10,xi=m.createLogger({name:"kos-model-manager"});class al{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new lf,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 ig(e),r.cache=new uf(e.preloadModels),r.instantiator=new ng(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(xi.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=>(xi.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 Lt(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(L.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),cc.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),il)))}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)}registerCompanionModel(e,s){this._registry.registerCompanionModel(e,s)}registerModel(e){this._registry.registerModel(e)}}var Xs=(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))(Xs||{}),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 ag=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}},Q=m.createLogger({name:"kos-core"}),cg=()=>{const t=me(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},lg=()=>{const t=window.location.protocol,e=me(),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://")},ug=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=me(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??e??t},dg=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=me(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??e??t},hg=(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)}}},Ai=t=>typeof t.reload=="function",fg=t=>typeof t.unload=="function";var cl=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(cl||{});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=Xs.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),C("token",a=>{a&&(this.transport.token=a.body)}),C(ps.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(mt.GO_ONLINE)}),C(ps.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(ps.RELOAD,()=>{Q.warn("WebSocket requested reload"),this.fsmService.service.send(mt.RELOAD)}),C("/studio/project/reload",()=>{Q.warn("Project requested reload"),this.fsmService.service.send(mt.RELOAD)});const s=Mt.getInstance(),r=ug(),o=dg(),n=lg();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=cg()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=ag(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){Q.info("reload already in progress");return}this._reloading=!0,Q.warn("reloading KOS Core"),Q.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)Ai(c.modelData)&&(Q.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),Q.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&Ai(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(()=>{Q.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){Q.debug("KOS Core going online"),await this._transport.whenReady(),Q.debug("KOS Transport Ready. Calling online() for models"),V("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){Q.debug("KOS Core going offline"),V("/kosCore/offline","/kosCore/offline")}async unload(){var o;Q.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,Q.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)fg(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===Xs.READY)}async ready(){Q.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}=hg(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw Q.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);Q.debug("leaving kos-core ready() ")}get isReady(){return this.status===Xs.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){Q.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,Q.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){Q.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,Q.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)}),x.model.getAll().forEach(([,u])=>{e.models={...e.models,...u.registration}}),e.models={...e.models,...x.model.getLegacyModels()},x.companion.getAll().forEach(([u,d])=>{e.companionModels={...e.companionModels},e.companionModels[u]=e.companionModels[u]||[];for(const h of d)e.companionModels[u].push({type:h})}),x.model.getPreloadModels().forEach(u=>{e.preloadModels.includes(u)||e.preloadModels.push(u)});const n=al.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 Io(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 pg(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 gg(t){return await t.arrayBuffer()}function mg(t,e){return new Blob([t],{type:e})}async function yg(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:Io(i)})}else e[o]=n.toString();return{fields:e,files:s}}function bg(t){return new ReadableStream({async start(){},async pull(e){await t(e)},cancel(){}})}async function vg(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:Io(e),contentType:"application/octet-stream",encoding:"base64"}}if(t instanceof Blob){const e=await gg(t);return{data:Io(e),contentType:t.type||"application/octet-stream",encoding:"base64"}}if(t instanceof FormData){const e=await yg(t);return{data:JSON.stringify(e),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const Hs=m.createLogger({name:"kos-fetch"}),wg=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,Eg=()=>new Promise(t=>{setTimeout(()=>{t(!0)},0)}),Mg=t=>t!=null&&t.studio?Vc:t!=null&&t.fos?Gc:Yc,Tg=async(t,e)=>{const s=O.getInstance().transport;await s.whenReady();const r=ot(),o=new URL(t),n=`${o.pathname}${o.search}`;Hs.debug(`path: ${n}`);const i=(e==null?void 0:e.timeout)||wg,a=Mg(e),c=await vg(e==null?void 0:e.body),u={};c.contentType&&(u["content-type"]=c.contentType),c.encoding&&(u["content-encoding"]=c.encoding);const d=ze(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:Wt({}),status:0,ok:!1,json:async()=>null,body:Qt(""),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:Wt({}),status:0,ok:!1,json:async()=>null,body:Qt(""),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(()=>{Hs.error(`Timeout occurred - url: ${t}`),f&&f(),h({headers:Wt({}),status:404,ok:!1,json:async()=>null,body:Qt(""),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)||{},k=_["content-type"]||"text/plain",R=_["content-encoding"],I=(E==null?void 0:E.body)||"";let S=I;if(R==="base64"&&I)try{S=pg(I)}catch(q){Hs.error("Failed to decode base64 response",q)}const H={headers:Wt(_),status:_.status&&parseInt(_.status)||200,ok:_.status==="200",json:async()=>{try{if(typeof S=="string")return S.length?JSON.parse(S):null;{const J=new TextDecoder().decode(S);return J.length?JSON.parse(J):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?mg(S,k):new Blob([S],{type:k}),formData:async()=>{const q=new FormData;if(k==="multipart/form-data"&&typeof S=="string")try{const J=JSON.parse(S);J.fields&&Object.entries(J.fields).forEach(([qt,zt])=>{q.append(qt,zt)}),J.files&&Hs.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return q},body:e!=null&&e.stream?bg(async q=>{if(S instanceof ArrayBuffer)q.enqueue(new Uint8Array(S));else{const J=new TextEncoder;q.enqueue(J.encode(S))}q.close()}):Qt(typeof S=="string"?S:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};y.unsubscribe(),Eg().then(()=>h(H))});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=Tg;if(process.env.KOS_MOCK_FETCH==="true"){const t=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${t}`}const _g=m.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Sg{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)){_g.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 ll{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 Og=async(t,e)=>{const s=new ll;e.forEach(o=>s.use(o));const r={data:t,result:{}};return await s.execute(r),r.result},Lt=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}}),Ig=t=>{O.getInstance().modelManager.registerModel(t)},$g=(t,e)=>{O.getInstance().modelManager.registerCompanionModel(t,e)},Ri="/kos/ui/internal/heartbeat/",Cg=({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:`${Ri}${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(()=>{tl({msg:{},options:{topic:`${Ri}${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}},ul=(...t)=>e=>t.reduce((s,r)=>r(s),e),Dg={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function xg(t,e){let s=1;const r={...Dg,...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 Ag=m.createLogger({name:"kos-service-request"}),ae=t=>({isMock:!1,URL:exports.BASE_URL}),Rg=(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),Ft(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()},Ft=(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),Pg=(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),Ft(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 ge(`There was a problem retrieving the model; returned status ${f.status}`,y)}return await f.json()},kg=(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),Ft(h,{timeout:u,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:d});const f=r||e;Ag.debug(`resolvedUrl: ${f}`);const p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ge(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()},Lg=(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),Ft(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 ge(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()};class ge extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const Pi=(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),Ft(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 ge(`There was a problem sending the POST data; returned status ${p.status}`,w)}return await p.json()},ki=(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),Ft(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 ge(`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:Pg(t,s||e,c),getModelById:Lg(t,r||e,c),getOne:kg(t,r||e,c),addModel:Pi(t,n||e,c),deleteModel:Rg(t,o||e,c),modifyModel:ki("POST",t,i||e,c),putModel:ki("PUT",t,i||e,c),postModel:Pi(t,n||e,c)}}};function Fg(t,e,s="get"){const r=t.serviceResponses;if(r)return r.getByPath(e,s)}function Ng(t,e,s="get"){const r=t.serviceResponses;return r?r.has(`${s.toUpperCase()}:${e}`):!1}function Ug(t,e,s="get"){const r=t.serviceResponses;r&&r.delete(`${s.toUpperCase()}:${e}`)}function jg(t,e){const s=t.serviceResponses;s&&s.clearPath(e)}function Bg(t){const e=t.serviceResponses;e&&e.clear()}const Kg=ot(),dl=()=>`kos-${Kg}`,Hg=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(dl()),bn=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)}),qg=async(t,e,s)=>{const r=bn(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)},zg=async({topic:t,msg:e,requestId:s})=>{const r=s??ot(),o=bn(r);V(t,e,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},he=new Map;class hl{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=Oe(this._parent))==null?void 0:e.model}get companionModels(){const e=Oe(this._id);return e!=null&&e.model?Mc(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||!he.has(n.id)?!1:(i=he.get(n.id))==null?void 0:i.context.has(e)});if(o)return(s=he.get(o.id))==null?void 0:s.get(e)}if(this._parent)return(r=he.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 Y={createContext:(t,e)=>{const s=he.get(t)??new hl(t);if(e){if(!he.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return he.set(t,s),s},getContext:t=>he.get(t),deleteContext:t=>{he.delete(t)},setParentContext:(t,e)=>{var s;if(!he.has(e))throw new Error(`Parent context ${e} does not exist`);(s=he.get(t))==null||s.setParent(e)},rootContext:()=>he.get("root")};Y.createContext("root");const Vg=t=>Y.getContext(t.id),ho=m.createLogger({name:"kos-data-container"});class vn{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");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=Se(),M.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new dn({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=M.isObservable(e)?e:M.observable.object(e),o=this._disposerMap.get(e.id);o&&(o(),this._disposerMap.delete(e.id)),this._data.set(r.id||"",r),s||this.increment();const n=M.observe(r,i=>{Object.values(this._optionsMap||{}).includes(i.name)&&this.increment()});this._disposerMap.set(r.id||"",n)}removeModel(e){this._data.delete(e),this.increment();const s=this._disposerMap.get(e);s&&(s(),this._disposerMap.delete(e))}updateModel(e){const s=M.observable.object(e);this._data.set(s.id||"",s),this.increment()}getModel(e){return this._data.get(e)}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(ho.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):(ho.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return ho.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}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 Gg{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 ie.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return Te(this.type)}}class Yg{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 ie.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return Te(this.type)}}class fl{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 pl{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 gl=m.createLogger({name:"intent-service"}),Wg=t=>{Yo(`/kos/intent/${t.type}`)?V(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):gl.info(`No subscribers for intent ${t.type}. Intent not sent.`)},Qg=async t=>new Promise(e=>{const{type:s,options:r}=t;if(Yo(`/kos/intent/${t.type}`)){const o=ot(),{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);V(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else gl.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),Ae=m.createLogger({name:"app-startup-service"});async function ml(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=e;if(t.length===0)return Ae.warn("No app IDs provided to waitForAppsToStart"),!0;Ae.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const n=t.map(c=>`/kos/app/started/${c}`),i=await Zo(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>Hc),[u,d]=await c.get("/api/kos/apps/started");return u?(Ae.error("Error fetching started apps:",u),[]):d}catch(c){Ae.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(Ae.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return Ae.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(Ae.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function Zg(t,e={}){return ml([t],e)}async function Xg(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){Ae.error("Failed to check app startup status:",r),t.forEach(o=>s[o]=!1)}return s}async function Jg(){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 Ae.error("Failed to fetch started apps:",t),[]}}const $o=M.when,wn=M.computed,X=M.runInAction,W=M.autorun,yl=M.reaction,En=M.observable,Mn="Not Assigned",em="kos.trouble.added",tm="kos.trouble.removed";var ve=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t))(ve||{}),gs=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(gs||{});const bl=m.createLogger({name:"config-bean-service",group:"Services"}),Tn=exports.BASE_URL,vl=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:sm,getOne:rm}=oe.build({destinationAddress:"",basePath:`${Tn}/kos/config/`}),wl=async(t,e,s="/api/kos/config")=>(bl.debug(`sending modify request for ConfigBean: ${t}`),sm({model:e,urlOverride:`${Tn}${s}/${t}`})),El=async(t,e="/api/kos/config")=>(bl.debug(`sending get request for ConfigBean: ${t}`),await rm({urlOverride:`${Tn}${e}/details/${t}/15`})),_n=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",jr=t=>{try{const e=Number(t);return!isNaN(e)}catch{return!1}};function Ml(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function Tl(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])?Tl(t[r],o,s):s[o]=t[r]}return s}const _l=(t,e)=>{const s=t.details[0].bean||Ml(t.details[0].scopes),r=Tl(s);M.runInAction(()=>{const o={...r};e.props.setValues(o)})},Sl=(t,e)=>{M.runInAction(()=>{t.changes.forEach(s=>{const r=s.attr;let o=s.currentValue,n=s.previousValue;typeof o=="string"&&_n(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})})},Ol=t=>Object.fromEntries(t.props.entries),om=t=>e=>s=>t.build(e,s);var nm=Object.defineProperty,im=Object.getOwnPropertyDescriptor,Il=(t,e,s,r)=>{for(var o=r>1?void 0:r?im(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&&nm(e,s,o),o};function am(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const Sn="config-bean-model",qs=m.getLogger(Sn),cm=nt("path");let ir=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=wl,getConfigBean:r=El}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=Se(),this.prevProps=Se()}get values(){return this.props.values}async ready(){qs.debug(`readying config bean ${this.path}`),qs.debug(`complete readying config bean ${this.path}`)}async load(){qs.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;_l(e,this),qs.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=am(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=Ol(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){Sl(t,this)}};Il([B({topic:`/kos/config/${cm}`,websocket:!0})],ir.prototype,"handleConfigBeanUpdated",1);ir=Il([A(Sn)],ir);const bs=new ye({class:ir,type:Sn}),Br=({path:t,lazy:e,serviceBasePath:s})=>(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:bs.type,id:`${bs.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:U.INIT,lazy:e}},{URL:$l}=ae(),{getOne:lm,getAll:um}=oe.build({basePath:`${$l}/api/kos/regions/info`}),Cl=async()=>{try{return await lm({})}catch{return}},Dl=async()=>{try{return await um({urlOverride:`${$l}/api/kos/regions`})}catch{return}},dm=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:Cl,getRegions:Dl},Symbol.toStringTag,{value:"Module"}));var le=(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))(le||{});const xl={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 hm(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},{...xl});return{...t,...r}}function fm(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,Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,n.alias&&(o[n.alias]=i),o},{time:{[s]:{...xl}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function pm(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 gm=Object.defineProperty,mm=Object.getOwnPropertyDescriptor,On=(t,e,s,r)=>{for(var o=r>1?void 0:r?mm(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&&gm(e,s,o),o};const Js="region-info-model",Gt=m.createLogger({name:"region-info-model"});let vs=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[le.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[le.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[le.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[le.family]!==s[le.family])throw new Error(`Cannot convert between units of different families: ${e[le.family]} and ${s[le.family]}`);const r=e[le.offset],o=e[le.scale],n=s[le.scale],i=s[le.offset],a=s[le.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||Gt.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||Gt.info("Could not find default unit for measure",e.measure)}return!n||!i?(Gt.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,n,i)}async init(){Gt.debug("initializing region info")}async load(){Gt.debug("loading region info");const t=await Dl();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 Cl();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(hm,{}),this.measureMap=e.data.unitSystems.reduce(fm,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(pm,{}),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))}};On([Br({path:"kos:service:region:settings"})],vs.prototype,"regionSource",2);On([Br({path:"kos:service:region"})],vs.prototype,"region",2);vs=On([A(Js)],vs);const re={registration:{[Js]:{class:vs,singleton:!0}},type:Js,factory:ie.Singleton.create(Js)},ar=({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},In=(t,e,s)=>{const{model:r}=Oe(re.type);if(!r)throw new Error("RegionInfo model not found");if(!nr(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=ar({source:e}),i=ar({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(t,n,i)};function Li(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 ym=(t,e,s,r)=>{const o=In(t,e,s),n=ar({source:e}),{model:i}=Oe(re.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},u=ar({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:Li(o,d||n.unit||"",{...f,mode:"long"}),shortDisplay:Li(o,d||n.unit||"",{...f,mode:"short"})}};function Fi({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 Ni({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 ht=(t,e)=>s=>!t||!e?s:jr(s)?In(Number(s),t,e):s,bm=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return Fi(t.options).map(ht(s,r));if(t.options.type==="rangeInterval")return Ni(t.options).map(ht(s,r));if(t.options.type==="list"){const{list:o}=t.options;return o.map(ht(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return Fi(t.options.unitSystems[e]).map(ht(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return Ni(t.options.unitSystems[e]).map(ht(s,r));if(t.options.type==="unitSystemList"&&e){const{list:o}=t.options.unitSystems[e];return o.map(ht(s,r))}}return[]},vm=(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 wm=Object.defineProperty,Em=Object.getOwnPropertyDescriptor,$n=(t,e,s,r)=>{for(var o=r>1?void 0:r?Em(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&&wm(e,s,o),o};function Mm(t){return(t==null?void 0:t.type)==="enum"}function Tm(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 _m(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return je.format(r,e)}const er="config-bean-prop-model",ft=m.createLogger({name:"config-bean-prop-model"}),Sm=nt("path"),Om=nt("serviceBasePath");let ws=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 vl(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?Tm(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=Mm(r)?r.values:bm(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){ft.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(){ft.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 _m(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){ft.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 vm(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){ft.error(`error creating formatter ${d}. Returning the raw value`,h)}}else ft.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,k=((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),R=((p=(f=this.converter)==null?void 0:f.to)==null?void 0:p.system)??this.regionInfo.getUnitSystem(k),I=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:I,...this.converter.from},to:{...this.converter.to,unit:k,system:R},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){ft.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)}};$n([kt({modelType:re.type})],ws.prototype,"regionInfo",2);$n([Br({path:Sm,serviceBasePath:Om})],ws.prototype,"bean",2);ws=$n([A(er)],ws);const it={registration:{[er]:{class:ws,singleton:!1}},type:er,factory:ie.Factory.create(er)};function Im(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:it.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:U.INIT,lazy:n}}}const Al="future-model",Nt=Lt(Al),Kr=m.createLogger({name:"future-service",group:"Services"}),{isMock:$m,URL:Ps}=ae();var Ke=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(Ke||{});const{getAll:Cm,modifyModel:Dm,addModel:xm,deleteModel:Am,postModel:Rm}=oe.build({destinationAddress:"",basePath:`${Ps}/api/future`,mock:$m}),Pm=async()=>await Cm({}),Rl=async(t,e="/api/kos/future")=>(Kr.info(`sending delete request for Future: ${t}`),await Am({id:t,urlOverride:`${Ps}${e}/${t}`})),Pl=async(t,e="/api/kos/future")=>(Kr.info("sending add request for Future"),await xm({model:t,urlOverride:`${Ps}${e}`})),km=async(t,e,s="/api/kos/future")=>(Kr.info(`sending modify request for Future: ${t}`),Dm({model:e,id:t,urlOverride:`${Ps}${s}/${t}`})),kl=async(t,e="/api/kos/future")=>(Kr.info(`sending cancel request for Future: ${t}`),Rm({urlOverride:`${Ps}${e}/${t}/cancel`,ordered:!0,model:{}})),Cn=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}),Dn=(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=Cn(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]})})}))},Ll=t=>e=>s=>t.build(String(e),s),xn=t=>e=>ul(Cn,Ll(t)(e.tracker||e.id))(e);var Lm=Object.defineProperty,Fm=Object.getOwnPropertyDescriptor,Fl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Fm(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&&Lm(e,s,o),o};const fo=m.getLogger(Nt.type);let cr=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=kl,$o(()=>this.status===Ke.Success||this.status===Ke.Fail,()=>{fo.info(`Future ${this.id} has completed with status ${this.status}`),tt(this)})}async load(){fo.debug(`loading Future ${this.id}`)}unload(){fo.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await $o(()=>this.futureId!==Mn),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}`),Dn(t,this)}};Fl([B({topic:`kos.future/${sr}`})],cr.prototype,"handleFutureUpdated",1);cr=Fl([A(Nt.type)],cr);const Nl=cr,Ul=mn();var Nm=Object.defineProperty,Um=Object.getOwnPropertyDescriptor,jl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Um(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&&Nm(e,s,o),o};const Bl="browser-router-model",jm="kos.http.request",Bm="kos.http.response";let lr=class{constructor(t,e,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=t,this.logger=s.logger,this.router=new pl}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),sl({msg:d,options:{responseId:i,destinationAddress:s,type:Bm,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}`)}};jl([B({topic:jm})],lr.prototype,"handleRequest",1);lr=jl([A(Bl)],lr);const An=new _e({class:lr,type:Bl}),Kl="future-container-model",He=Lt(Kl),Hl=t=>xn(Nt)(t),Km=t=>{const e=Hl(t);return He.build(He.type,{}).addFutureModel(e),e},Hm=t=>He.build(He.type,{}).getFuture(String(t)),st={buildFutureModel:Hl,initiateFuture:Km,getFuture:Hm};var qm=Object.defineProperty,zm=Object.getOwnPropertyDescriptor,Rn=(t,e,s,r)=>{for(var o=r>1?void 0:r?zm(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&&qm(e,s,o),o};const zs=m.getLogger(He.type);let Es=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=Rl,addFuture:o=Pl}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=t,this._futures=new Ce,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){zs.error("error deleting a Future"),zs.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=xn(Nt)(s);return this.addFutureModel(r),r}}catch(e){throw zs.error("error creating a Future"),zs.error(e),e}}handleFutureUpdated(t,e){const s=st.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),V(r,e.body,e.headers)}};Rn([$e],Es.prototype,"_futures",2);Rn([B({topic:"kos.future"})],Es.prototype,"handleFutureUpdated",1);Es=Rn([A(He.type)],Es);const ql=Es,{URL:ks}=ae(),{getOne:Vm,postModel:Gm,deleteModel:zl}=oe.build({basePath:`${ks}/api/keyVal`}),Co=m.createLogger({name:"key-value-service",group:"Services"}),Vl=async(t,e)=>{await zl({urlOverride:`${ks}/api/keyVal/${t}/${e}`,id:e})},Gl=async(t,e,s)=>{const r=await Gm({urlOverride:`${ks}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw Co.error("Failed to update key-value data",r),new Error(`Failed to update key-value data for namespace ${t}`);return r.data},Yl=async(t="studio")=>{Co.debug(`Retrieving all key-value data for namespace: ${t}`);const e=await Vm({urlOverride:`${ks}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw Co.error("Failed to retrieve key-value data",e),new Error(`Failed to retrieve key-value data for namespace ${t}`);return e.data},Ym=async t=>{await zl({urlOverride:`${ks}/api/keyVal/${t}`,id:""})},Wm=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Vl,deleteKeyValueNamespace:Ym,getKeyValue:Yl,updateKeyValue:Gl},Symbol.toStringTag,{value:"Module"}));var Qm=Object.defineProperty,Zm=Object.getOwnPropertyDescriptor,Pn=(t,e,s,r)=>{for(var o=r>1?void 0:r?Zm(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&&Qm(e,s,o),o};const Wl="key-value-model";let Ms=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=Se(),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 Gl(this.namespace,t,e),this.data[t]=e):(await Vl(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await Yl(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)}};Pn([B({topic:"/keyVal/set"})],Ms.prototype,"handleStateUpdate",1);Pn([B({topic:"/keyVal/remove"})],Ms.prototype,"handleStateDelete",1);Ms=Pn([A(Wl)],Ms);const kn=new ye({class:Ms,type:Wl});var fe="INUMBER",Ut="IOP1",jt="IOP2",Bt="IOP3",Pe="IVAR",rt="IVARNAME",Tt="IFUNCALL",Hr="IFUNDEF",ne="IEXPR",Ln="IEXPREVAL",at="IMEMBER",qr="IENDSTATEMENT",_t="IARRAY";function P(t,e){this.type=t,this.value=e??0}P.prototype.toString=function(){switch(this.type){case fe:case Ut:case jt:case Bt:case Pe:case rt:case qr:return this.value;case Tt:return"CALL "+this.value;case Hr:return"DEF "+this.value;case _t:return"ARRAY "+this.value;case at:return"."+this.value;default:return"Invalid Instruction"}};function zr(t){return new P(Ut,t)}function Ue(t){return new P(jt,t)}function Ql(t){return new P(Bt,t)}function Do(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===fe||p===rt)Array.isArray(f.value)?n.push.apply(n,Do(f.value.map(function(y){return new P(fe,y)}).concat(new P(_t,f.value.length)),e,s,r,o)):n.push(f);else if(p===Pe&&o.hasOwnProperty(f.value))f=new P(fe,o[f.value]),n.push(f);else if(p===jt&&n.length>1)c=n.pop(),a=n.pop(),d=s[f.value],f=new P(fe,d(a.value,c.value)),n.push(f);else if(p===Bt&&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(fe,d(a.value,c.value,u.value)),n.push(f));else if(p===Ut&&n.length>0)a=n.pop(),d=e[f.value],f=new P(fe,d(a.value)),n.push(f);else if(p===ne){for(;n.length>0;)i.push(n.shift());i.push(new P(ne,Do(f.value,e,s,r,o)))}else if(p===at&&n.length>0)a=n.pop(),n.push(new P(fe,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 Zl(t,e,s){for(var r=[],o=0;o<t.length;o++){var n=t[o],i=n.type;if(i===Pe&&n.value===e)for(var a=0;a<s.tokens.length;a++){var c=s.tokens[a],u;c.type===Ut?u=zr(c.value):c.type===jt?u=Ue(c.value):c.type===Bt?u=Ql(c.value):u=new P(c.type,c.value),r.push(u)}else i===ne?r.push(new P(ne,Zl(n.value,e,s))):r.push(n)}return r}function Qe(t,e,s){var r=[],o,n,i,a,c,u;if(Fn(t))return xe(t,s);for(var d=t.length,h=0;h<d;h++){var f=t[h],p=f.type;if(p===fe||p===rt)r.push(f.value);else if(p===jt)n=r.pop(),o=r.pop(),f.value==="and"?r.push(o?!!Qe(n,e,s):!1):f.value==="or"?r.push(o?!0:!!Qe(n,e,s)):f.value==="="?(a=e.binaryOps[f.value],r.push(a(o,Qe(n,e,s),s))):(a=e.binaryOps[f.value],r.push(a(xe(o,s),xe(n,s))));else if(p===Bt)i=r.pop(),n=r.pop(),o=r.pop(),f.value==="?"?r.push(Qe(o?n:i,e,s)):(a=e.ternaryOps[f.value],r.push(a(xe(o,s),xe(n,s),xe(i,s))));else if(p===Pe)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===Ut)o=r.pop(),a=e.unaryOps[f.value],r.push(a(xe(o,s)));else if(p===Tt){for(u=f.value,c=[];u-- >0;)c.unshift(xe(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===Hr)r.push(function(){for(var w=r.pop(),E=[],_=f.value;_-- >0;)E.unshift(r.pop());var k=r.pop(),R=function(){for(var I=Object.assign({},s),S=0,H=E.length;S<H;S++)I[E[S]]=arguments[S];return Qe(w,e,I)};return Object.defineProperty(R,"name",{value:k,writable:!1}),s[k]=R,R}());else if(p===ne)r.push(Xm(f,e));else if(p===Ln)r.push(f);else if(p===at)o=r.pop(),r.push(o[f.value]);else if(p===qr)r.pop();else if(p===_t){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:xe(r[0],s)}function Xm(t,e,s){return Fn(t)?t:{type:Ln,value:function(r){return Qe(t.value,e,r)}}}function Fn(t){return t&&t.type===Ln}function xe(t,e){return Fn(t)?t.value(e):t}function Nn(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===fe)typeof d.value=="number"&&d.value<0?s.push("("+d.value+")"):Array.isArray(d.value)?s.push("["+d.value.map(Ui).join(", ")+"]"):s.push(Ui(d.value));else if(h===jt)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===Bt)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===Pe||h===rt)s.push(d.value);else if(h===Ut)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===Tt){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());i=s.pop(),s.push(i+"("+a.join(", ")+")")}else if(h===Hr){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===at)r=s.pop(),s.push(r+"."+d.value);else if(h===_t){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());s.push("["+a.join(", ")+"]")}else if(h===ne)s.push("("+Nn(d.value,e)+")");else if(h!==qr)throw new Error("invalid Expression")}return s.length>1&&(e?s=[s.join(",")]:s=[s.join(";")]),String(s[0])}function Ui(t){return typeof t=="string"?JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"):t}function bt(t,e){for(var s=0;s<t.length;s++)if(t[s]===e)return!0;return!1}function Un(t,e,s){s=s||{};for(var r=!!s.withMembers,o=null,n=0;n<t.length;n++){var i=t[n];i.type===Pe||i.type===rt?!r&&!bt(e,i.value)?e.push(i.value):(o!==null&&(bt(e,o)||e.push(o)),o=i.value):i.type===at&&r&&o!==null?o+="."+i.value:i.type===ne?Un(i.value,e,s):o!==null&&(bt(e,o)||e.push(o),o=null)}o!==null&&!bt(e,o)&&e.push(o)}function we(t,e){this.tokens=t,this.parser=e,this.unaryOps=e.unaryOps,this.binaryOps=e.binaryOps,this.ternaryOps=e.ternaryOps,this.functions=e.functions}we.prototype.simplify=function(t){return t=t||{},new we(Do(this.tokens,this.unaryOps,this.binaryOps,this.ternaryOps,t),this.parser)};we.prototype.substitute=function(t,e){return e instanceof we||(e=this.parser.parse(String(e))),new we(Zl(this.tokens,t,e),this.parser)};we.prototype.evaluate=function(t){return t=t||{},Qe(this.tokens,this,t)};we.prototype.toString=function(){return Nn(this.tokens,!1)};we.prototype.symbols=function(t){t=t||{};var e=[];return Un(this.tokens,e,t),e};we.prototype.variables=function(t){t=t||{};var e=[];Un(this.tokens,e,t);var s=this.functions;return e.filter(function(r){return!(r in s)})};we.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 "+Nn(this.simplify(e).tokens,!0)+"; }");return function(){return r.apply(s,arguments)}};var Ts="TEOF",j="TOP",Vr="TNUMBER",Xl="TSTRING",ke="TPAREN",St="TBRACKET",Gr="TCOMMA",jn="TNAME",Bn="TSEMICOLON";function Jl(t,e,s){this.type=t,this.value=e,this.index=s}Jl.prototype.toString=function(){return this.type+": "+this.value};function G(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}G.prototype.newToken=function(t,e,s){return new Jl(t,e,s??this.pos)};G.prototype.save=function(){this.savedPosition=this.pos,this.savedCurrent=this.current};G.prototype.restore=function(){this.pos=this.savedPosition,this.current=this.savedCurrent};G.prototype.next=function(){if(this.pos>=this.expression.length)return this.newToken(Ts,"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)+'"')};G.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(Xl,this.unescape(o),e),t=!0;break}r=this.expression.indexOf(s,r+1)}return t};G.prototype.isParen=function(){var t=this.expression.charAt(this.pos);return t==="("||t===")"?(this.current=this.newToken(ke,t),this.pos++,!0):!1};G.prototype.isBracket=function(){var t=this.expression.charAt(this.pos);return(t==="["||t==="]")&&this.isOperatorEnabled("[")?(this.current=this.newToken(St,t),this.pos++,!0):!1};G.prototype.isComma=function(){var t=this.expression.charAt(this.pos);return t===","?(this.current=this.newToken(Gr,","),this.pos++,!0):!1};G.prototype.isSemicolon=function(){var t=this.expression.charAt(this.pos);return t===";"?(this.current=this.newToken(Bn,";"),this.pos++,!0):!1};G.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(Vr,this.consts[r]),this.pos+=r.length,!0}return!1};G.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};G.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};G.prototype.isWhitespace=function(){for(var t=!1,e=this.expression.charAt(this.pos);(e===" "||e===" "||e===`
|
|
78
|
+
`||e==="\r")&&(t=!0,this.pos++,!(this.pos>=this.expression.length));)e=this.expression.charAt(this.pos);return t};var Jm=/^[0-9a-f]{4}$/i;G.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+=`
|
|
79
|
+
`;break;case"r":s+="\r";break;case"t":s+=" ";break;case"u":var o=t.substring(e+1,e+5);Jm.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};G.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};G.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(Vr,parseInt(this.expression.substring(o,t),e)),this.pos=t),r};G.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(Vr,parseFloat(this.expression.substring(s,e))),this.pos=e):this.pos=r,t};G.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)};G.prototype.isOperatorEnabled=function(t){return this.parser.isOperatorEnabled(t)};G.prototype.getCoordinates=function(){var t=0,e,s=-1;do t++,e=this.pos-s,s=this.expression.indexOf(`
|
|
80
|
+
`,s+1);while(s>=0&&s<this.pos);return{line:t,column:e}};G.prototype.parseError=function(t){var e=this.getCoordinates();throw new Error("parse error ["+e.line+":"+e.column+"]: "+t)};function K(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}K.prototype.next=function(){return this.current=this.nextToken,this.nextToken=this.tokens.next()};K.prototype.tokenMatches=function(t,e){return typeof e>"u"?!0:Array.isArray(e)?bt(e,t.value):typeof e=="function"?e(t):t.value===e};K.prototype.save=function(){this.savedCurrent=this.current,this.savedNextToken=this.nextToken,this.tokens.save()};K.prototype.restore=function(){this.tokens.restore(),this.current=this.savedCurrent,this.nextToken=this.savedNextToken};K.prototype.accept=function(t,e){return this.nextToken.type===t&&this.tokenMatches(this.nextToken,e)?(this.next(),!0):!1};K.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))}};K.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(Pe,this.current.value));else if(this.accept(Vr))t.push(new P(fe,this.current.value));else if(this.accept(Xl))t.push(new P(fe,this.current.value));else if(this.accept(ke,"("))this.parseExpression(t),this.expect(ke,")");else if(this.accept(St,"["))if(this.accept(St,"]"))t.push(new P(_t,0));else{var r=this.parseArrayList(t);t.push(new P(_t,r))}else throw new Error("unexpected "+this.nextToken)};K.prototype.parseExpression=function(t){var e=[];this.parseUntilEndStatement(t,e)||(this.parseVariableAssignmentExpression(e),!this.parseUntilEndStatement(t,e)&&this.pushExpression(t,e))};K.prototype.pushExpression=function(t,e){for(var s=0,r=e.length;s<r;s++)t.push(e[s])};K.prototype.parseUntilEndStatement=function(t,e){return this.accept(Bn)?(this.nextToken&&this.nextToken.type!==Ts&&!(this.nextToken.type===ke&&this.nextToken.value===")")&&e.push(new P(qr)),this.nextToken.type!==Ts&&this.parseExpression(e),t.push(new P(ne,e)),!0):!1};K.prototype.parseArrayList=function(t){for(var e=0;!this.accept(St,"]");)for(this.parseExpression(t),++e;this.accept(Gr);)this.parseExpression(t),++e;return e};K.prototype.parseVariableAssignmentExpression=function(t){for(this.parseConditionalExpression(t);this.accept(j,"=");){var e=t.pop(),s=[],r=t.length-1;if(e.type===Tt){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===Pe&&(t[i]=new P(rt,t[i].value))}this.parseVariableAssignmentExpression(s),t.push(new P(ne,s)),t.push(new P(Hr,e.value));continue}if(e.type!==Pe&&e.type!==at)throw new Error("expected variable for assignment");this.parseVariableAssignmentExpression(s),t.push(new P(rt,e.value)),t.push(new P(ne,s)),t.push(Ue("="))}};K.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(ne,e)),t.push(new P(ne,s)),t.push(Ql("?"))}};K.prototype.parseOrExpression=function(t){for(this.parseAndExpression(t);this.accept(j,"or");){var e=[];this.parseAndExpression(e),t.push(new P(ne,e)),t.push(Ue("or"))}};K.prototype.parseAndExpression=function(t){for(this.parseComparison(t);this.accept(j,"and");){var e=[];this.parseComparison(e),t.push(new P(ne,e)),t.push(Ue("and"))}};var ey=["==","!=","<","<=",">=",">","in"];K.prototype.parseComparison=function(t){for(this.parseAddSub(t);this.accept(j,ey);){var e=this.current;this.parseAddSub(t),t.push(Ue(e.value))}};var ty=["+","-","||"];K.prototype.parseAddSub=function(t){for(this.parseTerm(t);this.accept(j,ty);){var e=this.current;this.parseTerm(t),t.push(Ue(e.value))}};var sy=["*","/","%"];K.prototype.parseTerm=function(t){for(this.parseFactor(t);this.accept(j,sy);){var e=this.current;this.parseFactor(t),t.push(Ue(e.value))}};K.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===ke&&this.nextToken.value==="("){this.restore(),this.parseExponential(t);return}else if(this.nextToken.type===Bn||this.nextToken.type===Gr||this.nextToken.type===Ts||this.nextToken.type===ke&&this.nextToken.value===")"){this.restore(),this.parseAtom(t);return}}var r=this.current;this.parseFactor(t),t.push(zr(r.value))}else this.parseExponential(t)};K.prototype.parseExponential=function(t){for(this.parsePostfixExpression(t);this.accept(j,"^");)this.parseFactor(t),t.push(Ue("^"))};K.prototype.parsePostfixExpression=function(t){for(this.parseFunctionCall(t);this.accept(j,"!");)t.push(zr("!"))};K.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(zr(r.value))}else for(this.parseMemberExpression(t);this.accept(ke,"(");)if(this.accept(ke,")"))t.push(new P(Tt,0));else{var o=this.parseArgumentList(t);t.push(new P(Tt,o))}};K.prototype.parseArgumentList=function(t){for(var e=0;!this.accept(ke,")");)for(this.parseExpression(t),++e;this.accept(Gr);)this.parseExpression(t),++e;return e};K.prototype.parseMemberExpression=function(t){for(this.parseAtom(t);this.accept(j,".")||this.accept(St,"[");){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(at,this.current.value))}else if(e.value==="["){if(!this.tokens.isOperatorEnabled("["))throw new Error('unexpected "[]", arrays are disabled');this.parseExpression(t),this.expect(St,"]"),t.push(Ue("["))}else throw new Error("unexpected symbol: "+e.value)}};function ry(t,e){return Number(t)+Number(e)}function oy(t,e){return t-e}function ny(t,e){return t*e}function iy(t,e){return t/e}function ay(t,e){return t%e}function cy(t,e){return Array.isArray(t)&&Array.isArray(e)?t.concat(e):""+t+e}function ly(t,e){return t===e}function uy(t,e){return t!==e}function dy(t,e){return t>e}function hy(t,e){return t<e}function fy(t,e){return t>=e}function py(t,e){return t<=e}function gy(t,e){return!!(t&&e)}function my(t,e){return!!(t||e)}function yy(t,e){return bt(e,t)}function by(t){return(Math.exp(t)-Math.exp(-t))/2}function vy(t){return(Math.exp(t)+Math.exp(-t))/2}function wy(t){return t===1/0?1:t===-1/0?-1:(Math.exp(t)-Math.exp(-t))/(Math.exp(t)+Math.exp(-t))}function Ey(t){return t===-1/0?t:Math.log(t+Math.sqrt(t*t+1))}function My(t){return Math.log(t+Math.sqrt(t*t-1))}function Ty(t){return Math.log((1+t)/(1-t))/2}function ji(t){return Math.log(t)*Math.LOG10E}function _y(t){return-t}function Sy(t){return!t}function Oy(t){return t<0?Math.ceil(t):Math.floor(t)}function Iy(t){return Math.random()*(t||1)}function Bi(t){return Kn(t+1)}function $y(t){return isFinite(t)&&t===Math.round(t)}var Cy=4.7421875,po=[.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 Kn(t){var e,s;if($y(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)*Kn(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=po[0];for(var u=1;u<po.length;++u)s+=po[u]/(t+u);return e=t+Cy+.5,Math.sqrt(2*Math.PI)*Math.pow(e,t+.5)*Math.exp(-e)*s}function Dy(t){return Array.isArray(t)?t.length:String(t).length}function Ki(){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 Hi(t,e,s){return t?e:s}function xy(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 Ay(t,e,s){return s&&(s[t]=e),e}function Ry(t,e){return t[e|0]}function Py(t){return arguments.length===1&&Array.isArray(t)?Math.max.apply(Math,t):Math.max.apply(Math,arguments)}function ky(t){return arguments.length===1&&Array.isArray(t)?Math.min.apply(Math,t):Math.min.apply(Math,arguments)}function Ly(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 Fy(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 Ny(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 Uy(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 jy(t,e){if(!Array.isArray(e))throw new Error("Second argument to join is not an array");return e.join(t)}function By(t){return(t>0)-(t<0)||+t}var qi=1/3;function Ky(t){return t<0?-Math.pow(-t,qi):Math.pow(t,qi)}function Hy(t){return Math.exp(t)-1}function qy(t){return Math.log(1+t)}function zy(t){return Math.log(t)/Math.LN2}function ct(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||by,cosh:Math.cosh||vy,tanh:Math.tanh||wy,asinh:Math.asinh||Ey,acosh:Math.acosh||My,atanh:Math.atanh||Ty,sqrt:Math.sqrt,cbrt:Math.cbrt||Ky,log:Math.log,log2:Math.log2||zy,ln:Math.log,lg:Math.log10||ji,log10:Math.log10||ji,expm1:Math.expm1||Hy,log1p:Math.log1p||qy,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc||Oy,"-":_y,"+":Number,exp:Math.exp,not:Sy,length:Dy,"!":Bi,sign:Math.sign||By},this.binaryOps={"+":ry,"-":oy,"*":ny,"/":iy,"%":ay,"^":Math.pow,"||":cy,"==":ly,"!=":uy,">":dy,"<":hy,">=":fy,"<=":py,and:gy,or:my,in:yy,"=":Ay,"[":Ry},this.ternaryOps={"?":Hi},this.functions={random:Iy,fac:Bi,min:ky,max:Py,hypot:Math.hypot||Ki,pyt:Math.hypot||Ki,pow:Math.pow,atan2:Math.atan2,if:Hi,gamma:Kn,roundTo:xy,map:Ly,fold:Fy,filter:Ny,indexOf:Uy,join:jy},this.consts={E:Math.E,PI:Math.PI,true:!0,false:!1}}ct.prototype.parse=function(t){var e=[],s=new K(this,new G(this,t),{allowMemberAccess:this.options.allowMemberAccess});return s.parseExpression(e),s.expect(Ts,"EOF"),new we(e,this)};ct.prototype.evaluate=function(t,e){return this.parse(t).evaluate(e)};var eu=new ct;ct.parse=function(t){return eu.parse(t)};ct.evaluate=function(t,e){return eu.parse(t).evaluate(e)};var zi={"+":"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 Vy(t){return zi.hasOwnProperty(t)?zi[t]:t}ct.prototype.isOperatorEnabled=function(t){var e=Vy(t),s=this.options.operators||{};return!(e in s)||!!s[e]};var Gy=Object.defineProperty,Yy=Object.getOwnPropertyDescriptor,Wy=(t,e,s)=>e in t?Gy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Qy=(t,e,s,r)=>{for(var o=r>1?void 0:r?Yy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o},Zy=(t,e,s)=>(Wy(t,e+"",s),s);const Xy="kos-expression-evaluator-model";class Jy{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 ur=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=Se(),this._results=Se(),this.parser=new ct}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 Jy(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=ot();return this.addExpression(e,t),e}};Zy(ur,"Registration");ur=Qy([A({modelTypeId:Xy,singleton:!1})],ur);const tu=ur.Registration,eb=m.createLogger({name:"kos-log-manager-service",group:"Services"}),tb="/api/kos/logs/overrides",su=async()=>(eb.debug("sending GET for kos-log-manager"),await De.get(tb)),sb=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:su},Symbol.toStringTag,{value:"Module"}));var rb=Object.defineProperty,ob=Object.getOwnPropertyDescriptor,Yr=(t,e,s,r)=>{for(var o=r>1?void 0:r?ob(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&&rb(e,s,o),o};const ru="kos-log-manager-model",nb="/kos/logs/override/add/*",ib="/kos/logs/override/remove/*",ab=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 Ot=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new vn}updateModel(t){}resolveLoggers(){const t=m.getLoggers(),s=Object.entries(t).map(([r,o])=>({name:r,level:ab(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 su();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)})}};Yr([uc("/api/kos/ui/loggers")],Ot.prototype,"getAllLoggers",1);Yr([B({topic:nb,websocket:!0,wildcardName:"nodeType"})],Ot.prototype,"handleOverrideAdded",1);Yr([B({topic:ib,websocket:!0,wildcardName:"nodeType"})],Ot.prototype,"handleOverrideRemoved",1);Ot=Yr([A(ru)],Ot);const ou=new _e({class:Ot,type:ru}),{URL:Ls}=ae(),{postModel:Hn,getOne:cb}=oe.build({basePath:`${Ls}/api/kos-time`});m.createLogger({name:"kos-time-service",group:"Services"});const nu=async t=>{const e=await Hn({model:t,urlOverride:`${Ls}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},iu=async t=>{const e=await Hn({model:t,urlOverride:`${Ls}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},au=async t=>{const e=await Hn({model:{},urlOverride:`${Ls}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},cu=async()=>{const t=await cb({urlOverride:`${Ls}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},lb=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:cu,setDate:iu,setTime:nu,setTimezone:au},Symbol.toStringTag,{value:"Module"}));var ub=Object.defineProperty,db=Object.getOwnPropertyDescriptor,Wr=(t,e,s,r)=>{for(var o=r>1?void 0:r?db(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&&ub(e,s,o),o};const Zt="kos-time-model",hb="/kos/time/time",fb="/kos/time/day",pb="/kos/time/timezone";let It=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 nu(t)}async updateSystemDate(t){await iu(t)}async updateSystemTimezone(t){await au(t)}handleTimeChange(){V(gs.TIME_CHANGE,{})}handleDayChange(){V(gs.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),V(gs.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await cu();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};Wr([B({topic:hb,websocket:!0})],It.prototype,"handleTimeChange",1);Wr([B({topic:fb,websocket:!0})],It.prototype,"handleDayChange",1);Wr([B({topic:pb,websocket:!0})],It.prototype,"handleTimeZoneChange",1);It=Wr([A(Zt)],It);const dr={registration:{[Zt]:{class:It,singleton:!0}},type:Zt,predicate:Te(Zt),factory:ie.Singleton.create(Zt)};var gb=Object.defineProperty,mb=Object.getOwnPropertyDescriptor,lu=(t,e,s,r)=>{for(var o=r>1?void 0:r?mb(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&&gb(e,s,o),o};const uu="log-block-container-model";let hr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({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}`)}};lu([$e],hr.prototype,"_models",2);hr=lu([A(uu)],hr);const yb=m.createLogger({name:"log-stream-container-service",group:"Services"}),du=()=>{var r;const t=me(),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},Kt=du(),bb="/api/kos/logs/node/{nodeId}/streams",hu=async()=>(yb.debug("sending GET for log-stream-container"),await De.get(bb,{path:{nodeId:"primary"}},{destinationAddress:Kt})),fu=async(t,e="primary")=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:Kt})},pu=async t=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:Kt})},vb=async()=>{await De.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:Kt})},gu=async t=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:Kt}),mu=async(t,e)=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:Kt}),wb=Object.freeze(Object.defineProperty({__proto__:null,createOverride:vb,getKosConnectionId:du,getLogStreamBlock:mu,getLogStreamBlocks:gu,getLogStreams:hu,subscribeToLogStream:fu,unsubscribeFromLogStream:pu},Symbol.toStringTag,{value:"Module"}));var Eb=Object.getOwnPropertyDescriptor,Mb=(t,e,s,r)=>{for(var o=r>1?void 0:r?Eb(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const yu="log-block-model";let xo=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 mu(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}`)}};xo=Mb([A(yu)],xo);const _s=new ye({class:xo,type:yu}),Qr=new ye({class:hr,type:uu});Qr.addRelatedModel(_s);var Tb=Object.defineProperty,_b=Object.getOwnPropertyDescriptor,bu=(t,e,s,r)=>{for(var o=r>1?void 0:r?_b(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&&Tb(e,s,o),o};const vu="log-stream-model";let fr=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=Qr.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=_s.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=_s.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 fu(this.name)}async unsubscribe(){await pu(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 gu(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=yl(()=>{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()}}};bu([$e],fr.prototype,"_blocks",2);fr=bu([A(vu)],fr);const ms=new ye({class:fr,type:vu});var Sb=Object.defineProperty,Ob=Object.getOwnPropertyDescriptor,lt=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ob(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&&Sb(e,s,o),o};const wu="log-stream-container-model",Ib="/kos/logs/subscription/addBlock/*",$b="/kos/logs/subscription/updateBlock/*",Cb="/kos/logs/subscription/removeBlock/*",Db="/kos/logs/subscription/lines/*",Eu="/kos/logs/streams/add/*";let Le=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 Ce({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: ${Eu}`);const e=t.stream,s=ms.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=ms.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 hu();if(t){this.logger.error(`Error loading log-streams: ${t}`);return}e&&e.forEach(s=>{const r=ms.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};lt([$e],Le.prototype,"_models",2);lt([B({topic:[Eu],websocket:!0})],Le.prototype,"handleStreamAdded",1);lt([B({topic:[Ib],websocket:!0})],Le.prototype,"handleAddBlock",1);lt([B({topic:[Cb],websocket:!0})],Le.prototype,"handleRemoveBlock",1);lt([B({topic:[$b],websocket:!0})],Le.prototype,"handleUpdateBlock",1);lt([B({topic:[Db],websocket:!0})],Le.prototype,"handleLogLine",1);Le=lt([A(wu)],Le);const Fs=new _e({class:Le,type:wu});Fs.addRelatedModel(ms);Fs.addRelatedModel(Qr);Fs.addRelatedModel(_s);const xb=t=>t.rank!==void 0,Ab=t=>t.visibleRole!==void 0,Rb=t=>t.color!==void 0,Pb=t=>{const e=t.info;return xb(e)?e.rank:0},kb=t=>{const e=t.info;return Rb(e)?e.color:"orange"},Lb=t=>{const e=t.info;return Ab(e)?e.visibleRole:"TECHNICIAN"},{URL:Zr}=ae(),{getAll:Fb,postModel:Mu}=oe.build({basePath:`${Zr}/api/kos/troubles`}),Tu=async t=>await Fb({urlOverride:`${Zr}${t}`}),_u=async(t,e="/api/kos/troubles",s)=>{try{const r=await Mu({model:{},urlOverride:`${Zr}${e}/resolve/${t}`,tracker:s});return r!=null&&r.data&&st.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:Ke.Fail,tracker:s,reason:"Failed to resolve trouble"};return st.initiateFuture(o),o}},Nb=async(t,e="/api/kos/troubles",s)=>{try{const r=await Mu({model:t,urlOverride:`${Zr}${e}/resolve/`,tracker:s});return r!=null&&r.data&&st.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:Ke.Fail,tracker:s,reason:"Failed to resolve troubles"};return st.initiateFuture(o),o}},Ub=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:Nb,getTroubles:Tu,resolveTrouble:_u},Symbol.toStringTag,{value:"Module"})),pr="troubleDataMapper",Vs=new Map;As(pr,{register:(t,e)=>{var s;Vs.has(t)||Vs.set(t,[]),(s=Vs.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Vs.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 Ns="troubleMapper",Gs=new Map;As(Ns,{register:(t,e)=>{var s;Gs.has(t)||Gs.set(t,[]),(s=Gs.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Gs.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))}});$[Ns].register("nozzle",async t=>[t.data.nozzlePath]);$[Ns].register("path",async t=>[t.data.path]);const jb=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(n=>$[Ns].execute(n,t));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>e.add(i))}),Array.from(e)},Su=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>$[pr].execute(i,t)),r=$[pr].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 Bb{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class Kb{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class pt{static getHandler(e){switch(e){case"ResolvableTrouble":return new Bb;case"BlockPumpTrouble":return new Kb;default:return}}}var Hb=Object.defineProperty,qb=Object.getOwnPropertyDescriptor,Ou=(t,e,s,r)=>{for(var o=r>1?void 0:r?qb(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&&Hb(e,s,o),o};const Xt="trouble-model";function Ys(t){return typeof t.shouldDefer=="boolean"}let gr=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 Ur(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=pt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:pt.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=pt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:pt.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=pt.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=pt.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 Su(this)}get deferredCompanion(){const t=To(this.id,e=>Ys(e));if(t&&Ys(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=To(this.id,e=>Ys(e));return t&&Ys(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 _u(this._troubleId,this.servicePath,t)}};Ou([ai()],gr.prototype,"resolve",1);gr=Ou([A(Xt)],gr);const Ss={registration:{[Xt]:{class:gr,singleton:!1}},type:Xt,predicate:Te(Xt),factory:ie.Factory.create(Xt)};var Iu=Object.defineProperty,zb=Object.getOwnPropertyDescriptor,Vb=(t,e,s)=>e in t?Iu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,qn=(t,e,s,r)=>{for(var o=r>1?void 0:r?zb(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&&Iu(e,s,o),o},Gb=(t,e,s)=>(Vb(t,e+"",s),s);function Vi(t){return $.propertyMapper.hasMapper(ve.TroubleRank)?$.propertyMapper.executeMapper(ve.TroubleRank,t):Pb(t)}function Gi(t){return($.propertyMapper.hasMapper(ve.TroubleColor)?$.propertyMapper.executeMapper(ve.TroubleColor,t):kb(t)).toLowerCase()}function Yi(t){return($.propertyMapper.hasMapper(ve.TroubleRole)?$.propertyMapper.executeMapper(ve.TroubleRole,t):Lb(t)).toLowerCase()}const Yb="trouble-container-model";class pe{}l(pe,"INDEX_TROUBLES_BY_IFACE","byIface"),l(pe,"INDEX_TROUBLES_BY_TYPE","byType"),l(pe,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(pe,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(pe,"SORT_KEY_RANK","rank"),l(pe,"TROUBLES_DEFERRED","true");let $t=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 Tu(this.servicePath);try{t==null||t.data.forEach(e=>{const s={...e,servicePath:this.servicePath,rank:Vi(e),color:Gi(e),role:Yi(e),id:String(e.id)},r=Ss.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&&tt(s)}handleTroubleAdded(t){const e={...t,servicePath:this.servicePath,rank:Vi(t),color:Gi(t),role:Yi(t),id:String(t.id)};if(e.role==="NONE")return;const s=Ss.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};Gb($t,"Registration");qn([B({topic:"/kos/trouble/remove",websocket:!0,lifecycle:U.INIT})],$t.prototype,"handleTroubleRemoved",1);qn([B({topic:"/kos/trouble/add",websocket:!0})],$t.prototype,"handleTroubleAdded",1);$t=qn([A({modelTypeId:Yb,singleton:!0}),pc(),lc({containerProperty:"troubles",containerOptions:{indexMap:{[pe.INDEX_TROUBLES_BY_IFACE]:jb,[pe.INDEX_TROUBLES_BY_TYPE]:"type",[pe.INDEX_TROUBLES_BY_GROUP]:"group",[pe.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:pe.SORT_KEY_RANK}})],$t);const Ct=$t.Registration,{URL:$u}=ae(),{getAll:Wb}=oe.build({basePath:`${$u}/api/kos/ota`}),Wi=m.createLogger({name:"ota-service",group:"Services"}),Qb=async()=>{Wi.debug("sending GET request to /api/kos/ota/artifacts");const t=await Wb({urlOverride:`${$u}/api/kos/ota/artifacts`});return Wi.debug("getArtifacts - response:",t),t==null?void 0:t.data};var Zb=Object.defineProperty,Xb=Object.getOwnPropertyDescriptor,Xr=(t,e,s,r)=>{for(var o=r>1?void 0:r?Xb(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&&Zb(e,s,o),o};const Cu="ota-model",Jb=t=>{let e=null;for(const s in t){const r=t[s],o=r.lastUpdateTime;(!e||e.lastUpdateTime<o)&&(e=r)}return e},go=t=>{const e=t.artifactInfo,s=Jb(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 Dt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"data",new vn);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 Qb();t&&t.forEach(e=>{const s=go(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=go(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=go(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};Xr([kt({modelType:Ct.type})],Dt.prototype,"troubleContainer",2);Xr([B({topic:"/kos/ota/artifacts/all",websocket:!0})],Dt.prototype,"handleAllArtifacts",1);Xr([B({topic:"/kos/ota/artifacts/changed",websocket:!0})],Dt.prototype,"handleChangedArtifacts",1);Dt=Xr([A(Cu)],Dt);const mr=new _e({class:Dt,type:Cu});function ev(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 mo=m.createLogger({name:"software-info-service",group:"Services"}),zn=async t=>{mo.debug("sending GET for software-info");const[e,s]=await Ul.get("/api/kos/manifest/info",void 0,{signal:t});if(!s)throw t!=null&&t.aborted?(mo.debug("Request was aborted"),new ge("Request was aborted")):(mo.error("Failed to fetch software-info",e),new ge("Failed to fetch software-info"));return s},tv=ev(zn),sv=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:zn,getSoftwareInfosWithCancel:tv},Symbol.toStringTag,{value:"Module"}));var rv=Object.getOwnPropertyDescriptor,ov=(t,e,s,r)=>{for(var o=r>1?void 0:r?rv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Jt="software-info-model";let Ao=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 zn(),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 ge&&this.logger.error("Failed to fetch software-info",t)}}};Ao=ov([A(Jt)],Ao);const yr={registration:{[Jt]:{class:Ao,singleton:!1}},type:Jt,predicate:Te(Jt),factory:ie.Factory.create(Jt)},{URL:Du}=ae(),{getOne:nv}=oe.build({basePath:`${Du}/api/kos/state`}),iv=m.createLogger({name:"state-bean-service",group:"Services"}),xu=async({path:t})=>(iv.debug("sending GET for state-bean"),await nv({urlOverride:`${Du}/api/kos/state/${t}`})),av=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:xu},Symbol.toStringTag,{value:"Module"}));var cv=Object.defineProperty,lv=Object.getOwnPropertyDescriptor,Au=(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 es="state-bean-model",uv=nt("path");let br=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=En.map(new Map),Mo(e,this)}updateModel(t){Mo(t,this)}handleConfigBeanUpdated(t){Object.entries(t).forEach(([e,s])=>{let r=s;typeof r=="string"&&_n(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 xu({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};Au([B({topic:`/kos/state/${uv}`,websocket:!0})],br.prototype,"handleConfigBeanUpdated",1);br=Au([A(es)],br);const Os={registration:{[es]:{class:br,singleton:!1}},type:es,predicate:Te(es),factory:ie.Factory.create(es)};var dv=Object.defineProperty,hv=Object.getOwnPropertyDescriptor,Ru=(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&&dv(e,s,o),o};const ts="state-prop-model",Qi=nt("path");let vr=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())??""}};Ru([kt({modelType:Os.type,id:`state-bean-${Qi}`,options:{path:Qi}})],vr.prototype,"stateBean",2);vr=Ru([A(ts)],vr);const Vn={registration:{[ts]:{class:vr,singleton:!1}},type:ts,predicate:Te(ts),factory:ie.Factory.create(ts)},{URL:fv}=ae(),{getAll:pv}=oe.build({basePath:`${fv}/api/state-prop`}),gv=m.createLogger({name:"state-prop-service",group:"Services"}),mv=async()=>(gv.debug("sending GET for state-prop"),await pv({})),yv=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:mv},Symbol.toStringTag,{value:"Module"})),{URL:Gn}=ae(),{getOne:Pu}=oe.build({basePath:`${Gn}/api/translation`}),ys=m.createLogger({name:"translation-service",group:"Services"}),bv=()=>{const t=window.location.origin,e=me();return(e==null?void 0:e.host)||t},ku=async(t,e)=>{ys.debug(`Loading translations from: ${t}`);const s=e??bv();try{const r=await fetch(`${s}${t}`);return r.status!==200?(ys.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw ys.error("Error fetching translations",r),r}},vv=async()=>{ys.debug("Getting system localization descriptor");const t=await Pu({urlOverride:`${Gn}/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},Lu=t=>async()=>{ys.debug(`Getting KOS localization descriptor for context: ${t}`);const e=await Pu({urlOverride:`${Gn}/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]},Fu="langResolver";var wv=Object.getOwnPropertyDescriptor,Ev=(t,e,s,r)=>{for(var o=r>1?void 0:r?wv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const ss="translation-model";function Mv(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 Nu(t,e=""){return Object.keys(t).reduce((s,r)=>{const o=e?`${e}.${r}`:r;if(typeof t[r]=="object"&&t[r]!==null){const n=Nu(t[r],o);return{...s,...n}}else return{...s,[o]:t[r]}},{})}function Uu(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]=Uu(t[r],e[r]):s[r]=e[r]);return s}const Ro=(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)?Ro(r,e):r},Ws=(t,e,s)=>{const r=/{{(.*?)}}/g,n=Ro(t,e).replace(r,(a,c)=>Object.prototype.hasOwnProperty.call(s||{},c.trim())?s==null?void 0:s[c.trim()]:a);return Ro(n,e)},Zi=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let Po=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(Fu),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=Y.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return ku(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=Uu(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),o),{});this.data=Nu(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=Zi(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}=Mv(e),{namespace:n,key:i}=Zi(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=>Ws(u,this.data,o)):Ws(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[a];return Array.isArray(c)?c.map(u=>Ws(u,this.data,o)):Ws(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()})}};Po=Ev([Lr(),A(ss)],Po);const wr={registration:{[ss]:{class:Po,singleton:!1}},type:ss,predicate:Te(ss),factory:ie.Factory.create(ss)};var Tv=Object.defineProperty,_v=Object.getOwnPropertyDescriptor,ju=(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 rs="translation-container-model",Sv=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function Ov(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 Sv([r,o])}let Er=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||Ov.bind(this),s.kosContext.set(Fu,this.resolver),this.logger=s.logger,this._models=new Ce({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 de(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=wr.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=wr.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)}};ju([$e],Er.prototype,"_models",2);Er=ju([A(rs)],Er);const Fe={registration:{[rs]:{class:Er,singleton:!0}},type:rs,predicate:Te(rs),factory:ie.Singleton.create(rs)},Iv={set(t,e){const s=Y.getContext(Fe.type);s&&s.set(t,e)},get(t){const e=Y.getContext(Fe.type);return e==null?void 0:e.get(t)}},Bu={async init(t){const e=Fe.factory(t);return await de(e),{translations:e}}};function $v(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 Ku="kos-ws-event",Yn=Lt(Ku);var Cv=Object.defineProperty,Dv=Object.getOwnPropertyDescriptor,Wn=(t,e,s,r)=>{for(var o=r>1?void 0:r?Dv(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 xv=({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:xv({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),m.debug(`logged ${this.events.size} events`)}}};Wn([B({topic:[xs.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);Wn([B({topic:[xs.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=Wn([A(Yn.type)],exports.WsEventModel);const Xi=me(),Av=Xi.debug==="true"||Xi.debug===!0,Rv="/api/system/canvas",Hu=async(t,e)=>{const s=e||Rv,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:Av?"false":"true"},body:t})},Pv=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:Hu},Symbol.toStringTag,{value:"Module"}));function Ji(t,e,s){{const r=t.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var kv=Object.defineProperty,Lv=Object.getOwnPropertyDescriptor,qu=(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&&kv(e,s,o),o};const zu="canvas-renderer-model";function yo(t){return typeof t.onDone=="function"}let Mr=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){Hu(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const t=this.isOneShotDone();this.stopStreaming(!t)});return}}handleFrame(t){var s;const e=Ji(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=Ji(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 yo(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=yo(this._renderer);yo(this._renderer)&&this._renderer.onDone(()=>{var c,u,d;this.logger.debug(`Renderer completed for ${this.id}`),V("/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"})})}};qu([kt({modelType:An.type})],Mr.prototype,"router",2);Mr=qu([A(zu)],Mr);const Qn=new ye({class:Mr,type:zu});class Vu{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 Fv{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 Nv extends Fv{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=`
|
|
81
81
|
attribute vec2 a_position;
|
|
82
82
|
void main() {
|
|
83
83
|
gl_Position = vec4(a_position, 0, 1);
|
|
@@ -111,8 +111,8 @@ ${u}topics:${t}
|
|
|
111
111
|
vec3 rgb = hslToRgb(hue, 1.0, 0.5);
|
|
112
112
|
gl_FragColor = vec4(rgb, 1.0);
|
|
113
113
|
}
|
|
114
|
-
`,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 at{constructor(){l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const t=this.canvas.getContext("2d");if(!t)throw new Error("2D canvas not supported");this.ctx=t}dispose(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove()}shouldStep(t){const s=performance.now();return s-this.lastUpdate>=t?(this.lastUpdate=s,!0):!1}readPixels(t,s){return this.ctx.getImageData(0,0,t,s).data}}function Vn(e){class t extends e{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 t}const ov=Vn(at);class nv extends ov{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 iv=Vn(at);class Uu extends iv{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 av extends Nu{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 cv(e){const t=e.replace("#","");if(!/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(t))throw new Error(`Invalid hex color: ${e}`);let s,r,o;return t.length===3?(s=parseInt(t[0]+t[0],16),r=parseInt(t[1]+t[1],16),o=parseInt(t[2]+t[2],16)):(s=parseInt(t.substring(0,2),16),r=parseInt(t.substring(2,4),16),o=parseInt(t.substring(4,6),16)),{r:s,g:r,b:o}}function ju(e){return typeof e=="string"?cv(e):e}function vr(e){const t=ju(e);return`rgb(${t.r},${t.g},${t.b})`}class lv extends at{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=ju(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 b=this.trailColors[p];u=b.r,d=b.g,h=b.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 uv{constructor(t,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(t.baseRenderer.type,t.baseRenderer.data),this.overlayConfigs=t.overlays,this.persistOverlaysOnComplete=t.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 t of this.overlayConfigs){const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{this.loadedIcons.add(t.src)},s.onerror=r=>{console.error(`Failed to load overlay image: ${t.src}`,r)},s.src=t.src,this.overlayIcons.set(t.src,s)}}calculateOverlayPosition(t,s,r){let o,n;if(typeof t.position=="string")switch(t.position){case"top-left":o=0,n=0;break;case"top-center":o=(s-t.size)/2,n=0;break;case"top-right":o=s-t.size,n=0;break;case"center-left":o=0,n=(r-t.size)/2;break;case"center":o=(s-t.size)/2,n=(r-t.size)/2;break;case"center-right":o=s-t.size,n=(r-t.size)/2;break;case"bottom-left":o=0,n=r-t.size;break;case"bottom-center":o=(s-t.size)/2,n=r-t.size;break;case"bottom-right":o=s-t.size,n=r-t.size;break;default:o=0,n=0}else o=t.position.x,n=t.position.y;return t.offset&&(o+=t.offset.x||0,n+=t.offset.y||0),{x:o,y:n}}reset(){this.baseRenderer.reset(),this.baseRendererCompleted=!1,this.hasSignaledCompletion=!1}renderFrame(t,s){if(this.canvas.width=t,this.canvas.height=s,this.ctx.clearRect(0,0,t,s),this.baseRendererCompleted&&this.persistOverlaysOnComplete)this.renderOverlays(t,s);else{this.baseRenderer.renderFrame(t,s);const r=this.baseRenderer.readPixels(t,s);if(r&&r.length>0){const o=new ImageData(r,t,s);this.ctx.putImageData(o,0,0)}this.renderOverlays(t,s)}}renderOverlays(t,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,t,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(t,s){return this.ctx.getImageData(0,0,t,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(t){this.completionCallback=t,this.hasSignaledCompletion&&t()}isOneShot(){return this.persistOverlaysOnComplete?!1:"isOneShot"in this.baseRenderer&&typeof this.baseRenderer.isOneShot=="function"?this.baseRenderer.isOneShot():!1}}class Bu extends at{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,b,w,M,_,F,Q;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=((b=this.scrollConfig)==null?void 0:b.width)||s,c=((w=this.scrollConfig)==null?void 0:w.height)||r);let u,d;switch(o==="left"||o==="right"?(u=0,((M=this.scrollConfig)==null?void 0:M.offsetY)==="center"||((_=this.scrollConfig)==null?void 0:_.offsetY)===void 0?d=(r-c)/2:d=this.scrollConfig.offsetY):(((F=this.scrollConfig)==null?void 0:F.offsetX)==="center"||((Q=this.scrollConfig)==null?void 0:Q.offsetX)===void 0?u=(s-a)/2:u=this.scrollConfig.offsetX,d=0),o){case"left":{const D=s-this.position;if(D<s&&D>-a&&this.ctx.drawImage(this.img,D,d,a,c),this.loopConfig&&this.pauseDuration===0&&this.position>n){const O=D+a+n;O<s&&this.ctx.drawImage(this.img,O,d,a,c)}break}case"right":{const D=-a+this.position;if(D>-a&&D<s&&this.ctx.drawImage(this.img,D,d,a,c),this.loopConfig&&this.pauseDuration===0&&D-n-a>-a){const O=D-a-n;O<s&&this.ctx.drawImage(this.img,O,d,a,c)}break}case"up":{const D=r-this.position;if(D>-c&&D<r&&this.ctx.drawImage(this.img,u,D,a,c),this.loopConfig&&this.pauseDuration===0&&D+c+n<r){const O=D+c+n;O>-c&&this.ctx.drawImage(this.img,u,O,a,c)}break}case"down":{const D=-c+this.position;if(D>-c&&D<r&&this.ctx.drawImage(this.img,u,D,a,c),this.loopConfig&&this.pauseDuration===0&&D-n-c>-c){const O=D-c-n;O<r&&this.ctx.drawImage(this.img,u,O,a,c)}break}}}checkScrollCompletion(s,r,o,n){var h,f,p,b,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=((b=this.scrollConfig)==null?void 0:b.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=vr(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 dv extends at{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(`
|
|
115
|
-
`),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=vr(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 hv{constructor(t){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=t.patterns,this.loopConfig=t.loop??!1,this.transitionDuration=t.transitionDuration??0,this.patternOverrides=t.patternOverrides??{},this.patternStore=t.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 t=this.patterns[this.currentPatternIndex],s=this.patternStore.get(t);if(!s){console.warn(`Pattern "${t}" not found in store, skipping`),this.moveToNextPattern();return}this.currentRenderer&&((i=(n=this.currentRenderer).dispose)==null||i.call(n));const r=this.patternOverrides[t]??{},o={...s.data,...r};try{this.currentRenderer=wr({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 "${t}":`,u),this.moveToNextPattern()}}isDoneAware(t){return typeof(t==null?void 0:t.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 t,s;(s=(t=this.currentRenderer)==null?void 0:t.play)==null||s.call(t)}pause(){var t,s;(s=(t=this.currentRenderer)==null?void 0:t.pause)==null||s.call(t)}renderFrame(t,s){this.width=t,this.height=s,this.canvas.width=t,this.canvas.height=s,this.currentRenderer&&this.currentRenderer.renderFrame(t,s)}readPixels(t,s){return this.currentRenderer?this.currentRenderer.readPixels(t,s):this.ctx.getImageData(0,0,t,s).data}onDone(t){this.completionCallback=t}isOneShot(){var t,s;return this.loopConfig===!1||this.loopConfig===1?this.patterns.length===1&&this.currentRenderer?((s=(t=this.currentRenderer).isOneShot)==null?void 0:s.call(t))??!1:!0:!1}dispose(){var t,s;this.currentRenderer&&((s=(t=this.currentRenderer).dispose)==null||s.call(t)),this.completionCallback=null}setPatternStore(t){this.patternStore=t,this.patterns.length>0&&this.loadCurrentPattern()}}const fv=Vn(at);class pv extends fv{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=vr(r)}setColor(s){this.color=vr(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 gv extends at{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 qi=new Map;$s(te,{register(e,t){qi.set(e,t)},execute(e,t){const s=qi.get(e);return s?new s(t):null}});S.canvas.registerRenderer("video",av);S.canvas.registerRenderer("video-basic",Nu);S[te].register("image-static",Uu);S[te].register("image-scrolling",Bu);const mv=class{constructor(e){var t;return(t=e.scroll)!=null&&t.enabled?new Bu(e):new Uu(e)}};S[te].register("image",mv);S[te].register("color",pv);S[te].register("matrix",lv);S[te].register("sweep",gv);S[te].register("gradient",nv);S[te].register("drop",rv);S[te].register("sequence",hv);S[te].register("text",dv);const yv=class{constructor(e){const t=(s,r)=>{const o=wr({mode:s,data:r});if(!o)throw new Error(`Failed to create renderer of type: ${s}`);return o};return new uv(e,t)}};S[te].register("overlay",yv);const wr=({mode:e,data:t})=>{const s=S[te].execute(e,t);if(s)return s;throw new Error(`Unknown mode: ${e}`)};var bv=Object.defineProperty,vv=Object.getOwnPropertyDescriptor,Bt=(e,t,s,r)=>{for(var o=r>1?void 0:r?vv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&bv(t,s,o),o};const Ku="canvas-dispatcher-model";function wv(e){if(e=e.replace(/^#/,""),e.length===3&&(e=e.split("").map(s=>s+s).join("")),e.length!==6)return null;const t=parseInt(e,16);return{r:t>>16&255,g:t>>8&255,b:t&255}}let ze=class{constructor(e,t,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=e,this.logger=s.logger,this._endpointRenderers=new Se}addNamedEndpoint(e,t){this._endpointRenderers.getModel(e)&&this.logger.warn(`Endpoint "${e}" already exists. Overwriting.`);const s=Gn.instance(e).options({apiPath:t.apiPath,width:t.width,height:t.height,fps:t.fps,durationMs:t.durationMs??null,endpoint:e}).build();return this._endpointRenderers.addModel(s),s}addContent(e,t){this._content.has(e)&&this.logger.warn(`Content "${e}" already exists. Overwriting.`),this._content.set(e,t)}addPattern(e,t){this._patterns.has(e)&&this.logger.warn(`Pattern "${e}" already exists. Overwriting.`),this._patterns.set(e,t)}async handlePatternsPost(e,t){var o,n;const s=e.body,r=Array.isArray(s)?s:[s];if(r.some(i=>!i.id||!i.type||!i.data)){(o=t.status)==null||o.call(t,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=t.status)==null||n.call(t,200).send({status:"OK"})}async handlePatternApplication(e,t){var u,d,h;const s=e.params.pattern,r=e.params.endpoint,o=this._endpointRenderers.getModel(r);if(!o){(u=t.status)==null||u.call(t,404).send({error:`Endpoint "${r}" not found`});return}if(!this._patterns.has(s)){(d=t.status)==null||d.call(t,404).send({error:`Pattern "${s}" not found`});return}const n=this._patterns.get(s),i=n.type,a=e.body||{};this.data={...n.data,...a};const c=i==="sequence"?{...this.data,patternStore:this._patterns}:this.data;o.renderer=wr({mode:i,data:c}),o.setClearOnComplete(n.clearOnComplete),o.startStreaming(),(h=t.status)==null||h.call(t,200).send({status:"OK"})}async handleColorApplication(e,t){var u,d,h;const s=e.params.color,r=wv(s);if(!r){(u=t.status)==null||u.call(t,400).send({error:"Invalid color format"});return}const o=e.params.endpoint,n=this._endpointRenderers.getModel(o);if(!n){(d=t.status)==null||d.call(t,404).send({error:`Endpoint "${o}" not found`});return}const{r:i,b:a,g:c}=r;n.renderer=wr({mode:"color",data:{r:i,g:c,b:a}}),n.startStreaming(),(h=t.status)==null||h.call(t,200).send({status:"OK"})}async handleEndpointCreation(e,t){var r,o;const s=e.body;if(!s.apiPath||!s.id){(r=t.status)==null||r.call(t,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(s.id,s),(o=t.status)==null||o.call(t,200).send({status:"OK"})}async load(e){var s;const t=e==null?void 0:e.get(Ct.loader);t&&((s=t.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)}))}};Bt([Ie],ze.prototype,"_endpointRenderers",2);Bt([Cs("/api/ui/canvas/patterns")],ze.prototype,"handlePatternsPost",1);Bt([Cs("/api/ui/canvas/pattern/:endpoint/:pattern")],ze.prototype,"handlePatternApplication",1);Bt([Cs("/api/ui/canvas/color/:endpoint/:color")],ze.prototype,"handleColorApplication",1);Bt([Cs("/api/ui/canvas/endpoint")],ze.prototype,"handleEndpointCreation",1);ze=Bt([A(Ku)],ze);const Ct=new Me({class:ze,type:Ku}),{URL:Yn}=ae(),{getOne:Hu}=oe.build({basePath:`${Yn}/api/device`}),Er=m.createLogger({name:"device-service",group:"Services"}),zu=async()=>{Er.debug("sending GET for device serial number");try{const e=await Hu({urlOverride:`${Yn}/api/kos/device/serialNumber`});return[void 0,e==null?void 0:e.data.serialNumber]}catch(e){if(e instanceof pe)return Er.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Gu=async()=>{Er.debug("sending GET for device details");try{const e=await Hu({urlOverride:`${Yn}/api/kos/device`});return e?[void 0,e.data]:["unknownError",void 0]}catch(e){if(e instanceof pe)return Er.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Ev=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:Gu,getSerialNumber:zu},Symbol.toStringTag,{value:"Module"}));var Mv=Object.defineProperty,Tv=Object.getOwnPropertyDescriptor,Vu=(e,t,s,r)=>{for(var o=r>1?void 0:r?Tv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Mv(t,s,o),o};const Yu="device-model",_v="/kos/criticalData/changed",Ov="/kos/criticalData/available";let Mr=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_serialNumber");l(this,"_name");l(this,"_nodeId");this.id=e,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[e]=this.nodeId.split("-");return e}get nodeName(){const[,e]=this.nodeId.split("-");return e}updateModel(e){this._serialNumber=e.serialNumber??"unassigned",this._name=e.name??"unassigned",this._nodeId=e.nodeId??"unassigned"}async loadDeviceData(){const[e,t]=await Gu();if(e){this.logger.error(`Error fetching device serial number: ${e}`);return}if(t){const{name:s,nodeId:r}=t;this.updateModel({name:s,nodeId:r,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[e,t]=await zu();if(e){this.logger.error(`Error fetching device serial number: ${e}`);return}this.updateModel({serialNumber:t,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()}};Vu([U({topic:[_v,Ov],websocket:!0})],Mr.prototype,"handleCriticalDataChanged",1);Mr=Vu([A(Yu)],Mr);const Tr=new Me({class:Mr,type:Yu});var Iv=Object.getOwnPropertyDescriptor,Sv=(e,t,s,r)=>{for(var o=r>1?void 0:r?Iv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const qu="network-interface-model";let xo=class{constructor(e,t,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=e,this.logger=s.logger,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}updateModel(e){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}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};xo=Sv([A(qu)],xo);const qn=new me({class:xo,type:qu}),{URL:$v}=ae(),{getAll:Cv}=oe.build({basePath:`${$v}/api/kos/network/interfaces`}),Wi=m.createLogger({name:"network-interface-service",group:"Services"}),Wu=async()=>{Wi.debug("sending GET for copy-logs");try{const e=await Cv({});return[void 0,e==null?void 0:e.data]}catch(e){if(e instanceof pe)return Wi.error(`Error fetching log file size: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Dv=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:Wu},Symbol.toStringTag,{value:"Module"}));var xv=Object.defineProperty,Av=Object.getOwnPropertyDescriptor,Qu=(e,t,s,r)=>{for(var o=r>1?void 0:r?Av(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&xv(t,s,o),o};const Zu="network-interface-container-model";let _r=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e,indexMap:{byCategory:"category"}})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[e,t]=await Wu();if(e){this.logger.error(`Error loading network interfaces: ${e}`);return}t&&t.forEach(s=>{const r=qn.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};Qu([Ie],_r.prototype,"_models",2);_r=Qu([A(Zu)],_r);const Ts=new Me({class:_r,type:Zu});Ts.addRelatedModel(qn);const{URL:Pv}=ae(),{getAll:Rv}=oe.build({basePath:`${Pv}/api/kos/storage/devices`}),Qi=m.createLogger({name:"storage-device-service",group:"Services"}),Xu=async()=>{Qi.debug("sending GET for storage-device");const e=await Rv({});return!(e!=null&&e.data)||e.status!==200?(Qi.error("Failed to retrieve storage-device data",e),[]):e.data},kv=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:Xu},Symbol.toStringTag,{value:"Module"}));var Lv=Object.getOwnPropertyDescriptor,Fv=(e,t,s,r)=>{for(var o=r>1?void 0:r?Lv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const Ju="storage-device-model";let Ao=class{constructor(e,t,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=e,this.logger=s.logger,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}updateModel(e){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}async init(){this.logger.debug(`initializing storage-device ${this.id}`)}async load(){this.logger.debug(`loading storage-device ${this.id}`)}};Ao=Fv([Ar(),A(Ju)],Ao);const Or=new me({class:Ao,type:Ju});var Nv=Object.defineProperty,Uv=Object.getOwnPropertyDescriptor,Wn=(e,t,s,r)=>{for(var o=r>1?void 0:r?Uv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Nv(t,s,o),o};const ed="storage-device-container-model",jv="/kos/storage";let _s=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}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(e){this._models.data.filter(s=>!e.find(r=>r.id===s.id)).forEach(s=>{this.removeModel(s.id)}),e.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=Or.instance(s.id).options(o).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await Xu()).forEach(t=>{if(t.deviceType!=="disk"){const s={...t,kosParentId:this.id},r=Or.instance(t.id).options(s).build();this.addModel(r)}})}};Wn([Ie],_s.prototype,"_models",2);Wn([U({topic:jv,websocket:!0})],_s.prototype,"handleStorageAvailability",1);_s=Wn([A(ed)],_s);const Dt=new Me({class:_s,type:ed});Dt.addRelatedModel(Or);const{URL:Qn}=ae(),{getAll:Bv,postModel:Kv}=oe.build({basePath:`${Qn}/api/kos/update/available`}),Zi=m.createLogger({name:"usb-update-service",group:"Services"}),td=async()=>{Zi.debug("sending GET for usb-update");const e=await Bv({urlOverride:`${Qn}/api/kos/update/available`});return!(e!=null&&e.data)||(e==null?void 0:e.status)!==200?(Zi.error("Failed to retrieve usb-update data",e),[]):e.data},sd=async(e,t,s)=>{const r=await Kv({model:{manifestId:e,deviceId:t},tracker:s,urlOverride:`${Qn}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},Hv=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:td,installUpdate:sd},Symbol.toStringTag,{value:"Module"}));var zv=Object.defineProperty,Gv=Object.getOwnPropertyDescriptor,rd=(e,t,s,r)=>{for(var o=r>1?void 0:r?Gv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&zv(t,s,o),o};const od="usb-update-model";let Ir=class{constructor(e,t,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=e,this.logger=s.logger,this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes,this.futureHandler=new Rr(this)}updateModel(e){this.active=e.active,this.blocked=e.blocked,this.createTime=e.createTime,this.deviceId=e.deviceId,this.manifestId=e.manifestId,this.notes=e.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(e){if(!e)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),sd(this.manifestId,this.deviceId,e)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};rd([si()],Ir.prototype,"install",1);Ir=rd([A(od)],Ir);const Zn=new me({class:Ir,type:od});var Vv=Object.defineProperty,Yv=Object.getOwnPropertyDescriptor,qr=(e,t,s,r)=>{for(var o=r>1?void 0:r?Yv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Vv(t,s,o),o};const nd="usb-update-container-model";let xt=class{constructor(e,t,s){l(this,"id");l(this,"disposer");l(this,"storageService");l(this,"_activeUpdate");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(e){this._activeUpdate=e}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const e=await td();X(()=>{const t=e.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!t.includes(s.id)).forEach(s=>this.removeModel(s.id)),e.forEach(s=>{const r=`${s.deviceId}-${s.manifestId}`,o=Zn.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 e;(e=this.disposer)==null||e.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}`)}};qr([Pt({modelType:Dt.type})],xt.prototype,"storageService",2);qr([Ie],xt.prototype,"_models",2);qr([lc({dependencies:e=>[e.isUsbInserted]})],xt.prototype,"usbInsertedEffect",1);xt=qr([A(nd)],xt);const Os=new Me({class:xt,type:nd});Os.addRelatedModel(Zn);const qv=()=>({...{[Lt.type]:{class:Dl},[He.type]:{class:Ll,singleton:!0},...re.registration,...rt.registration,...St.registration,...mr.registration,...ke.registration,[Hn.type]:{class:exports.WsEventModel,singleton:!0},...Ms.registration,...Bn.registration,...ar.registration}}),Xn=qv(),Wv={models:Xn,preloadModels:[]},Xi=!0,id=e=>()=>{const t=Xn;return bc(Po)(Es).model(St).model(Dt).model(Os).model(Tr).model(hr).model(ps).model(fr).model(Dn).model(Ts).model(Ct).model(Gn).model(Yl).model(Sn,Xi).model(Ps).model(Ql,Xi),Object.keys(t).forEach(s=>{const r=t[s];yc(Po)(s,r)}),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e)}},we={};we.core={models:id(we)};we.preload=x.model.preloadModel(we);we.model=x.model.register(we);we.companion=x.companion.register(we);we.legacy=x.model.registerLegacyModel(we);const Po=we;class Qv{registerTroubleRankMapper(t){return S.propertyMapper.registerPropertyMapper(be.TroubleRank,t),this}registerTroubleRoleMapper(t){return S.propertyMapper.registerPropertyMapper(be.TroubleRole,t),this}registerTroubleColorMapper(t){return S.propertyMapper.registerPropertyMapper(be.TroubleColor,t),this}registerModelLoader(t,s){S.loader.registerLoader(t,s)}registerCanvasPatternLoader(t){S.loader.registerLoader(Ct.loader,t)}}const Zv=async(e,t)=>{const s=Dn.instance(e).options({}).build(),r=t?`${t}-`:"";return await ue(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:()=>{Xe(s)}}},ad="kos:service:region",cd="regionId",Xv=`${ad}-${cd}`,ld=async e=>{const t=rt.factory(Xv)({path:ad,attribute:cd});await ue(t),t.updateProperty(e)},Jn="/kos-timer-event",ei="/kos-timer-event/tick",ti="defaultTimerEnd",es=m.createLogger({name:"timer-manager"}),Jv=e=>e.updateProperty!==void 0;class ud{constructor(t,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=t;const o=typeof s=="number"?s:s.value||60;this.timeout=o,this.state="inactive",this.remainingTime=o,Jv(s)&&Y(()=>{m.info(`Updating config value timer ${t} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:ti}),r&&r.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){es.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&&(es.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(t){this.timeout=t,this.restart()}addTimeoutAction(t){const s=t.remainingTime??0;this.timeoutActions.has(s)||this.timeoutActions.set(s,[]);const r=t.name,o=this.timeoutActions.get(s).find(n=>n.name===r);o?o.action=t.action:this.timeoutActions.get(s).push(t)}removeTimeoutAction(t){for(const[s,r]of this.timeoutActions.entries()){const o=r.filter(n=>n.name!==t);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(t){this.timeoutActions.has(t)&&this.timeoutActions.get(t).forEach(s=>{var r;es.debug(`Executing timer action ${s.name} at ${t}`),(r=s.action)==null||r.call(s,s.name,t),this.notifyTimeoutAction(s),s.singleUse&&(es.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){z(`${ei}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(t){z(Jn,{name:this.name,action:t.name,remainingTime:this.remainingTime})}}const ts=new Map,ht=(e,t)=>{const s=ts.get(e);if(!s){es.error(`Timer ${e} not found`);return}t(s)},dd={createRelativeTimer(e,t,s){const r=new Date,o=Math.round((t.getTime()-r.getTime())/1e3);return this.createTimer(e,o,s)},createTimer(e,t=60,s){if(ts.has(e))return ts.get(e);const r=new ud(e,t,s);return ts.set(e,r),r},getTimer(e){return ts.get(e)},clearTimer(e){ht(e,t=>t.pause())},restartTimer(e){ht(e,t=>t.restart())},resetTimer(e){ht(e,t=>t.reset())},addTimeoutAction(e,t){ht(e,s=>s.addTimeoutAction(t))},removeTimeoutAction(e,t){ht(e,s=>s.removeTimeoutAction(t))},startTimer(e){ht(e,t=>t.start())}},hd="kos:service:region:settings",fd="timeZone",ew=`${hd}-${fd}`,Ro=async e=>{const t=rt.factory(ew)({path:hd,attribute:fd});await ue(t),t.updateProperty(e)},tw=e=>!e||!e.data;function si(e={}){const{alias:t,namespace:s,abortController:r=!1}=e;return(o,n,i)=>{o[os]=o[os]||{},t&&(o[as]=o[as]||new Map,o[as].set(n,t));const a=i.value,c=async function(...u){const d=tt();m.debug(`Calling future service ${n} with tracker ${d}`);let h,f;r&&(h=new AbortController);const p=Je.initiateFuture({tracker:d,id:yn});s&&(p.namespace=s),m.debug(`waiting for future ${p.id} to be ready`),await ue(p),m.debug(`future ${p.id} is ready`),X(()=>{m.debug(`Adding future ${p.id} to futureHandler`),this.futureHandler.addFuture(p,t)}),r&&h&&(f=Y(()=>{(p.status==="CANCELLED"||p.endState===Ke.Canceled)&&(m.debug(`Future ${p.id} cancelled, aborting request`),h==null||h.abort())}),h.signal.addEventListener("abort",async()=>{if(p.status!=="CANCELLED"&&p.endState!==Ke.Canceled&&!p.endState){m.debug(`AbortController aborted, cancelling future ${p.id}`);try{await p.cancelFuture()}catch(w){m.error(`Failed to cancel future ${p.id}:`,w)}}},{once:!0}));const b=()=>{f&&(f(),f=void 0)};try{const w=[...u];if(r&&h){const F=w[w.length-1];F&&typeof F=="object"&&"aborted"in F?w[w.length-1]=h.signal:w.push(h.signal)}w.push(d);const M=await a.apply(this,w);m.debug(`received future response for ${d}`,M);const _=tw(M)?M:M==null?void 0:M.data;return _?(_.progress=1,m.debug("mapping future response to future model"),p.endState?m.debug(`future ${p.id} has already completed. Not updating the model`):On(_,p)):this.futureHandler.removeFuture(t),b(),_}catch(w){if(b(),r&&(h!=null&&h.signal.aborted)){const M=new Error("Operation cancelled");throw m.debug(`Operation ${n} was cancelled`),M}throw m.error(w),w}};o[os][n]={handler:c}}}const sw=({path:e})=>(t,s)=>{t[k]=t[k]||{},t[k][s]={modelType:Ms.type,id:`${Ms.type}-${e}`,options:{path:e},lifecycle:H.INIT}};function rw(e){const{path:t,attribute:s}=e;return(r,o)=>{r[k]=r[k]||{},r[k][o]={modelType:Bn.type,id:`${t}-${s}`,options:{path:t,attribute:s},lifecycle:H.INIT}}}const mt=m.createLogger({name:"services",group:"Services"}),ow=async(e,t)=>pd(e,t,`${exports.BASE_URL}/api/server/login`),pd=async(e,t,s=`${exports.BASE_URL}/api/login`)=>{const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:e,password:t})});if(!r.ok){const n=await r.json();throw Error(`${n==null?void 0:n.error}`)}return await r.json()},nw=async e=>gd(e,`${exports.BASE_URL}/api/server/startPasswordReset`,""),gd=async(e,t=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const r=await exports.kosFetch(`${t}?email=${e}`,{method:"POST",destinationAddress:s});if(!r.ok)throw Error(`There was a problem reseting config; returned status ${r.status}`);return await r.json()},iw=async(e,t)=>md(e,t,`${exports.BASE_URL}/api/server/resetPassword`),md=async(e,t,s=`${exports.BASE_URL}/api/resetPassword`)=>{mt.debug(`resetting password with token ${e} and password ${t.replace(/./g,"*")}`);const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t})});if(mt.debug(`password reset returned status ${r.status}`),!r.ok){mt.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()},aw=async(e,t,s)=>yd(e,t,s,`${exports.BASE_URL}/api/server/acceptInvite`),yd=async(e,t,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{mt.debug(`accepting invite with token ${e} and password ${t.replace(/./g,"*")}`);const o=await exports.kosFetch(`${r}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t,name:s})});if(mt.debug(`invitation accept returned status ${o.status}`),!o.ok){mt.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 cw(e,t,s,r){const o=e instanceof Promise?{promise:e,abortController:t,cancelFuture:s,future:r}:e,{promise:n,abortController:i,cancelFuture:a,future:c}=o,u=n;let d=0,h="PENDING",f=!0;const p=new Set;let b;return c&&typeof c=="object"&&(b=E.autorun(()=>{const w=c.progress||0,M=c.status||"PENDING",_=!c.endState;(w!==d||M!==h||_!==f)&&(d=w,h=M,f=_,p.forEach(F=>{try{F(d,h)}catch(Q){console.warn("Progress callback error:",Q)}}))})),n.finally(()=>{f=!1,i!=null&&i.signal.aborted||(h="COMPLETED",p.forEach(w=>{try{w(d,h)}catch(M){console.warn("Progress callback error:",M)}})),b&&b(),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(M){console.warn("Progress callback error:",M)}}),b&&b()},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 lw=qe.keyframes`
|
|
114
|
+
`,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 ut{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 Zn(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 Uv=Zn(ut);class jv extends Uv{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 Bv=Zn(ut);class Gu extends Bv{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 Kv extends Vu{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 Hv(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 Yu(t){return typeof t=="string"?Hv(t):t}function Tr(t){const e=Yu(t);return`rgb(${e.r},${e.g},${e.b})`}class qv extends ut{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=Yu(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 zv{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 Wu extends ut{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,_,k,R;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):(((k=this.scrollConfig)==null?void 0:k.offsetX)==="center"||((R=this.scrollConfig)==null?void 0:R.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=Tr(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 Vv extends ut{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(`
|
|
115
|
+
`),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=Tr(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 Gv{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=_r({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 Yv=Zn(ut);class Wv extends Yv{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=Tr(r)}setColor(s){this.color=Tr(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 Qv extends ut{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 ea=new Map;As(te,{register(t,e){ea.set(t,e)},execute(t,e){const s=ea.get(t);return s?new s(e):null}});$.canvas.registerRenderer("video",Kv);$.canvas.registerRenderer("video-basic",Vu);$[te].register("image-static",Gu);$[te].register("image-scrolling",Wu);const Zv=class{constructor(t){var e;return(e=t.scroll)!=null&&e.enabled?new Wu(t):new Gu(t)}};$[te].register("image",Zv);$[te].register("color",Wv);$[te].register("matrix",qv);$[te].register("sweep",Qv);$[te].register("gradient",jv);$[te].register("drop",Nv);$[te].register("sequence",Gv);$[te].register("text",Vv);const Xv=class{constructor(t){const e=(s,r)=>{const o=_r({mode:s,data:r});if(!o)throw new Error(`Failed to create renderer of type: ${s}`);return o};return new zv(t,e)}};$[te].register("overlay",Xv);const _r=({mode:t,data:e})=>{const s=$[te].execute(t,e);if(s)return s;throw new Error(`Unknown mode: ${t}`)};var Jv=Object.defineProperty,ew=Object.getOwnPropertyDescriptor,Ht=(t,e,s,r)=>{for(var o=r>1?void 0:r?ew(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&&Jv(e,s,o),o};const Qu="canvas-dispatcher-model";function tw(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 qe=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 Ce}addNamedEndpoint(t,e){this._endpointRenderers.getModel(t)&&this.logger.warn(`Endpoint "${t}" already exists. Overwriting.`);const s=Qn.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=_r({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=tw(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=_r({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(xt.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)}))}};Ht([$e],qe.prototype,"_endpointRenderers",2);Ht([Rs("/api/ui/canvas/patterns")],qe.prototype,"handlePatternsPost",1);Ht([Rs("/api/ui/canvas/pattern/:endpoint/:pattern")],qe.prototype,"handlePatternApplication",1);Ht([Rs("/api/ui/canvas/color/:endpoint/:color")],qe.prototype,"handleColorApplication",1);Ht([Rs("/api/ui/canvas/endpoint")],qe.prototype,"handleEndpointCreation",1);qe=Ht([A(Qu)],qe);const xt=new _e({class:qe,type:Qu}),{URL:Xn}=ae(),{getOne:Zu}=oe.build({basePath:`${Xn}/api/device`}),Sr=m.createLogger({name:"device-service",group:"Services"}),Xu=async()=>{Sr.debug("sending GET for device serial number");try{const t=await Zu({urlOverride:`${Xn}/api/kos/device/serialNumber`});return[void 0,t==null?void 0:t.data.serialNumber]}catch(t){if(t instanceof ge)return Sr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},Ju=async()=>{Sr.debug("sending GET for device details");try{const t=await Zu({urlOverride:`${Xn}/api/kos/device`});return t?[void 0,t.data]:["unknownError",void 0]}catch(t){if(t instanceof ge)return Sr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},sw=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:Ju,getSerialNumber:Xu},Symbol.toStringTag,{value:"Module"}));var rw=Object.defineProperty,ow=Object.getOwnPropertyDescriptor,ed=(t,e,s,r)=>{for(var o=r>1?void 0:r?ow(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 td="device-model",nw="/kos/criticalData/changed",iw="/kos/criticalData/available";let Or=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 Ju();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 Xu();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()}};ed([B({topic:[nw,iw],websocket:!0})],Or.prototype,"handleCriticalDataChanged",1);Or=ed([A(td)],Or);const Ir=new _e({class:Or,type:td});var aw=Object.getOwnPropertyDescriptor,cw=(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=i(o)||o);return o};const sd="network-interface-model";let ko=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}`)}};ko=cw([A(sd)],ko);const Jn=new ye({class:ko,type:sd}),{URL:lw}=ae(),{getAll:uw}=oe.build({basePath:`${lw}/api/kos/network/interfaces`}),ta=m.createLogger({name:"network-interface-service",group:"Services"}),rd=async()=>{ta.debug("sending GET for copy-logs");try{const t=await uw({});return[void 0,t==null?void 0:t.data]}catch(t){if(t instanceof ge)return ta.error(`Error fetching log file size: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},dw=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:rd},Symbol.toStringTag,{value:"Module"}));var hw=Object.defineProperty,fw=Object.getOwnPropertyDescriptor,od=(t,e,s,r)=>{for(var o=r>1?void 0:r?fw(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&&hw(e,s,o),o};const nd="network-interface-container-model";let $r=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({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 rd();if(t){this.logger.error(`Error loading network interfaces: ${t}`);return}e&&e.forEach(s=>{const r=Jn.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};od([$e],$r.prototype,"_models",2);$r=od([A(nd)],$r);const Is=new _e({class:$r,type:nd});Is.addRelatedModel(Jn);const{URL:pw}=ae(),{getAll:gw}=oe.build({basePath:`${pw}/api/kos/storage/devices`}),sa=m.createLogger({name:"storage-device-service",group:"Services"}),id=async()=>{sa.debug("sending GET for storage-device");const t=await gw({});return!(t!=null&&t.data)||t.status!==200?(sa.error("Failed to retrieve storage-device data",t),[]):t.data},mw=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:id},Symbol.toStringTag,{value:"Module"}));var yw=Object.getOwnPropertyDescriptor,bw=(t,e,s,r)=>{for(var o=r>1?void 0:r?yw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const ad="storage-device-model";let Lo=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}`)}};Lo=bw([Lr(),A(ad)],Lo);const Cr=new ye({class:Lo,type:ad});var vw=Object.defineProperty,ww=Object.getOwnPropertyDescriptor,ei=(t,e,s,r)=>{for(var o=r>1?void 0:r?ww(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&&vw(e,s,o),o};const cd="storage-device-container-model",Ew="/kos/storage";let $s=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({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=Cr.instance(s.id).options(o).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await id()).forEach(e=>{if(e.deviceType!=="disk"){const s={...e,kosParentId:this.id},r=Cr.instance(e.id).options(s).build();this.addModel(r)}})}};ei([$e],$s.prototype,"_models",2);ei([B({topic:Ew,websocket:!0})],$s.prototype,"handleStorageAvailability",1);$s=ei([A(cd)],$s);const At=new _e({class:$s,type:cd});At.addRelatedModel(Cr);const{URL:ti}=ae(),{getAll:Mw,postModel:Tw}=oe.build({basePath:`${ti}/api/kos/update/available`}),ra=m.createLogger({name:"usb-update-service",group:"Services"}),ld=async()=>{ra.debug("sending GET for usb-update");const t=await Mw({urlOverride:`${ti}/api/kos/update/available`});return!(t!=null&&t.data)||(t==null?void 0:t.status)!==200?(ra.error("Failed to retrieve usb-update data",t),[]):t.data},ud=async(t,e,s)=>{const r=await Tw({model:{manifestId:t,deviceId:e},tracker:s,urlOverride:`${ti}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},_w=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:ld,installUpdate:ud},Symbol.toStringTag,{value:"Module"}));var Sw=Object.defineProperty,Ow=Object.getOwnPropertyDescriptor,dd=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ow(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&&Sw(e,s,o),o};const hd="usb-update-model";let Dr=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 Ur(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}`),ud(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}`)}};dd([ai()],Dr.prototype,"install",1);Dr=dd([A(hd)],Dr);const si=new ye({class:Dr,type:hd});var Iw=Object.defineProperty,$w=Object.getOwnPropertyDescriptor,Jr=(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 fd="usb-update-container-model";let Rt=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 Ce({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 ld();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=si.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}`)}};Jr([kt({modelType:At.type})],Rt.prototype,"storageService",2);Jr([$e],Rt.prototype,"_models",2);Jr([gc({dependencies:t=>[t.isUsbInserted]})],Rt.prototype,"usbInsertedEffect",1);Rt=Jr([A(fd)],Rt);const Cs=new _e({class:Rt,type:fd});Cs.addRelatedModel(si);const Cw=()=>({...{[Nt.type]:{class:Nl},[He.type]:{class:ql,singleton:!0},...re.registration,...it.registration,...Ct.registration,...wr.registration,...Fe.registration,[Yn.type]:{class:exports.WsEventModel,singleton:!0},...Os.registration,...Vn.registration,...dr.registration}}),ri=Cw(),Dw={models:ri,preloadModels:[]},oa=!0,pd=t=>()=>{const e=ri;return _c(Fo)(Ss).model(Ct).model(At).model(Cs).model(Ir).model(mr).model(bs).model(yr).model(kn).model(Is).model(xt).model(Qn).model(tu).model(An,oa).model(Fs).model(ou,oa),Object.keys(e).forEach(s=>{const r=e[s];Tc(Fo)(s,r)}),{preload:x.model.preloadModel(t),model:x.model.register(t),companion:x.companion.register(t),legacy:x.model.registerLegacyModel(t)}},Me={};Me.core={models:pd(Me)};Me.preload=x.model.preloadModel(Me);Me.model=x.model.register(Me);Me.companion=x.companion.register(Me);Me.legacy=x.model.registerLegacyModel(Me);const Fo=Me;class xw{registerTroubleRankMapper(e){return $.propertyMapper.registerPropertyMapper(ve.TroubleRank,e),this}registerTroubleRoleMapper(e){return $.propertyMapper.registerPropertyMapper(ve.TroubleRole,e),this}registerTroubleColorMapper(e){return $.propertyMapper.registerPropertyMapper(ve.TroubleColor,e),this}registerModelLoader(e,s){$.loader.registerLoader(e,s)}registerCanvasPatternLoader(e){$.loader.registerLoader(xt.loader,e)}}const Aw=async(t,e)=>{const s=kn.instance(t).options({}).build(),r=e?`${e}-`:"";return await de(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:()=>{tt(s)}}},gd="kos:service:region",md="regionId",Rw=`${gd}-${md}`,yd=async t=>{const e=it.factory(Rw)({path:gd,attribute:md});await de(e),e.updateProperty(t)},oi="/kos-timer-event",ni="/kos-timer-event/tick",ii="defaultTimerEnd",os=m.createLogger({name:"timer-manager"}),Pw=t=>t.updateProperty!==void 0;class bd{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,Pw(s)&&W(()=>{m.info(`Updating config value timer ${e} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:ii}),r&&r.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){os.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&&(os.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;os.debug(`Executing timer action ${s.name} at ${e}`),(r=s.action)==null||r.call(s,s.name,e),this.notifyTimeoutAction(s),s.singleUse&&(os.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){V(`${ni}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(e){V(oi,{name:this.name,action:e.name,remainingTime:this.remainingTime})}}const ns=new Map,gt=(t,e)=>{const s=ns.get(t);if(!s){os.error(`Timer ${t} not found`);return}e(s)},vd={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(ns.has(t))return ns.get(t);const r=new bd(t,e,s);return ns.set(t,r),r},getTimer(t){return ns.get(t)},clearTimer(t){gt(t,e=>e.pause())},restartTimer(t){gt(t,e=>e.restart())},resetTimer(t){gt(t,e=>e.reset())},addTimeoutAction(t,e){gt(t,s=>s.addTimeoutAction(e))},removeTimeoutAction(t,e){gt(t,s=>s.removeTimeoutAction(e))},startTimer(t){gt(t,e=>e.start())}},wd="kos:service:region:settings",Ed="timeZone",kw=`${wd}-${Ed}`,No=async t=>{const e=it.factory(kw)({path:wd,attribute:Ed});await de(e),e.updateProperty(t)},Lw=t=>!t||!t.data;function ai(t={}){const{alias:e,namespace:s,abortController:r=!1,trackerPolicy:o="id"}=t;return(n,i,a)=>{n[cs]=n[cs]||{},e&&(n[ds]=n[ds]||new Map,n[ds].set(i,e));const c=a.value,u=async function(...d){const h=ot();m.debug(`Calling future service ${i} with tracker ${h}`);let f,p;r&&(f=new AbortController);const y=st.initiateFuture({tracker:h,id:Mn});s&&(y.namespace=s),m.debug(`waiting for future ${y.id} to be ready`),await de(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=W(()=>{(y.status==="CANCELLED"||y.endState===Ke.Canceled)&&(m.debug(`Future ${y.id} cancelled, aborting request`),f==null||f.abort())}),f.signal.addEventListener("abort",async()=>{if(y.status!=="CANCELLED"&&y.endState!==Ke.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 R=E[E.length-1];R&&typeof R=="object"&&"aborted"in R?E[E.length-1]=f.signal:E.push(f.signal)}if(o==="context"){const R=E[E.length-1];if(un(R))R.$tracker=h;else{const I={[Fr]:!0,$tracker:h};E.push(I)}}else E.push(h);const _=await c.apply(this,E);m.debug(`received future response for ${h}`,_);const k=Lw(_)?_:_==null?void 0:_.data;return k?(k.progress=1,m.debug("mapping future response to future model"),y.endState?m.debug(`future ${y.id} has already completed. Not updating the model`):Dn(k,y)):this.futureHandler.removeFuture(e),w(),k}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[cs][i]={handler:u}}}const Fw=({path:t})=>(e,s)=>{e[F]=e[F]||{},e[F][s]={modelType:Os.type,id:`${Os.type}-${t}`,options:{path:t},lifecycle:U.INIT}};function Nw(t){const{path:e,attribute:s}=t;return(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:Vn.type,id:`${e}-${s}`,options:{path:e,attribute:s},lifecycle:U.INIT}}}const vt=m.createLogger({name:"services",group:"Services"}),Uw=async(t,e)=>Md(t,e,`${exports.BASE_URL}/api/server/login`),Md=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()},jw=async t=>Td(t,`${exports.BASE_URL}/api/server/startPasswordReset`,""),Td=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()},Bw=async(t,e)=>_d(t,e,`${exports.BASE_URL}/api/server/resetPassword`),_d=async(t,e,s=`${exports.BASE_URL}/api/resetPassword`)=>{vt.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(vt.debug(`password reset returned status ${r.status}`),!r.ok){vt.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()},Kw=async(t,e,s)=>Sd(t,e,s,`${exports.BASE_URL}/api/server/acceptInvite`),Sd=async(t,e,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{vt.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(vt.debug(`invitation accept returned status ${o.status}`),!o.ok){vt.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 Hw(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(k=>{try{k(d,h)}catch(R){console.warn("Progress callback error:",R)}}))})),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 qw=We.keyframes`
|
|
116
116
|
0% {
|
|
117
117
|
left: -90px;
|
|
118
118
|
color: #eee;
|
|
@@ -124,13 +124,13 @@ ${u}topics:${t}
|
|
|
124
124
|
left: 90px;
|
|
125
125
|
color: #eee;
|
|
126
126
|
}
|
|
127
|
-
`,
|
|
127
|
+
`,zw=We.css`
|
|
128
128
|
font-size: 100px;
|
|
129
129
|
margin-top: -80px;
|
|
130
130
|
position: relative;
|
|
131
|
-
animation: ${
|
|
131
|
+
animation: ${qw} ease-in-out infinite alternate;
|
|
132
132
|
animation-duration: 1.2s;
|
|
133
|
-
`,
|
|
133
|
+
`,Vw=({children:t})=>ca.createPortal(t,document.body);function Od({message:t="Wait a moment while we load your app.",theme:e="light"}){return T.jsx(Vw,{children:T.jsxs(Gw,{theme:e,children:[t,T.jsx("div",{css:zw,children:"."})]})})}const Gw=Ko.div`
|
|
134
134
|
padding-inline: 20px;
|
|
135
135
|
width: 100%;
|
|
136
136
|
height: 100vh;
|
|
@@ -142,33 +142,33 @@ ${u}topics:${t}
|
|
|
142
142
|
font-size: 14px;
|
|
143
143
|
top: 0;
|
|
144
144
|
left: 0;
|
|
145
|
-
color: ${({theme:
|
|
145
|
+
color: ${({theme:t})=>t==="light"?"black":"white"};
|
|
146
146
|
z-index: 10000;
|
|
147
|
-
`;class
|
|
147
|
+
`;class Id 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 Yw={normal:"#B5F7F6",warn:"#F3D78A",error:"#FC8486"},Ww=({value:t=0,title:e,status:s="normal",subtitle:r})=>{const o=We.css`
|
|
148
148
|
display: flex;
|
|
149
149
|
flex-direction: column;
|
|
150
|
-
`,n=
|
|
150
|
+
`,n=We.css`
|
|
151
151
|
position: relative;
|
|
152
152
|
height: 18px;
|
|
153
153
|
width: 100%;
|
|
154
154
|
background-color: #ddd;
|
|
155
155
|
border-radius: 5px;
|
|
156
156
|
overflow: hidden;
|
|
157
|
-
`,i=
|
|
157
|
+
`,i=We.css`
|
|
158
158
|
position: absolute;
|
|
159
159
|
top: 50%; /* position the top edge of the element at the middle of the parent */
|
|
160
160
|
left: 50%; /* position the left edge of the element at the middle of the parent */
|
|
161
161
|
z-index: 5;
|
|
162
162
|
transform: translate(-50%, -50%);
|
|
163
163
|
font-size: smaller;
|
|
164
|
-
`,a=
|
|
165
|
-
width: ${
|
|
164
|
+
`,a=We.css`
|
|
165
|
+
width: ${t}%;
|
|
166
166
|
height: 35px;
|
|
167
|
-
background-color: ${
|
|
167
|
+
background-color: ${Yw[s]};
|
|
168
168
|
text-align: center;
|
|
169
169
|
line-height: 32px;
|
|
170
170
|
color: black;
|
|
171
|
-
`,c=
|
|
171
|
+
`,c=We.css`
|
|
172
172
|
animation: indeterminateAnimation 1s infinite linear;
|
|
173
173
|
transform-origin: 0% 50%;
|
|
174
174
|
@keyframes indeterminateAnimation {
|
|
@@ -182,7 +182,7 @@ ${u}topics:${t}
|
|
|
182
182
|
transform: translateX(100%) scaleX(0.5);
|
|
183
183
|
}
|
|
184
184
|
}
|
|
185
|
-
`;return T.jsxs("div",{css:o,children:[T.jsxs("div",{css:n,children:[T.jsx("div",{css:i,children:
|
|
185
|
+
`;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})]})},Qw={setModel:()=>!1},eo=g.createContext(Qw),Zw=()=>{const t=g.useContext(eo);if(t==null)throw new Error("useModels must be used within a KosModelProvider");return t.model},$d=({children:t})=>{const[e,s]=g.useState(),r=g.useCallback(o=>(s(o),!0),[s]);return T.jsx(eo.Provider,{value:{model:e,setModel:r},children:t})},Cd=m.createLogger({name:"kos-model-hierarchy-context"}),Xw={models:[],addModel:()=>{Cd.debug("Default implementation being used. Do Nothing.")}},to=g.createContext(Xw),Jw=({children:t})=>{const[e,s]=g.useState([]),r=g.useCallback(o=>{e.includes(o)||(Cd.debug("adding to hierarchy context",o.id),s(n=>[...n,o]))},[e]);return T.jsx(to.Provider,{value:{models:e,addModel:r},children:t})},eE=()=>!0,Dd=t=>{const e=g.useContext(to);if(!e)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(t==null?void 0:t.filter)||eE;return g.useMemo(()=>e.models.filter(s),[e.models,s])},tE=t=>Dd({filter:s=>{const r=Oe(s.id);return(r==null?void 0:r.type)===t}})[0],sE=m.createLogger({name:"kos-model-loader"}),rE=()=>T.jsx("div",{}),xd=({fallback:t,children:e,...s})=>T.jsx($d,{children:T.jsx(Id,{fallback:t,children:T.jsx(g.Suspense,{children:T.jsx(Ad,{...s,children:e})})})}),Ad=t=>{const[e,s]=g.useState(),[r,o]=g.useState(!1),{setModel:n}=g.useContext(eo),i=g.useContext(to);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 sE.error(t.error),new Error(t.error);const a=t.loading||T.jsx(rE,{});return T.jsx(T.Fragment,{children:e&&r?t.children:a})},tr={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},Rd=g.createContext(tr),oE=({translations:t=tr,children:e})=>{const s={header:{...tr.header,...t.header},createModal:{...tr.createModal,...t.createModal}};return T.jsx(Rd.Provider,{value:s,children:e})};function nE(t,e){const s=O.create(t,!1,e),r=s.whenReady().then(()=>s);return Xo(r)}const Pd=g.createContext(void 0),iE=(t={models:{},preloadModels:[]},e)=>{const s=nE(t,e),r=({children:o})=>{const n=s.read(),[i,a]=g.useState(n.isOnline);return g.useEffect(()=>{const c=W(()=>{a(n.isOnline)});return()=>{c()}},[n]),T.jsx(Pd.Provider,{value:{kosCore:n,online:i},children:o})};return{KosCoreContextProvider:Ho.observer(r)}},kd=()=>{const t=g.useContext(Pd);if(t===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return t},aE=8,cE=(t=0)=>new Promise(e=>{setTimeout(()=>{e(!0)},2**t*10)}),Ze=new Map;function lE(t,e){if(Ze.has(t)){const s=Ze.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(()=>{Ze.set(t,{status:"finished",key:t})},o=>{throw Ze.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw Ze.set(t,r),s}}function uE(t,e){return lE(t,e)}async function dE(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>aE)throw Error(`KOS Model ${s} has not been found`);await cE(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 Z=t=>{const{modelId:e,modelType:s,activate:r,destroyOnUnmount:o}=t,n=kd(),[i,a]=g.useState(!1),[c,u]=g.useState(),{kosModel:d,model:h}=uE(e||s||"",()=>dE(n.kosCore,t));return g.useEffect(()=>{t.forceUpdate&&h&&hn(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(L.GO_ACTIVE,v.ACTIVE)),a(!0),d}catch(y){throw u(y.message),y}}let p;return n.kosCore&&e&&f().then(y=>{p=W(()=>{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(L.GO_INACTIVE,v.INACTIVE).then(()=>{if(o){const w=h.id;tt(h).then(()=>{Ze.delete(w),p==null||p()})}})}}else o&&h&&tt(h).then(()=>{Ze.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:xd}},ci=()=>{const t=dr.type;return Z({modelId:t,modelType:dr.type,options:{}})},li=g.createContext(void 0),hE=({children:t})=>{const{model:e,ready:s}=ci(),r=g.useMemo(()=>s&&e?{model:e}:{},[s,e]);return T.jsx(li.Provider,{value:r,children:t})},fE=()=>{const t=g.useContext(li);if(!t)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return t},ui=()=>{const t=yr.type;return Z({modelId:t,modelType:yr.type,options:{}})};function pE(t){return()=>e=>{const{model:s,status:r,KosModelLoader:o}=ui();return T.jsx(o,{...r,children:T.jsx(t,{...e,softwareInfo:s})})}}const di=g.createContext(void 0),gE=({children:t})=>{const{model:e,ready:s}=ui(),r=g.useMemo(()=>s&&e?{model:e}:{},[s,e]);return T.jsx(di.Provider,{value:r,children:t})},mE=()=>{const t=g.useContext(di);if(!t)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return t},Ld=new fl,Fd=g.createContext(Ld);function yE({children:t}){return T.jsx(Fd.Provider,{value:Ld,children:t})}const hi=g.createContext(void 0),bE=()=>{const t=window.location.origin,e=me();return(e==null?void 0:e.host)||t},vE=({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||bE(),p=g.useMemo(()=>e??"app/system",[e]);g.useEffect(()=>{async function E(){const k=(Array.isArray(p)?p:[p]).map(H=>(n||Lu(H))()),S=(await Promise.allSettled(k)).map(H=>{if(H.status==="rejected"){m.warn("Failed to load localization descriptor",H.reason);return}return H.value}).filter(H=>!!H).reverse().reduce((H,q)=>{const J=q.path;return Object.keys(q.namespaces).forEach(qt=>{const zt=q.namespaces[qt];zt.basePath=J}),{...H,namespaces:{...H.namespaces,...q.namespaces}}},{});u(S)}E()},[p,n]),g.useEffect(()=>{async function E(){if(c){const _=f,{translations:k}=await Bu.init({lang:s,descriptor:c,defaultNamespace:"common",resolver:r,rootUrl:_});h(k),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(hi.Provider,{value:y,children:w})},wE=()=>{const t=g.useContext(hi);if(!t)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return t},EE=()=>{const t=xt.type;return Z({modelId:t,modelType:xt.type,options:{}})};function ME(t){return e=>{const{model:s,status:r,KosModelLoader:o}=EE();return T.jsx(o,{...r,children:T.jsx(t,{...e,canvasDispatcher:s})})}}const TE=(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 _E({ctx:t,format:e,dataString:s,width:r,height:o,pixelSize:n}){const i=TE(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 SE=m.createLogger({name:"canvas-streamer"});SE.debug("main-view component loaded");const bo=10,Nd=Ho.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&&_E({ctx:f,format:"base64",dataString:h,height:e,width:s,pixelSize:bo})}},[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&&ca.createPortal(T.jsx(IE,{children:T.jsx($E,{children:T.jsx("canvas",{ref:a,width:s*bo,height:e*bo,style:{border:"1px solid black"}})})}),document.body)}),OE=ME(Nd),IE=Ko.div`
|
|
186
186
|
display: flex;
|
|
187
187
|
flex-direction: column;
|
|
188
188
|
gap: 8px;
|
|
@@ -190,9 +190,9 @@ ${u}topics:${t}
|
|
|
190
190
|
width: 100%;
|
|
191
191
|
justify-content: space-between;
|
|
192
192
|
align-items: center;
|
|
193
|
-
|
|
193
|
+
`,$E=Ko.div`
|
|
194
194
|
display: flex;
|
|
195
195
|
flex-direction: column;
|
|
196
196
|
align-items: center;
|
|
197
|
-
`,xd=()=>{const e=Tr.type;return Z({modelId:e,modelType:Tr.type,options:{}})};function qw(e){return t=>{const{model:s,status:r,KosModelLoader:o}=xd();return T.jsx(o,{...r,children:T.jsx(e,{...t,device:s})})}}function Ww(e,t,s){const r=new Promise(o=>{I.getInstance().whenReady().then(()=>{const{model:n}=I.getInstance().modelManager.createModelInstance(e,t??e,s);return n.whenReady().then(()=>{o(n.modelData)})})});return qo(r)}function Qw(e){return t=>{const{model:s,status:r,KosModelLoader:o}=ri();return T.jsx(o,{...r,children:T.jsx(e,{...t,kosTime:s})})}}const Ad=()=>{const e=Ts.type;return Z({modelId:e,modelType:Ts.type,options:{}})};function Zw(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Ad();return T.jsx(o,{...r,children:T.jsx(e,{...t,networkInterfaceContainer:s})})}}const Pd=()=>{const e=hr.type;return Z({modelId:e,modelType:hr.type,options:{}})};function Xw(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Pd();return T.jsx(o,{...r,children:T.jsx(e,{...t,oTA:s})})}}function Jw(e,t){g.useEffect(()=>{function s(o){e.current&&!e.current.contains(o.target)&&t()}function r(o){o.key==="Escape"&&t()}return document.addEventListener("mousedown",s),document.addEventListener("keydown",r,!1),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",r,!1)}},[e,t])}function eE(e){const t=g.useRef(null),s=e.onAlert;return Jw(t,s),T.jsx("div",{ref:t,style:{width:"100%"},children:e.children})}const tE=e=>{var u;const{stateProp:t}=e,[s,r]=g.useState((u=e.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 ue(h),n(!0))}catch(f){a(f.message)}}d(t)},[t]),g.useEffect(()=>{const d=Y(()=>{t&&o&&r(t.value)});return()=>{d()}},[o,t]),[s,{ready:o,error:i}]},Rd=()=>{const[e,t]=g.useState(!1),[s,r]=g.useState([]),o=Dt.type,n=Z({modelId:o,modelType:Dt.type,options:{}});return g.useEffect(()=>{const i=Y(()=>{var a,c;t(((a=n.model)==null?void 0:a.isStorageInserted)??!1),r(((c=n.model)==null?void 0:c.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:e,devices:s}};function sE(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Rd();return T.jsx(o,{...r,children:T.jsx(e,{...t,storageDeviceContainer:s})})}}const go=m.createLogger({name:"use-timer"}),rE=({timerName:e,onTimerExpired:t,onTimerTick:s,timerEventActions:r,autoStart:o})=>{const n=dd.getTimer(e);g.useEffect(()=>{if(!n){console.warn(`Timer with name ${e} does not exist.`);return}const u=$(Jn,d=>{const{name:h,action:f,remainingTime:p}=d==null?void 0:d.body;h===e&&(f===ti?t({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,t,r,e,n]),g.useEffect(()=>{if(!n||!s)return;const u=`${ei}/${e}`,d=$(u,h=>{const{name:f,remainingTime:p}=h==null?void 0:h.body;f===e&&s({name:f,remainingTime:p,timer:n})});return()=>{d.unsubscribe()}},[s,e,n]);const i=g.useCallback(()=>{n?n.start():go.warn(`Timer with name ${e} does not exist.`)},[n,e]),a=g.useCallback(()=>{n?n.reset():go.warn(`Timer with name ${e} does not exist.`)},[n,e]),c=g.useCallback(()=>{n?n.pause():go.warn(`Timer with name ${e} does not exist.`)},[n,e]);return{timer:n,start:i,reset:a,pause:c}},oE=e=>{const t=/[\\^$.*+?()[\]{}|]/g;return RegExp(t.source).test(e)?e.replace(t,"\\$&"):e},nE=e=>e instanceof RegExp,iE=e=>typeof e=="string",aE=(e,t,s)=>{if(e===""||t==="")return e;let r=t;nE(r)||(r=new RegExp("("+oE(r)+")","gi"));const o=e.split(r);for(let n=1,i=o.length;n<i;n+=2)o[n]=s(o[n],n);return o},kd=(e,t,s)=>{let r=e;return Array.isArray(r)||(r=[r]),r.flatMap(o=>iE(o)?aE(o,t,s):o)};function cE(e,t){let s=e;return Object.entries(t).forEach(([r,o])=>{const n=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=kd(s,n,(i,a)=>o.type==="br"?T.jsx("br",{}):g.cloneElement(o,{key:`${r}-${a}`},i))}),s}const lE=e=>{const{i18nKey:t,t:s,defaults:r,components:o,values:n={},context:i}=e,a=s(t,{defaultValue:r,data:n,context:i,returnObjects:!0}),c=cE(a,o||{});return T.jsx("span",{className:e.className,children:c})},pt=new Map;function uE(e,t){if(pt.has(e)){const s=pt.get(e);if(s.status==="finished")return s.result;throw s.promise}else{const s=t().then(o=>{pt.set(e,{status:"finished",result:o})},o=>{throw pt.set(e,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw pt.set(e,r),s}}function ko(e,t){return uE(e,t)}const dE=async()=>{const e=await pc(ke.type);return await ue(e.model),e.model},hE=async(e,t,s)=>{const r=e.resolveNamespace(t);await ue(r);for(const o of s){const n=e.resolveNamespace(o);await ue(n),pt.set(o,{status:"finished",result:n})}return r},fE=(e,t)=>{const s=[e].flat(),[r,...o]=s,n=ko(ke.type,dE),i=s.join("__"),a=ko(i,()=>hE(n,r,o)),c=g.useMemo(()=>({exists:d=>{const h=t!=null&&t.keyPrefix?`${t.keyPrefix}.${d}`:d;return a?a.exists(h):!1}}),[t==null?void 0:t.keyPrefix,a]);return{t:g.useCallback((d,h)=>{const f=t!=null&&t.keyPrefix?`${t.keyPrefix}.${d}`:d;return a?a.resolveKey(f,h):(m.debug(`Translation model ${e} not ready for key: ${f}`),f)},[t==null?void 0:t.keyPrefix,e,a]),i18n:c}},Ld=()=>{const e=ke.type;return Z({modelId:e,modelType:ke.type,options:{}})};function pE(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Ld();return T.jsx(o,{...r,children:T.jsx(e,{...t,translationContainer:s})})}}const gE=e=>Z({modelId:e,modelType:Es.type}),ci=()=>Z({modelId:St.type,modelType:St.type,options:{}}),mE=({troubleType:e,condition:t})=>{const{model:s}=ci(),[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=(e?s==null?void 0:s.troubles.getIndexByKey("byType",e):s==null?void 0:s.troubles.data)||[],d=t?u.filter(t):u;o(d.length>0),i(d)}),[t,s,e]),[r,a,n.length>0?n[0]:void 0,n]};function yE(e){return t=>{const{model:s,status:r,KosModelLoader:o}=ci();return T.jsx(o,{...r,children:T.jsx(e,{...t,troubleContainer:s})})}}const Fd=()=>{const e=Os.type,t=Z({modelId:e,modelType:Os.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=t.model)==null?void 0:u.isUsbInserted)??!1),n(((d=t.model)==null?void 0:d.hasAvailableUpdates)??!1),a(((h=t.model)==null?void 0:h.data)??[])});return()=>{c()}},[t.model]),{...t,inserted:s,updateAvailable:o,updates:i}};function bE(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Fd();return T.jsx(o,{...r,children:T.jsx(e,{...t,usbUpdateContainer:s})})}}const vE=({path:e,propKey:t})=>{const{status:s}=Z({modelType:ps.type,modelId:e,options:{path:e}}),[r,o]=g.useState(!1),[n,i]=g.useState(),[a,c]=g.useState(""),[u,d]=g.useState(),h=f=>{n&&t&&n.updateProperty(t,f)};return g.useEffect(()=>{var f;s.model&&i(s.model),s.model&&t&&((f=s.model)!=null&&f.props.has(t)?c(s.model.props[t]):d(`property ${t} not found`)),s.ready&&o(s.ready)},[s.ready,s.model,t]),g.useEffect(()=>{t&&E.autorun(()=>{const f=n==null?void 0:n.props[t];c(f||"")})},[n,t]),{config:n,ready:r,value:a,error:u,updateValue:h}},wE=(e,t)=>{switch(t.type){case"UPDATE":return t.payload;default:return e}},Nd=({configProperty:e,optionsTransformer:t})=>{const[s,r]=g.useState(!1),[o,n]=g.useState(""),[i,a]=g.useReducer(wE,{value:String(e==null?void 0:e.value),displayValue:e==null?void 0:e.displayValue,significantValue:e==null?void 0:e.significantValue,unit:e==null?void 0:e.unit,options:e==null?void 0:e.options,mappedOptions:[],updateProperty:e==null?void 0:e.updateProperty,displayOptions:e==null?void 0:e.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&&(e==null||e.updateProperty(d))},[e]);return g.useEffect(()=>{async function u(d){try{d&&(await ue(d),r(!0))}catch(h){n(h.message)}}u(e)},[e]),g.useEffect(()=>{const u=Y(()=>{if(e&&s){let d=[];t&&(d=t(e.options)),a({type:"UPDATE",payload:{value:String(e.value),displayValue:e.displayValue,significantValue:e.significantValue,unit:e.unit,options:e.options,mappedOptions:d,updateProperty:e.updateProperty,displayOptions:e==null?void 0:e.displayOptions}})}});return()=>{u()}},[e,t,s]),{...i,configSelectProps:{onChange:c,value:i.value,options:t?i.mappedOptions||[]:i.options||[]},ready:s,error:o}};function EE(e,t){const s=t??new Date().getFullYear(),r=[31,28,31,30,31,30,31,31,30,31,30,31];return e===1&&(s%4===0&&s%100!==0||s%400===0)?29:r[e]??0}function ME(e,t){return new Date(e,t,0).getDate()}function Ud(e,t){const s=EE(t,e),r=[];for(let o=1;o<=s;o++)r.push(o);return r}function jd(){return[...Array(12).keys()].map(t=>new Date(0,t).getMonth())}function Bd(e=[2018,2028]){const t=[];for(let s=e[0];s<=e[1];s++)t.push(s);return t}function Kd(e,t=[2018,2028]){const s=Bd(t);return e==="long"?s:s.map(r=>Number(r.toString().substring(2)))}function li(e="numeric",t="en-US"){const s=new Intl.DateTimeFormat(t,{month:e,timeZone:"UTC"}).format;return[...Array(12).keys()].map(r=>s(new Date(Date.UTC(0,r,1))))}function TE({locale:e="en-US",year:t,month:s,day:r,formatOptions:o={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:n}){const i=s-1,a=new Date(t,i,r),c=new Intl.DateTimeFormat(e,{month:o.month}).format(a),u=new Intl.DateTimeFormat(e,{year:o.year}).format(a),d=new Intl.DateTimeFormat(e,{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(e,o).format(a)}function ye(e){return e.toString().length===2?new Date(Date.parse(`01 Jan 20${e}`)).getFullYear():e}function _E(e){return typeof e=="string"?new Date(Date.parse(`01 ${e.substring(0,3)} 2023`)).getMonth()+1:e}function Hd(e,t,s){const r=ye(t),o=new Date(r,e,1).getDay(),n=new Date(r,e+1,0).getDate();return[...Array(42).keys()].map(a=>a<o||a>n+o-1?{label:"",value:0,disabled:!0}:s[a-o])}function ss(e,t,s){const r=t-1,o=new Date(e,r,s);return new Date(o).getMonth()===r&&new Date(o).getDate()===s}function rs(e,t){return new Date(e,t,0).getDate()}function zd(e="en-US",t="short"){const s=new Intl.DateTimeFormat(e,{weekday:t}).format;return[...Array(7).keys()].map(r=>s(new Date(Date.UTC(2021,5,r))))}function Gd({locale:e="en-US",year:t=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=ui(n,r),u=Vd(n,r,e),d=Yd(i,e),h=qd(i,e),f=di(t,s),p=Wd(t,s,e,o),b=Xd(s,t,p),w=Qd(e,a);return{daysArray:f,monthsArray:d,yearsArray:c,yearsOptionsArray:u,monthsOptionsArray:h,daysOptionsArray:p,calendarDayArray:b,dayNamesArray:w}}function ui(e="long",t=[2018,2028]){return g.useMemo(()=>Kd(e,t),[e,t])}function Vd(e="long",t=[2018,2028],s="en-US"){const r=ui(e,t);return g.useMemo(()=>r.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,r])}function Yd(e,t="en-US"){return g.useMemo(()=>li(e,t),[e,t])}function qd(e,t="en-US"){const s=g.useMemo(()=>jd(),[]),r=g.useMemo(()=>li(e,t),[e,t]);return g.useMemo(()=>[...Array(12).keys()].map(n=>({label:r[n],value:Number(s[n])})),[r,s])}function di(e,t){const s=ye(e);return g.useMemo(()=>Ud(s,t),[t,s])}const OE=(e,t,s,r=[])=>{const o=new Date(e,t,s).getDay();return r.length>0&&r.includes(o)};function Wd(e,t,s="en-US",r=[]){const o=di(e,t);return g.useMemo(()=>o.map(i=>({label:i.toLocaleString(s),value:i,disabled:OE(e,t,i,r)})),[r,s,t,o,e])}function Qd(e="en-US",t="short"){return g.useMemo(()=>zd(e,t),[e,t])}function Zd({year:e=new Date().getFullYear(),month:t=new Date().getMonth(),day:s=new Date().getDate(),formatString:r}){const o=t,n=new Date(e,o,s);return{formattedDate:je.format(n,r)}}function Xd(e,t,s){return g.useMemo(()=>Hd(e,t,s),[e,t,s])}var Jd=(e=>(e.MMDDYY="MMDDYY",e.DDMMYY="DDMMYY",e.YYMMDD="YYMMDD",e.YYDDMM="YYDDMM",e))(Jd||{});function IE({locale:e="en-US",date:{year:t=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(t),[f,p]=g.useState(c),[b,w]=g.useState(s),[M,_]=g.useState(r);g.useEffect(()=>{h(t)},[t]),g.useEffect(()=>{w(s)},[s]),g.useEffect(()=>{_(r)},[r]);const{yearsArray:F,yearsOptionsArray:Q,monthsArray:D,monthsOptionsArray:O,daysArray:W,daysOptionsArray:B,calendarDayArray:J,dayNamesArray:Ue}=Gd({locale:e,year:d,yearRange:f,month:b,formatOptions:{yearFormat:o,monthFormat:n,dayFormat:i},daysOfWeekFilter:u}),{formattedDate:$e}=Zd({year:d,month:b,day:M,formatString:a});return{dateActions:{setYear:h,setYearRange:p,setMonth:w,setDay:_,nextMonth:()=>{const se=b<11?ye(d):ye(d+1),ce=b<11?b+1:0;if(!ss(se,ce,M)){const Ve=rs(se,ce);_(Ve)}ce===0&&h(se),w(ce)},previousMonth:()=>{const se=ye(b===0?d-1:d),ce=b===0?11:b-1;if(!ss(se,ce,M)){const Ve=rs(se,ce);_(Ve)}ce===11&&h(se),w(ce)},nextYear:()=>{const se=d<f[1]?d+1:f[0],ce=ye(se);if(ss(ce,b,M))h(se);else{const Ve=rs(ye(d+1),b);_(Ve),h(se)}},previousYear:()=>{const se=d>f[0]?d-1:f[0],ce=ye(se);if(ss(ce,b,M))h(se);else{const Ve=rs(ye(d-1),b);_(Ve),h(se)}}},dateState:{year:d,yearRange:f,month:b,day:M,yearsArray:F,yearsOptionsArray:Q,monthsArray:D,monthsOptionsArray:O,daysArray:W,daysOptionsArray:B,calendarDayNames:Ue,calendarDayArray:J,formattedDate:$e}}}function eh({date:e=new Date,dateFormat:t,timeFormat:s,options:r={}}){const[o,n]=g.useState("Formatting Time..."),[i,a]=g.useState("Formatting Date..."),c=!!r.ignoreDateFormat,{model:u,ready:d}=Z({modelId:re.type,modelType:re.type,options:{}}),h=typeof e=="string"?je.parseISO(e):e;return g.useEffect(()=>{c?a(""):t?a(je.format(h,t)):d&&a(je.format(h,u!=null&&u.selectedDateFormat?u==null?void 0:u.selectedDateFormat:""))},[c,e,t,h,u,d]),g.useEffect(()=>{s?n(je.format(h,s)):d&&n(je.format(h,u!=null&&u.selectedTimeFormat?u==null?void 0:u.selectedTimeFormat:""))},[e,s,h,u,d]),{formattedDate:i,formattedTime:o}}const th=({secondsFromMidnight:e=0})=>{const[t,s]=g.useState(0),[r,o]=g.useState(0),[n,i]=g.useState(0),[a,c]=g.useState(new Date),{formattedTime:u}=eh({date:a,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const d=Number(e),h=Math.floor(d/3600),f=Math.floor(d%3600/60),p=d%60;s(h),o(f),i(p);const b=new Date;b.setHours(0,0,0,0);const w=new Date(b.getTime()+d*1e3);c(new Date(w))},[e]),{hours:t,minutes:r,seconds:n,formattedTime:u,timeActions:{setHours:s,setMinutes:o,setSeconds:i}}},SE=({configProperty:e})=>{const{value:t}=Nd({configProperty:e}),s=parseInt(t||"0",10),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}=th({secondsFromMidnight:s}),c=g.useRef();return g.useEffect(()=>{const u=r*3600+o*60+n;return c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{e&&e.updateProperty(u.toString())},100),()=>{c.current&&clearTimeout(c.current)}},[e,r,o,n]),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}};function $E(e,t={}){const{intervalMs:s=5*60*1e3,immediate:r=!0}=t;g.useEffect(()=>{const o=()=>{try{e({__warmup:!0})}catch{}};r&&("requestIdleCallback"in window?requestIdleCallback(o):setTimeout(o,1));const n=s?setInterval(o,s):null;return()=>{n&&clearInterval(n)}},[e,s,r])}const CE=e=>T.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),DE=(e=CE)=>{const[t,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const c=Y(()=>{s((n==null?void 0:n.dateFormatOptions.map(e))||[])});return()=>{c()}},[n,i,e]),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:t}}},xE=e=>T.jsx("option",{title:e,value:e,children:e},e),sh="kos:service:region:settings",rh="timeZone",AE=`${sh}-${rh}`,PE=(e=xE)=>{const[t,s]=g.useState([]),[r,o]=g.useState(""),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}}),a=rt.factory(AE)({path:sh,attribute:rh});g.useEffect(()=>{const u=Y(()=>{s((n==null?void 0:n.timeZones.map(e))||[]),n!=null&&n.timeZones.length&&Ro(n==null?void 0:n.timeZones[0])});return()=>{u()}},[n,i,e]),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&&Ro(d)},[]);return{options:t,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:t}}},oh="kos:service:region",nh="regionId",RE=`${oh}-${nh}`,kE=e=>T.jsx("option",{title:e,value:e,children:e},e),ih=(e=kE)=>{const[t,s]=g.useState([]),[r,o]=g.useState("factory"),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}}),a=rt.factory(RE)({path:oh,attribute:nh});g.useEffect(()=>{const u=Y(()=>{s((n==null?void 0:n.availableRegions.map(e))||[])});return()=>{u()}},[n,i,e]),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&&ld(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:t}}},LE=e=>T.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),FE=(e=LE)=>{const[t,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const c=Y(()=>{s((n==null?void 0:n.timeFormatOptions.map(e))||[])});return()=>{c()}},[n,i,e]),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:t}}},NE=(e,t)=>g.useMemo(()=>gn(e),t),UE={config:{attributes:!0,childList:!0,subtree:!0}};function jE(e,t,s=UE){const[r,o]=g.useState(null);g.useEffect(()=>{if(!t||typeof t!="function")throw new Error("A valid callback function is required");const n=new MutationObserver(t);o(n)},[t,s,o]),g.useEffect(()=>{if(!r)return()=>{};if(!e)throw new Error("A valid DOM element is required");const{config:n}=s;try{r.observe(e,n)}catch(i){m.error(i)}return()=>{r&&r.disconnect()}},[r,e,s])}const ah={validateStart:function(e){return!0},validateStop:function(e){const t=e.event.currentTarget.getBoundingClientRect(),[s,r]=e.xy;return s<t.left||s>t.right||r<t.top||r>t.bottom}},mo=m.createLogger({name:"usePressGesture",group:"kos-hooks"});function BE({onPressed:e,onRelease:t,intersectionStrategy:s=ah}){const r=g.useRef(!1),o=bh.useGesture({onDragStart:c=>{mo.info("onDragStart",c.type),s.validateStart(c)&&(e&&e(),r.current=!0)},onDrag:c=>{mo.info("onDrag",c.type),r.current&&s.validateStop(c)&&(t&&t(),r.current=!1)},onDragEnd:c=>{mo.info("onDragEnd",c.type),r.current&&t&&(t(),r.current=!1)}}),n=()=>{e&&e(),r.current=!0},i=()=>{r.current&&t&&(t(),r.current=!1)},a=()=>{r.current&&t&&(t(),r.current=!1)};return{dom:o,mesh:()=>({onPointerDown:n,onPointerUp:i,onPointerOut:a})}}const ch=()=>{const[e,t]=g.useState(!1),s=I.getInstance();return g.useEffect(()=>{const r=Y(()=>{s&&s.reloading!==e&&t(s.reloading)});return()=>{r()}},[s,e]),[e]};function lh(e=!1,t="2-digit"){return g.useMemo(()=>{const s=e?12:24;return Array.from({length:s},(r,o)=>{const n=e&&o===0?12:o%s;return{id:o,label:t==="2-digit"?n.toString().padStart(2,"0"):n.toString()}})},[t,e])}function Lo(e,t="2-digit",s=0,r=0){return g.useMemo(()=>Array.from({length:e},(o,n)=>{const i=String(n+s);return{id:n+r,label:t==="2-digit"?i.padStart(2,"0"):i}}),[e,s,r,t])}function uh(e="en-US"){return g.useMemo(()=>["AM","PM"].map(t=>{const s=new Intl.DateTimeFormat(e,{hour:"2-digit",hour12:!0}).formatToParts(new Date().setHours(t==="AM"?0:12))[2].value;return{id:s,label:s}}),[e])}function dh({formatOptions:{hour12:e=!0,hour:t="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=lh(e,t),i=Lo(60,s),a=Lo(60,r),c=uh(o);return{hourOptions:n,minuteOptions:i,secondOptions:a,amPmOptions:c}}function hh(e,t){return je.format(e,t)}function fh({formatOptions:e,initialDate:t=new Date,locale:s="en-US",format:r="HH:mm"}){const[o,n]=g.useState(t),i=g.useCallback(w=>{n(M=>{const _=new Date(M);return _.setHours(Number(w)),_})},[]),a=g.useCallback(w=>{n(M=>{const _=new Date(M);return _.setMinutes(Number(w)),_})},[]),c=g.useCallback(w=>{n(M=>{const _=new Date(M);return _.setSeconds(Number(w)),_})},[]),u=g.useCallback(w=>{const M=new Date(w);n(M)},[]),d=hh(o,r),{hourOptions:h,minuteOptions:f,secondOptions:p,amPmOptions:b}=dh({formatOptions:e,locale:s});return{amPmOptions:b,formattedTime:d,hourOptions:h,minuteOptions:f,secondOptions:p,setHours:i,setMinutes:a,setSeconds:c,setTime:u,time:new Date(o)}}const KE=e=>{const{regionModel:t}=ih(),s=g.useMemo(()=>({hour12:t==null?void 0:t.is12HourTimeFormat}),[t==null?void 0:t.is12HourTimeFormat]);return fh({...e,locale:t==null?void 0:t.regionId,format:t==null?void 0:t.selectedTimeFormat,formatOptions:s})};function HE(e){return t=>{const[s]=ch();return s?T.jsx(bd,{message:"Wait a moment while your project reloads..."}):T.jsx(e,{...t})}}const Ji=m.createLogger({name:"studio-properties-service",group:"Services"}),zE="/api/kos/studio/properties",ph=async e=>{if(Ji.debug("sending GET for studio-properties"),!e)throw Ji.error("connectionId is undefined"),new Error("connectionId is undefined");return await Ne.get(zE,{},{destinationAddress:e,timeout:500})},GE=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:ph},Symbol.toStringTag,{value:"Module"}));var VE=Object.getOwnPropertyDescriptor,YE=(e,t,s,r)=>{for(var o=r>1?void 0:r?VE(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const gh="studio-properties-model",qE="/kos/studio/properties",ea={"kos.studio.tool.legacy":1};let Fo=class{constructor(e,t,s){l(this,"id");l(this,"connectionId");l(this,"unsubscribe",null);l(this,"logger");l(this,"data");this.id=e,this.logger=s.logger,this.data=Te(),this.connectionId=t.connectionId}async init(){this.logger.debug(`initializing studio-properties ${this.id}`)}async load(){this.logger.debug(`loading studio-properties ${this.id}`)}async terminatePropertiesSession(){var e;(e=this.unsubscribe)==null||e.call(this)}async initializePropertiesSession(){this.unsubscribe=wt.getInstance().subscribeTopic({topic:qE,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[e,t]=await ph(this.connectionId);if(e){this.logger.error(`Error loading studio-properties: ${e}`),this.data.setValues(ea);return}if(t){const s=Object.keys(t).reduce((r,o)=>(r[o]=t[o]??o,r),{});this.data.setValues(s??ea),m.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(e){return this.data[e]}createObservableProperty(e){return gn(()=>this.get(e))}};Fo=YE([A(gh)],Fo);const WE=new me({class:Fo,type:gh});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>E.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>E.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>Uo.observer});exports.AuthState=Jc;exports.BrowserKosRouter=il;exports.BrowserRouter=Sn;exports.CanvasDispatcher=Ct;exports.CanvasDispatcherServices=Jb;exports.CanvasRenderer=Gn;exports.CanvasStreamer=Gw;exports.CanvasStreamerBase=Dd;exports.ChildModels=Be;exports.CompanionParentModel=bt;exports.ConfigBean=ps;exports.ContainerAwareSetup=on;exports.CoreExtensionManager=Qv;exports.CoreModels=Xn;exports.CreateModelTranslationsContext=Od;exports.CreateModelTranslationsProvider=Tw;exports.DateDisplayFormat=Jd;exports.DateHelpers=Rh;exports.DependencyLifecycle=H;exports.DependencyModels=k;exports.Device=Tr;exports.DeviceServices=Ev;exports.DomIntersectionStrategy=ah;exports.EVENT_KOS_MODEL_READY=Ho;exports.EVENT_TROUBLE_ADDED=bg;exports.EVENT_TROUBLE_REMOVED=vg;exports.EXTENSION_CANVAS_RENDERER=te;exports.EXTENSION_FEATURE_FLAG_RESOLVER=Qa;exports.EXTENSION_TROUBLE_DATA_MAPPER=ur;exports.EXTENSION_TROUBLE_MAPPER=Rs;exports.ErrorBoundaryWithFallback=vd;exports.EventBus=Mh;exports.EventBusFunctional=_h;exports.EventBusState=Ih;exports.ExtensionManager=S;exports.FUTURE_CONTAINER_MODEL_TYPE=Rl;exports.FUTURE_MODEL_TYPE=_l;exports.FUTURE_NOT_ASSIGNED=yn;exports.FeatureFlagService=Za;exports.FetchError=pe;exports.FutureAliases=as;exports.FutureContainerFactory=He;exports.FutureContainerModel=Ll;exports.FutureContainerSetup=en;exports.FutureEndState=Ke;exports.FutureFactory=Lt;exports.FutureHandler=Rr;exports.FutureManager=Je;exports.FutureModel=Dl;exports.FutureService=os;exports.HEADER_CACHE_CONTROL=ia;exports.HEADER_CONTENT_TYPE=na;exports.HEADER_DESTINATION_ADDR=Le;exports.HEADER_FOS_REQUEST_ID=aa;exports.HEADER_METHOD=Sr;exports.HEADER_ORDERED=Bo;exports.HEADER_REQUEST_ID=Is;exports.HEADER_REQUEST_TYPE=Oe;exports.HEADER_RESPONSE_ID=$r;exports.HEADER_SOURCE_ADDR=oa;exports.HEADER_TOPIC=ra;exports.HEADER_URL=At;exports.HEADER_WORK_TRACKER=Ko;exports.HttpRouteHandlers=xe;exports.KOS_MODEL_ID=Xs;exports.KeyValue=Dn;exports.KeyValueServices=fm;exports.Kos=ie;exports.KosConfigPropertySpec=rt;exports.KosContainerIndex=nn;exports.KosContextBean=ol;exports.KosContextManager=V;exports.KosCore=I;exports.KosCoreModelPropertyMapper=be;exports.KosDataContainer=pn;exports.KosDependencyTypes=lf;exports.KosExpressionEvaluator=Yl;exports.KosExtensionUtils=Nh;exports.KosFeatureFlags=Xa;exports.KosFetchMethods=Lc;exports.KosGlobalConfig=Xo;exports.KosHttpRouteManager=un;exports.KosLog=m;exports.KosLogManager=Ql;exports.KosLogManagerServices=Ey;exports.KosMockEvents=ua;exports.KosModel=Wc;exports.KosModelCollectionProvider=bw;exports.KosModelContainer=Se;exports.KosModelContext=Wr;exports.KosModelEvents=R;exports.KosModelFactory=cs;exports.KosModelLoader=Td;exports.KosModelLoaderDisplay=_d;exports.KosModelManager=Xc;exports.KosModelProvider=wd;exports.KosModelRegistrationFactory=me;exports.KosModelRegistry=Po;exports.KosModelState=v;exports.KosModelSymbol=Jo;exports.KosModelVisitor=Vp;exports.KosObservableData=hc;exports.KosRegistration=dg;exports.KosSingletonRegistration=hg;exports.KosTime=ar;exports.KosTimeContext=oi;exports.KosTimeProvider=xw;exports.KosTimeServices=$y;exports.KosTimer=ud;exports.KosToken=nl;exports.KosTranslationProvider=Nw;exports.KosTranslations=Pu;exports.KosWSTransportStatus=qc;exports.KosWsEvents=Ss;exports.LOADER_FEATURE_FLAG=Qh;exports.LOGIN_HOST=ca;exports.LOGIN_URL=vh;exports.LoadingMessage=bd;exports.LogBlock=ws;exports.LogBlockContainer=Gr;exports.LogConfig=is;exports.LogStream=hs;exports.LogStreamContainer=Ps;exports.LogStreamServices=Uy;exports.LoggerSetup=rn;exports.MODEL_DELETION_DELAY=Zc;exports.MiddlewareChain=tl;exports.ModelEffects=Ze;exports.MultipleFutureContainerSetup=tn;exports.MultipleFutureHandler=uc;exports.NestedModelContext=Qr;exports.NetworkInterface=qn;exports.NetworkInterfaceContainer=Ts;exports.NetworkInterfaceServices=Dv;exports.ObservableData=Te;exports.Ota=hr;exports.OutsideAlerter=eE;exports.PLUGIN_EXTENSION_NAME=Uh;exports.PORT=la;exports.PROFILE_LOG_DEBUG=ja;exports.PROFILE_LOG_INFO=Ba;exports.PROFILE_RELAX_STORE_VALIDATION=Bh;exports.PROFILE_TOOLS_PREVIEW=Ua;exports.ParentModel=ns;exports.PluginExtensionManager=jh;exports.ProgressBar=pw;exports.ReferenceConfig=Vs;exports.RegionInfo=re;exports.RegionServices=Cg;exports.RegistrationManager=x;exports.Registry=Wv;exports.STATUS=jo;exports.ServiceFactory=oe;exports.SingletonKosModelRegistrationFactory=Me;exports.SoftwareInfo=fr;exports.SoftwareInfoContext=ii;exports.SoftwareInfoProvider=Rw;exports.SoftwareInfoServices=Eb;exports.StateBean=Ms;exports.StateBeanServices=Ib;exports.StateProp=Bn;exports.StatePropServices=Lb;exports.StorageDevice=Or;exports.StorageDeviceContainer=Dt;exports.StorageDeviceServices=kv;exports.StudioProperties=WE;exports.StudioPropertiesServices=GE;exports.SubscriptionHandlers=ee;exports.TIMER_END=ti;exports.TIMER_EVENT=Jn;exports.TOPIC_TIMER_TICK_EVENT=ei;exports.TimerManager=dd;exports.TokenContext=Cd;exports.TokenProvider=Lw;exports.Topics=ds;exports.Trans=lE;exports.TransitionMap=Ys;exports.Transitions=cn;exports.Translation=mr;exports.TranslationContainer=ke;exports.TranslationContainerContext=ai;exports.TranslationContext=Vb;exports.TransportFactory=Mo;exports.Trouble=Es;exports.TroubleAwareSetup=sn;exports.TroubleContainer=St;exports.TroubleServices=ob;exports.Troubles=fe;exports.UsbUpdate=Zn;exports.UsbUpdateContainer=Os;exports.UsbUpdateServices=Hv;exports.WS_EVENT_TYPE=Ru;exports.WebSocketEvents=us;exports.WebSocketTransport=wt;exports.WsEventFactory=Hn;exports.acceptOrgInvitation=yd;exports.addDaysToDate=xa;exports.addFuture=Il;exports.addMonthsToDate=Da;exports.api=xl;exports.applyMixins=$h;exports.arraysEqual=Ch;exports.buildConfigBeanModel=Mg;exports.buildFuture=In;exports.buildFutureModel=$l;exports.cancelFuture=Sl;exports.checkAppsStarted=mg;exports.convert=Mn;exports.convertFileSizeRaw=Sh;exports.convertWithUnits=kg;exports.createBaseMessage=Uc;exports.createBroadcastMessageResponse=Hc;exports.createCancellablePromise=cw;exports.createClient=hn;exports.createFosBaseMessage=Nc;exports.createHeaders=Gt;exports.createKosHtpMessageResponse=zc;exports.createKosMessage=Bc;exports.createKosMessageResponse=Gc;exports.createMessageBody=Ge;exports.createModelDependency=Dc;exports.createOptionKey=sf;exports.createPropKey=st;exports.createReadableStream=Vt;exports.createStudioMessage=Fc;exports.createStudioMessageRequest=jc;exports.createStudioMessageResponse=Kc;exports.debounce=Fa;exports.del=nc;exports.deleteFuture=Ol;exports.destroyKosModel=Xe;exports.evaluateScopes=pl;exports.executeChildrenModelLifecycle=Pc;exports.executeDependentModelLifecycle=zt;exports.executeListLifecycle=Ac;exports.extractTrailingWildcard=wc;exports.fetchModel=Ww;exports.findModel=Ef;exports.findModels=gc;exports.formatDate=Ra;exports.formatDateSince=Ca;exports.formatDateTime=La;exports.formatTime=ka;exports.get=oc;exports.getAllKosCompanionModels=mc;exports.getCalendarMonthArray=Hd;exports.getConfigBean=fl;exports.getDayStrings=zd;exports.getDays=ME;exports.getDaysArray=Ud;exports.getDaysInMonth=Zo;exports.getDependenciesByLifecycle=xc;exports.getFormattedDate=TE;exports.getFormattedMonth=_E;exports.getFormattedMonthsArray=li;exports.getFormattedYear=ye;exports.getFormattedYearsArray=Kd;exports.getFutures=Xg;exports.getHttpRouteHandlers=ic;exports.getKosCompanionModel=Mf;exports.getKosLocalizationDescriptor=$u;exports.getKosMessageLogging=Ga;exports.getKosModel=pc;exports.getKosModelSync=_e;exports.getKosModelType=wf;exports.getKosSessionKey=rl;exports.getLastDayOfMonth=rs;exports.getLocalizationDescriptor=Nb;exports.getLogLevel=za;exports.getLogMessageToStudio=Va;exports.getMessageBody=Eo;exports.getMonthsArray=jd;exports.getObservableCompanions=Tf;exports.getQueryParams=ge;exports.getStartedApps=yg;exports.getTranslations=Su;exports.getYearsArray=Bd;exports.hasDecimals=dl;exports.hasHttpRouteHandlers=er;exports.hasKosProfile=yo;exports.hasTrailingWildcard=Ec;exports.hslStringToHex=ec;exports.hslToHex=Ja;exports.httpDelete=df;exports.initKosProvider=Ow;exports.isBoolean=vn;exports.isKosCompanionTypeFactory=Qc;exports.isKosDataModel=ls;exports.isKosLoggingEnabled=zh;exports.isKosModel=Ee;exports.isKosModelContainer=ln;exports.isKosModelReady=tr;exports.isLeapYear=Qo;exports.isLocalRefId=ag;exports.isNumber=kr;exports.isPrintable=Gf;exports.isTroubleAware=Yb;exports.isValidDate=ss;exports.kosAction=X;exports.kosAutoEffect=Y;exports.kosChild=Ie;exports.kosCompanion=of;exports.kosComputed=gn;exports.kosConfigBean=Lr;exports.kosConfigProperty=Gg;exports.kosContainerAware=rc;exports.kosContext=nf;exports.kosDependency=Pt;exports.kosEffect=ll;exports.kosFuture=si;exports.kosFutureAware=af;exports.kosLogger=hf;exports.kosLoggerAware=cc;exports.kosModel=A;exports.kosModelEffect=lc;exports.kosMultipleFutureAware=cf;exports.kosObservable=mn;exports.kosParentAware=Ar;exports.kosReference=ff;exports.kosStateBean=sw;exports.kosStateProp=rw;exports.kosSubscribe=Ff;exports.kosTopicHandler=U;exports.kosTroubleAware=pf;exports.kosWhen=_o;exports.login=pd;exports.mapConfigBeanModelToDto=bl;exports.mapDataToModel=bo;exports.mapDtoToConfigBeanModel=ml;exports.mapDtoToFutureModel=On;exports.mapDtoToFutureOptions=_n;exports.mapUpdateDtoToConfigBeanModel=yl;exports.modelEventTopicFactory=Mc;exports.modelFactory=Rt;exports.modelTypeEventTopicFactory=Tc;exports.modifyConfigBean=hl;exports.modifyFuture=Jg;exports.pairedClientHeartbeat=Xp;exports.pipe=sl;exports.post=Cs;exports.preloadKosModel=If;exports.processId=Ph;exports.processMiddleware=Wp;exports.put=uf;exports.registerCompanionModel=Of;exports.registerCoreModels=id;exports.registerExtensionPoint=$s;exports.registerHttpRoutes=op;exports.registerKosModel=bc;exports.registerLegacyModel=yc;exports.resetKosModel=vf;exports.resetPassword=md;exports.resolveBaseUrl=el;exports.resolveChild=Rc;exports.resolveContainerDeltas=Dh;exports.resolveItemListDeltas=Ah;exports.resolveKosCompanion=vo;exports.resolveKosContext=ug;exports.resolveKosProfiles=Ha;exports.resolveListDeltas=xh;exports.resolveServiceUrl=ae;exports.resolveVariable=tc;exports.retryWithExponentialBackoff=eg;exports.sendAsyncIntent=pg;exports.sendBroadcastMessage=dp;exports.sendIntent=fg;exports.sendKosHttpMessageResponse=Yc;exports.sendKosMessage=cp;exports.sendKosMessageResponse=Vc;exports.sendRequest=cg;exports.sendStudioMessage=up;exports.sendStudioMessageRequest=lp;exports.startPasswordReset=gd;exports.stringComponentInsert=kd;exports.studioAcceptOrgInvitation=aw;exports.studioLogin=ow;exports.studioResetPassword=iw;exports.studioStartPasswordReset=nw;exports.subscribeStore=Zv;exports.syncPublish=lg;exports.transitionToActive=Ic;exports.transitionToInit=Cc;exports.transitionToLoad=$c;exports.transitionToReady=Sc;exports.transitionToUnload=zf;exports.troubleByTypeReducer=dc;exports.troubleDataFactory=yu;exports.unloadKosModel=bf;exports.updateCompanionModelRegistration=Zp;exports.updateModelRegistration=Qp;exports.updateRegion=ld;exports.updateTimeZone=Ro;exports.useAmPmValues=uh;exports.useCalendarDayArray=Xd;exports.useConfigBean=vE;exports.useConfigProperty=Nd;exports.useContextModel=mw;exports.useContextModelHierarchy=Md;exports.useDateArrays=Gd;exports.useDateProps=IE;exports.useDateRelativeConfig=SE;exports.useDateRelativeData=th;exports.useDayNames=Qd;exports.useDayOptions=Wd;exports.useDays=di;exports.useDevice=xd;exports.useFormattedDate=Zd;exports.useFormattedTime=hh;exports.useFunctionWarmup=$E;exports.useHourValues=lh;exports.useKosCore=Sd;exports.useKosDateFormats=DE;exports.useKosModel=Z;exports.useKosRegions=ih;exports.useKosTime=ri;exports.useKosTimeContext=Aw;exports.useKosTimeFormats=FE;exports.useKosTimeZones=PE;exports.useKosTranslation=fE;exports.useKosTranslationContext=Uw;exports.useLocalComputed=NE;exports.useModelFromHierarchy=ww;exports.useMonths=Yd;exports.useMonthsOptions=qd;exports.useMutationObserver=jE;exports.useNetworkInterfaceContainer=Ad;exports.useOta=Pd;exports.usePressGesture=BE;exports.useProjectReload=ch;exports.useRegionTimeProps=KE;exports.useRegionalTimeDate=eh;exports.useSoftwareInfo=ni;exports.useSoftwareInfoContext=kw;exports.useStateProperty=tE;exports.useStorageDeviceContainer=Rd;exports.useSuspenseData=ko;exports.useTimeOptions=dh;exports.useTimeProps=fh;exports.useTimeValues=Lo;exports.useTimer=rE;exports.useTranslationContainer=Ld;exports.useTroubleContainerModel=ci;exports.useTroubleModel=gE;exports.useTroublePresence=mE;exports.useUsbUpdateContainer=Fd;exports.useYears=ui;exports.useYearsOptions=Vd;exports.uuid=tt;exports.variableToHex=Zh;exports.waitForAppToStart=gg;exports.waitForAppsToStart=cl;exports.waitForRequest=fn;exports.whenReady=ue;exports.withDevice=qw;exports.withKosTime=Qw;exports.withNetworkInterfaceContainer=Zw;exports.withOta=Xw;exports.withProjectReloading=HE;exports.withSoftwareInfo=Pw;exports.withStorageDeviceContainer=sE;exports.withTranslationContainer=pE;exports.withTroubleContainer=yE;exports.withUsbUpdateContainer=bE;exports.wrapPromise=qo;
|
|
197
|
+
`,Ud=()=>{const t=Ir.type;return Z({modelId:t,modelType:Ir.type,options:{}})};function CE(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Ud();return T.jsx(o,{...r,children:T.jsx(t,{...e,device:s})})}}function DE(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 Xo(r)}function xE(t){return e=>{const{model:s,status:r,KosModelLoader:o}=ci();return T.jsx(o,{...r,children:T.jsx(t,{...e,kosTime:s})})}}const jd=()=>{const t=Is.type;return Z({modelId:t,modelType:Is.type,options:{}})};function AE(t){return e=>{const{model:s,status:r,KosModelLoader:o}=jd();return T.jsx(o,{...r,children:T.jsx(t,{...e,networkInterfaceContainer:s})})}}const Bd=()=>{const t=mr.type;return Z({modelId:t,modelType:mr.type,options:{}})};function RE(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Bd();return T.jsx(o,{...r,children:T.jsx(t,{...e,oTA:s})})}}function PE(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 kE(t){const e=g.useRef(null),s=t.onAlert;return PE(e,s),T.jsx("div",{ref:e,style:{width:"100%"},children:t.children})}const LE=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 de(h),n(!0))}catch(f){a(f.message)}}d(e)},[e]),g.useEffect(()=>{const d=W(()=>{e&&o&&r(e.value)});return()=>{d()}},[o,e]),[s,{ready:o,error:i}]},Kd=()=>{const[t,e]=g.useState(!1),[s,r]=g.useState([]),o=At.type,n=Z({modelId:o,modelType:At.type,options:{}});return g.useEffect(()=>{const i=W(()=>{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 FE(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Kd();return T.jsx(o,{...r,children:T.jsx(t,{...e,storageDeviceContainer:s})})}}const vo=m.createLogger({name:"use-timer"}),NE=({timerName:t,onTimerExpired:e,onTimerTick:s,timerEventActions:r,autoStart:o})=>{const n=vd.getTimer(t);g.useEffect(()=>{if(!n){console.warn(`Timer with name ${t} does not exist.`);return}const u=C(oi,d=>{const{name:h,action:f,remainingTime:p}=d==null?void 0:d.body;h===t&&(f===ii?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=`${ni}/${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():vo.warn(`Timer with name ${t} does not exist.`)},[n,t]),a=g.useCallback(()=>{n?n.reset():vo.warn(`Timer with name ${t} does not exist.`)},[n,t]),c=g.useCallback(()=>{n?n.pause():vo.warn(`Timer with name ${t} does not exist.`)},[n,t]);return{timer:n,start:i,reset:a,pause:c}},UE=t=>{const e=/[\\^$.*+?()[\]{}|]/g;return RegExp(e.source).test(t)?t.replace(e,"\\$&"):t},jE=t=>t instanceof RegExp,BE=t=>typeof t=="string",KE=(t,e,s)=>{if(t===""||e==="")return t;let r=e;jE(r)||(r=new RegExp("("+UE(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},Hd=(t,e,s)=>{let r=t;return Array.isArray(r)||(r=[r]),r.flatMap(o=>BE(o)?KE(o,e,s):o)};function HE(t,e){let s=t;return Object.entries(e).forEach(([r,o])=>{const n=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=Hd(s,n,(i,a)=>o.type==="br"?T.jsx("br",{}):g.cloneElement(o,{key:`${r}-${a}`},i))}),s}const qE=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=HE(a,o||{});return T.jsx("span",{className:t.className,children:c})},yt=new Map;function zE(t,e){if(yt.has(t)){const s=yt.get(t);if(s.status==="finished")return s.result;throw s.promise}else{const s=e().then(o=>{yt.set(t,{status:"finished",result:o})},o=>{throw yt.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw yt.set(t,r),s}}function Uo(t,e){return zE(t,e)}const VE=async()=>{const t=await wc(Fe.type);return await de(t.model),t.model},GE=async(t,e,s)=>{const r=t.resolveNamespace(e);await de(r);for(const o of s){const n=t.resolveNamespace(o);await de(n),yt.set(o,{status:"finished",result:n})}return r},YE=(t,e)=>{const s=[t].flat(),[r,...o]=s,n=Uo(Fe.type,VE),i=s.join("__"),a=Uo(i,()=>GE(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}},qd=()=>{const t=Fe.type;return Z({modelId:t,modelType:Fe.type,options:{}})};function WE(t){return e=>{const{model:s,status:r,KosModelLoader:o}=qd();return T.jsx(o,{...r,children:T.jsx(t,{...e,translationContainer:s})})}}const QE=t=>Z({modelId:t,modelType:Ss.type}),fi=()=>Z({modelId:Ct.type,modelType:Ct.type,options:{}}),ZE=({troubleType:t,condition:e})=>{const{model:s}=fi(),[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(()=>W(()=>{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 XE(t){return e=>{const{model:s,status:r,KosModelLoader:o}=fi();return T.jsx(o,{...r,children:T.jsx(t,{...e,troubleContainer:s})})}}const zd=()=>{const t=Cs.type,e=Z({modelId:t,modelType:Cs.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=W(()=>{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 JE(t){return e=>{const{model:s,status:r,KosModelLoader:o}=zd();return T.jsx(o,{...r,children:T.jsx(t,{...e,usbUpdateContainer:s})})}}const eM=({path:t,propKey:e})=>{const{status:s}=Z({modelType:bs.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}},tM=(t,e)=>{switch(e.type){case"UPDATE":return e.payload;default:return t}},Vd=({configProperty:t,optionsTransformer:e})=>{const[s,r]=g.useState(!1),[o,n]=g.useState(""),[i,a]=g.useReducer(tM,{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 de(d),r(!0))}catch(h){n(h.message)}}u(t)},[t]),g.useEffect(()=>{const u=W(()=>{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 sM(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 rM(t,e){return new Date(t,e,0).getDate()}function Gd(t,e){const s=sM(e,t),r=[];for(let o=1;o<=s;o++)r.push(o);return r}function Yd(){return[...Array(12).keys()].map(e=>new Date(0,e).getMonth())}function Wd(t=[2018,2028]){const e=[];for(let s=t[0];s<=t[1];s++)e.push(s);return e}function Qd(t,e=[2018,2028]){const s=Wd(e);return t==="long"?s:s.map(r=>Number(r.toString().substring(2)))}function pi(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 oM({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 be(t){return t.toString().length===2?new Date(Date.parse(`01 Jan 20${t}`)).getFullYear():t}function nM(t){return typeof t=="string"?new Date(Date.parse(`01 ${t.substring(0,3)} 2023`)).getMonth()+1:t}function Zd(t,e,s){const r=be(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 is(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 as(t,e){return new Date(t,e,0).getDate()}function Xd(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 Jd({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=gi(n,r),u=eh(n,r,t),d=th(i,t),h=sh(i,t),f=mi(e,s),p=rh(e,s,t,o),y=ih(s,e,p),w=oh(t,a);return{daysArray:f,monthsArray:d,yearsArray:c,yearsOptionsArray:u,monthsOptionsArray:h,daysOptionsArray:p,calendarDayArray:y,dayNamesArray:w}}function gi(t="long",e=[2018,2028]){return g.useMemo(()=>Qd(t,e),[t,e])}function eh(t="long",e=[2018,2028],s="en-US"){const r=gi(t,e);return g.useMemo(()=>r.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,r])}function th(t,e="en-US"){return g.useMemo(()=>pi(t,e),[t,e])}function sh(t,e="en-US"){const s=g.useMemo(()=>Yd(),[]),r=g.useMemo(()=>pi(t,e),[t,e]);return g.useMemo(()=>[...Array(12).keys()].map(n=>({label:r[n],value:Number(s[n])})),[r,s])}function mi(t,e){const s=be(t);return g.useMemo(()=>Gd(s,e),[e,s])}const iM=(t,e,s,r=[])=>{const o=new Date(t,e,s).getDay();return r.length>0&&r.includes(o)};function rh(t,e,s="en-US",r=[]){const o=mi(t,e);return g.useMemo(()=>o.map(i=>({label:i.toLocaleString(s),value:i,disabled:iM(t,e,i,r)})),[r,s,e,o,t])}function oh(t="en-US",e="short"){return g.useMemo(()=>Xd(t,e),[t,e])}function nh({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:je.format(n,r)}}function ih(t,e,s){return g.useMemo(()=>Zd(t,e,s),[t,e,s])}var ah=(t=>(t.MMDDYY="MMDDYY",t.DDMMYY="DDMMYY",t.YYMMDD="YYMMDD",t.YYDDMM="YYDDMM",t))(ah||{});function aM({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:k,yearsOptionsArray:R,monthsArray:I,monthsOptionsArray:S,daysArray:H,daysOptionsArray:q,calendarDayArray:J,dayNamesArray:qt}=Jd({locale:t,year:d,yearRange:f,month:y,formatOptions:{yearFormat:o,monthFormat:n,dayFormat:i},daysOfWeekFilter:u}),{formattedDate:zt}=nh({year:d,month:y,day:E,formatString:a});return{dateActions:{setYear:h,setYearRange:p,setMonth:w,setDay:_,nextMonth:()=>{const se=y<11?be(d):be(d+1),ce=y<11?y+1:0;if(!is(se,ce,E)){const Ve=as(se,ce);_(Ve)}ce===0&&h(se),w(ce)},previousMonth:()=>{const se=be(y===0?d-1:d),ce=y===0?11:y-1;if(!is(se,ce,E)){const Ve=as(se,ce);_(Ve)}ce===11&&h(se),w(ce)},nextYear:()=>{const se=d<f[1]?d+1:f[0],ce=be(se);if(is(ce,y,E))h(se);else{const Ve=as(be(d+1),y);_(Ve),h(se)}},previousYear:()=>{const se=d>f[0]?d-1:f[0],ce=be(se);if(is(ce,y,E))h(se);else{const Ve=as(be(d-1),y);_(Ve),h(se)}}},dateState:{year:d,yearRange:f,month:y,day:E,yearsArray:k,yearsOptionsArray:R,monthsArray:I,monthsOptionsArray:S,daysArray:H,daysOptionsArray:q,calendarDayNames:qt,calendarDayArray:J,formattedDate:zt}}}function ch({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}=Z({modelId:re.type,modelType:re.type,options:{}}),h=typeof t=="string"?je.parseISO(t):t;return g.useEffect(()=>{c?a(""):e?a(je.format(h,e)):d&&a(je.format(h,u!=null&&u.selectedDateFormat?u==null?void 0:u.selectedDateFormat:""))},[c,t,e,h,u,d]),g.useEffect(()=>{s?n(je.format(h,s)):d&&n(je.format(h,u!=null&&u.selectedTimeFormat?u==null?void 0:u.selectedTimeFormat:""))},[t,s,h,u,d]),{formattedDate:i,formattedTime:o}}const lh=({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}=ch({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}}},cM=({configProperty:t})=>{const{value:e}=Vd({configProperty:t}),s=parseInt(e||"0",10),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}=lh({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 lM(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 uM=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),dM=(t=uM)=>{const[e,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const c=W(()=>{s((n==null?void 0:n.dateFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),g.useEffect(()=>{const c=W(()=>{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}}},hM=t=>T.jsx("option",{title:t,value:t,children:t},t),uh="kos:service:region:settings",dh="timeZone",fM=`${uh}-${dh}`,pM=(t=hM)=>{const[e,s]=g.useState([]),[r,o]=g.useState(""),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}}),a=it.factory(fM)({path:uh,attribute:dh});g.useEffect(()=>{const u=W(()=>{s((n==null?void 0:n.timeZones.map(t))||[]),n!=null&&n.timeZones.length&&No(n==null?void 0:n.timeZones[0])});return()=>{u()}},[n,i,t]),g.useEffect(()=>{const u=W(()=>{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&&No(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}}},hh="kos:service:region",fh="regionId",gM=`${hh}-${fh}`,mM=t=>T.jsx("option",{title:t,value:t,children:t},t),ph=(t=mM)=>{const[e,s]=g.useState([]),[r,o]=g.useState("factory"),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}}),a=it.factory(gM)({path:hh,attribute:fh});g.useEffect(()=>{const u=W(()=>{s((n==null?void 0:n.availableRegions.map(t))||[])});return()=>{u()}},[n,i,t]),g.useEffect(()=>{const u=W(()=>{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&&yd(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}}},yM=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),bM=(t=yM)=>{const[e,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const c=W(()=>{s((n==null?void 0:n.timeFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),g.useEffect(()=>{const c=W(()=>{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}}},vM=(t,e)=>g.useMemo(()=>wn(t),e),wM={config:{attributes:!0,childList:!0,subtree:!0}};function EM(t,e,s=wM){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 gh={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}},wo=m.createLogger({name:"usePressGesture",group:"kos-hooks"});function MM({onPressed:t,onRelease:e,intersectionStrategy:s=gh}){const r=g.useRef(!1),o=Oh.useGesture({onDragStart:c=>{wo.info("onDragStart",c.type),s.validateStart(c)&&(t&&t(),r.current=!0)},onDrag:c=>{wo.info("onDrag",c.type),r.current&&s.validateStop(c)&&(e&&e(),r.current=!1)},onDragEnd:c=>{wo.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 mh=()=>{const[t,e]=g.useState(!1),s=O.getInstance();return g.useEffect(()=>{const r=W(()=>{s&&s.reloading!==t&&e(s.reloading)});return()=>{r()}},[s,t]),[t]};function yh(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 bh(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 vh({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=yh(t,e),i=jo(60,s),a=jo(60,r),c=bh(o);return{hourOptions:n,minuteOptions:i,secondOptions:a,amPmOptions:c}}function wh(t,e){return je.format(t,e)}function Eh({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=wh(o,r),{hourOptions:h,minuteOptions:f,secondOptions:p,amPmOptions:y}=vh({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 TM=t=>{const{regionModel:e}=ph(),s=g.useMemo(()=>({hour12:e==null?void 0:e.is12HourTimeFormat}),[e==null?void 0:e.is12HourTimeFormat]);return Eh({...t,locale:e==null?void 0:e.regionId,format:e==null?void 0:e.selectedTimeFormat,formatOptions:s})};function _M(t){return e=>{const[s]=mh();return s?T.jsx(Od,{message:"Wait a moment while your project reloads..."}):T.jsx(t,{...e})}}const na=m.createLogger({name:"studio-properties-service",group:"Services"}),SM="/api/kos/studio/properties",Mh=async t=>{if(na.debug("sending GET for studio-properties"),!t)throw na.error("connectionId is undefined"),new Error("connectionId is undefined");return await De.get(SM,{},{destinationAddress:t,timeout:500})},OM=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:Mh},Symbol.toStringTag,{value:"Module"}));var IM=Object.getOwnPropertyDescriptor,$M=(t,e,s,r)=>{for(var o=r>1?void 0:r?IM(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Th="studio-properties-model",CM="/kos/studio/properties",ia={"kos.studio.tool.legacy":1};let Bo=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=Se(),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=Mt.getInstance().subscribeTopic({topic:CM,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[t,e]=await Mh(this.connectionId);if(t){this.logger.error(`Error loading studio-properties: ${t}`),this.data.setValues(ia);return}if(e){const s=Object.keys(e).reduce((r,o)=>(r[o]=e[o]??o,r),{});this.data.setValues(s??ia),m.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(t){return this.data[t]}createObservableProperty(t){return wn(()=>this.get(t))}};Bo=$M([A(Th)],Bo);const DM=new ye({class:Bo,type:Th});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:()=>Ho.observer});exports.AuthState=cl;exports.BrowserKosRouter=pl;exports.BrowserRouter=An;exports.CanvasDispatcher=xt;exports.CanvasDispatcherServices=Pv;exports.CanvasRenderer=Qn;exports.CanvasStreamer=OE;exports.CanvasStreamerBase=Nd;exports.ChildModels=Be;exports.CompanionParentModel=Et;exports.ConfigBean=bs;exports.ContainerAwareSetup=ln;exports.CoreExtensionManager=xw;exports.CoreModels=ri;exports.CreateModelTranslationsContext=Rd;exports.CreateModelTranslationsProvider=oE;exports.DateDisplayFormat=ah;exports.DateHelpers=Kh;exports.DependencyLifecycle=U;exports.DependencyModels=F;exports.Device=Ir;exports.DeviceServices=sw;exports.DomIntersectionStrategy=gh;exports.EVENT_KOS_MODEL_READY=Go;exports.EVENT_TROUBLE_ADDED=em;exports.EVENT_TROUBLE_REMOVED=tm;exports.EXTENSION_CANVAS_RENDERER=te;exports.EXTENSION_FEATURE_FLAG_RESOLVER=sc;exports.EXTENSION_TROUBLE_DATA_MAPPER=pr;exports.EXTENSION_TROUBLE_MAPPER=Ns;exports.ErrorBoundaryWithFallback=Id;exports.EventBus=Dh;exports.EventBusFunctional=Ah;exports.EventBusState=Ph;exports.ExtensionManager=$;exports.FUTURE_CONTAINER_MODEL_TYPE=Kl;exports.FUTURE_MODEL_TYPE=Al;exports.FUTURE_NOT_ASSIGNED=Mn;exports.FeatureFlagService=rc;exports.FetchError=ge;exports.FutureAliases=ds;exports.FutureContainerFactory=He;exports.FutureContainerModel=ql;exports.FutureContainerSetup=on;exports.FutureEndState=Ke;exports.FutureFactory=Nt;exports.FutureHandler=Ur;exports.FutureManager=st;exports.FutureModel=Nl;exports.FutureService=cs;exports.HEADER_CACHE_CONTROL=ha;exports.HEADER_CONTENT_TYPE=da;exports.HEADER_DESTINATION_ADDR=Ne;exports.HEADER_FOS_REQUEST_ID=fa;exports.HEADER_METHOD=xr;exports.HEADER_ORDERED=zo;exports.HEADER_REQUEST_ID=Ds;exports.HEADER_REQUEST_TYPE=Ie;exports.HEADER_RESPONSE_ID=Ar;exports.HEADER_SOURCE_ADDR=ua;exports.HEADER_TOPIC=la;exports.HEADER_URL=Pt;exports.HEADER_WORK_TRACKER=Vo;exports.HttpRouteHandlers=Re;exports.KOS_EXECUTION_CONTEXT=Fr;exports.KOS_MODEL_ID=sr;exports.KeyValue=kn;exports.KeyValueServices=Wm;exports.Kos=ie;exports.KosConfigPropertySpec=it;exports.KosContainerIndex=dn;exports.KosContextBean=hl;exports.KosContextManager=Y;exports.KosCore=O;exports.KosCoreModelPropertyMapper=ve;exports.KosDataContainer=vn;exports.KosDependencyTypes=yf;exports.KosExpressionEvaluator=tu;exports.KosExtensionUtils=Vh;exports.KosFeatureFlags=oc;exports.KosFetchMethods=zc;exports.KosGlobalConfig=sn;exports.KosHttpRouteManager=gn;exports.KosLog=m;exports.KosLogManager=ou;exports.KosLogManagerServices=sb;exports.KosMockEvents=ma;exports.KosModel=ol;exports.KosModelCollectionProvider=Jw;exports.KosModelContainer=Ce;exports.KosModelContext=eo;exports.KosModelEvents=L;exports.KosModelFactory=hs;exports.KosModelLoader=xd;exports.KosModelLoaderDisplay=Ad;exports.KosModelManager=al;exports.KosModelProvider=$d;exports.KosModelRegistrationFactory=ye;exports.KosModelRegistry=Fo;exports.KosModelState=v;exports.KosModelSymbol=rn;exports.KosModelVisitor=Sg;exports.KosObservableData=bc;exports.KosRegistration=Gg;exports.KosSingletonRegistration=Yg;exports.KosTime=dr;exports.KosTimeContext=li;exports.KosTimeProvider=hE;exports.KosTimeServices=lb;exports.KosTimer=bd;exports.KosToken=fl;exports.KosTranslationProvider=vE;exports.KosTranslations=Bu;exports.KosWSTransportStatus=rl;exports.KosWsEvents=xs;exports.LOADER_FEATURE_FLAG=of;exports.LOGIN_HOST=pa;exports.LOGIN_URL=Ih;exports.LoadingMessage=Od;exports.LogBlock=_s;exports.LogBlockContainer=Qr;exports.LogConfig=us;exports.LogStream=ms;exports.LogStreamContainer=Fs;exports.LogStreamServices=wb;exports.LoggerSetup=cn;exports.MODEL_DELETION_DELAY=il;exports.MiddlewareChain=ll;exports.ModelEffects=Je;exports.MultipleFutureContainerSetup=nn;exports.MultipleFutureHandler=mc;exports.NestedModelContext=to;exports.NetworkInterface=Jn;exports.NetworkInterfaceContainer=Is;exports.NetworkInterfaceServices=dw;exports.ObservableData=Se;exports.Ota=mr;exports.OutsideAlerter=kE;exports.PLUGIN_EXTENSION_NAME=Gh;exports.PORT=ga;exports.PROFILE_LOG_DEBUG=Va;exports.PROFILE_LOG_INFO=Ga;exports.PROFILE_RELAX_STORE_VALIDATION=Wh;exports.PROFILE_TOOLS_PREVIEW=za;exports.ParentModel=ls;exports.PluginExtensionManager=Yh;exports.ProgressBar=Ww;exports.ReferenceConfig=Qs;exports.RegionInfo=re;exports.RegionServices=dm;exports.RegistrationManager=x;exports.Registry=Dw;exports.ReplayStrategy=Xe;exports.ResponseRetention=ue;exports.STATUS=qo;exports.ServiceFactory=oe;exports.ServiceRequestHandlers=et;exports.SingletonKosModelRegistrationFactory=_e;exports.SoftwareInfo=yr;exports.SoftwareInfoContext=di;exports.SoftwareInfoProvider=gE;exports.SoftwareInfoServices=sv;exports.StateBean=Os;exports.StateBeanServices=av;exports.StateProp=Vn;exports.StatePropServices=yv;exports.StorageDevice=Cr;exports.StorageDeviceContainer=At;exports.StorageDeviceServices=mw;exports.StudioProperties=DM;exports.StudioPropertiesServices=OM;exports.SubscriptionHandlers=ee;exports.TIMER_END=ii;exports.TIMER_EVENT=oi;exports.TOPIC_TIMER_TICK_EVENT=ni;exports.TimerManager=vd;exports.TokenContext=Fd;exports.TokenProvider=yE;exports.Topics=gs;exports.Trans=qE;exports.TransitionMap=Zs;exports.Transitions=fn;exports.Translation=wr;exports.TranslationContainer=Fe;exports.TranslationContainerContext=hi;exports.TranslationContext=Iv;exports.TransportFactory=Oo;exports.Trouble=Ss;exports.TroubleAwareSetup=an;exports.TroubleContainer=Ct;exports.TroubleServices=Ub;exports.Troubles=pe;exports.UsbUpdate=si;exports.UsbUpdateContainer=Cs;exports.UsbUpdateServices=_w;exports.WS_EVENT_TYPE=Ku;exports.WebSocketEvents=ps;exports.WebSocketTransport=Mt;exports.WsEventFactory=Yn;exports.acceptOrgInvitation=Sd;exports.addDaysToDate=Fa;exports.addFuture=Pl;exports.addMonthsToDate=La;exports.api=Ul;exports.applyMixins=Lh;exports.arraysEqual=Fh;exports.buildConfigBeanModel=om;exports.buildFuture=xn;exports.buildFutureModel=Ll;exports.cancelFuture=kl;exports.checkAppsStarted=Xg;exports.checkWildcardPattern=Ic;exports.clearAllServiceResponses=Bg;exports.clearPath=jg;exports.clearServiceResponse=Ug;exports.convert=In;exports.convertFileSizeRaw=kh;exports.convertWithUnits=ym;exports.createBaseMessage=Yc;exports.createBroadcastMessageResponse=Xc;exports.createCancellablePromise=Hw;exports.createClient=mn;exports.createFosBaseMessage=Gc;exports.createHeaders=Wt;exports.createKosHtpMessageResponse=Jc;exports.createKosMessage=Qc;exports.createKosMessageResponse=el;exports.createMessageBody=ze;exports.createModelDependency=Lc;exports.createOptionKey=df;exports.createPropKey=nt;exports.createReadableStream=Qt;exports.createStudioMessage=Vc;exports.createStudioMessageRequest=Wc;exports.createStudioMessageResponse=Zc;exports.debounce=Ha;exports.del=dc;exports.deleteFuture=Rl;exports.destroyKosModel=tt;exports.evaluateScopes=Ml;exports.executeChildrenModelLifecycle=Uc;exports.executeDependentModelLifecycle=Yt;exports.executeListLifecycle=Nc;exports.fetchModel=DE;exports.findModel=Df;exports.findModels=Ec;exports.formatDate=ja;exports.formatDateSince=ka;exports.formatDateTime=Ka;exports.formatTime=Ba;exports.get=uc;exports.getAllKosCompanionModels=Mc;exports.getCalendarMonthArray=Zd;exports.getConfigBean=El;exports.getDayStrings=Xd;exports.getDays=rM;exports.getDaysArray=Gd;exports.getDaysInMonth=tn;exports.getDependenciesByLifecycle=Fc;exports.getFormattedDate=oM;exports.getFormattedMonth=nM;exports.getFormattedMonthsArray=pi;exports.getFormattedYear=be;exports.getFormattedYearsArray=Qd;exports.getFutures=Pm;exports.getHttpRouteHandlers=hc;exports.getKosCompanionModel=xf;exports.getKosLocalizationDescriptor=Lu;exports.getKosMessageLogging=Za;exports.getKosModel=wc;exports.getKosModelSync=Oe;exports.getKosModelType=Cf;exports.getKosSessionKey=dl;exports.getLastDayOfMonth=as;exports.getLocalizationDescriptor=vv;exports.getLogLevel=Qa;exports.getLogMessageToStudio=Xa;exports.getMessageBody=So;exports.getMonthsArray=Yd;exports.getObservableCompanions=Af;exports.getQueryParams=me;exports.getServiceResponse=Fg;exports.getStartedApps=Jg;exports.getTranslations=ku;exports.getYearsArray=Wd;exports.hasCachedResponse=Ng;exports.hasDecimals=vl;exports.hasHttpRouteHandlers=or;exports.hasKosProfile=Eo;exports.hslStringToHex=ic;exports.hslToHex=nc;exports.httpDelete=vf;exports.initKosProvider=iE;exports.isBoolean=_n;exports.isKosCompanionTypeFactory=nl;exports.isKosDataModel=fs;exports.isKosExecutionContext=un;exports.isKosLoggingEnabled=Xh;exports.isKosModel=Te;exports.isKosModelContainer=pn;exports.isKosModelReady=nr;exports.isLeapYear=en;exports.isLocalRefId=Hg;exports.isNumber=jr;exports.isPrintable=cp;exports.isTroubleAware=$v;exports.isValidDate=is;exports.kosAction=X;exports.kosAutoEffect=W;exports.kosChild=$e;exports.kosCompanion=ff;exports.kosComputed=wn;exports.kosConfigBean=Br;exports.kosConfigProperty=Im;exports.kosContainerAware=lc;exports.kosContext=pf;exports.kosDependency=kt;exports.kosEffect=yl;exports.kosFuture=ai;exports.kosFutureAware=gf;exports.kosLogger=wf;exports.kosLoggerAware=pc;exports.kosModel=A;exports.kosModelEffect=gc;exports.kosMultipleFutureAware=mf;exports.kosObservable=En;exports.kosParentAware=Lr;exports.kosReference=Ef;exports.kosServiceRequest=Mf;exports.kosStateBean=Fw;exports.kosStateProp=Nw;exports.kosSubscribe=Vf;exports.kosTopicHandler=B;exports.kosTroubleAware=Tf;exports.kosWhen=$o;exports.login=Md;exports.mapConfigBeanModelToDto=Ol;exports.mapDataToModel=Mo;exports.mapDtoToConfigBeanModel=_l;exports.mapDtoToFutureModel=Dn;exports.mapDtoToFutureOptions=Cn;exports.mapUpdateDtoToConfigBeanModel=Sl;exports.modelEventTopicFactory=$c;exports.modelFactory=Lt;exports.modelTypeEventTopicFactory=Cc;exports.modifyConfigBean=wl;exports.modifyFuture=km;exports.pairedClientHeartbeat=Cg;exports.parseWildcardSegment=Oc;exports.pipe=ul;exports.post=Rs;exports.preloadKosModel=kf;exports.processId=Bh;exports.processMiddleware=Og;exports.put=bf;exports.registerCompanionModel=Pf;exports.registerCoreModels=pd;exports.registerExtensionPoint=As;exports.registerHttpRoutes=Ep;exports.registerKosModel=_c;exports.registerLegacyModel=Tc;exports.resetKosModel=$f;exports.resetPassword=_d;exports.resolveBaseUrl=Kc;exports.resolveChild=jc;exports.resolveContainerDeltas=Nh;exports.resolveItemListDeltas=jh;exports.resolveKosCompanion=To;exports.resolveKosContext=Vg;exports.resolveKosProfiles=Wa;exports.resolveListDeltas=Uh;exports.resolveServiceUrl=ae;exports.resolveVariable=ac;exports.retryWithExponentialBackoff=xg;exports.sendAsyncIntent=Qg;exports.sendBroadcastMessage=Up;exports.sendIntent=Wg;exports.sendKosHttpMessageResponse=sl;exports.sendKosMessage=Lp;exports.sendKosMessageResponse=tl;exports.sendRequest=qg;exports.sendStudioMessage=Np;exports.sendStudioMessageRequest=Fp;exports.startPasswordReset=Td;exports.stringComponentInsert=Hd;exports.studioAcceptOrgInvitation=Kw;exports.studioLogin=Uw;exports.studioResetPassword=Bw;exports.studioStartPasswordReset=jw;exports.subscribeStore=Aw;exports.syncPublish=zg;exports.transitionToActive=Ac;exports.transitionToInit=kc;exports.transitionToLoad=Pc;exports.transitionToReady=Rc;exports.transitionToUnload=ap;exports.troubleByTypeReducer=yc;exports.troubleDataFactory=Su;exports.unloadKosModel=If;exports.updateCompanionModelRegistration=$g;exports.updateModelRegistration=Ig;exports.updateRegion=yd;exports.updateTimeZone=No;exports.useAmPmValues=bh;exports.useCalendarDayArray=ih;exports.useConfigBean=eM;exports.useConfigProperty=Vd;exports.useContextModel=Zw;exports.useContextModelHierarchy=Dd;exports.useDateArrays=Jd;exports.useDateProps=aM;exports.useDateRelativeConfig=cM;exports.useDateRelativeData=lh;exports.useDayNames=oh;exports.useDayOptions=rh;exports.useDays=mi;exports.useDevice=Ud;exports.useFormattedDate=nh;exports.useFormattedTime=wh;exports.useFunctionWarmup=lM;exports.useHourValues=yh;exports.useKosCore=kd;exports.useKosDateFormats=dM;exports.useKosModel=Z;exports.useKosRegions=ph;exports.useKosTime=ci;exports.useKosTimeContext=fE;exports.useKosTimeFormats=bM;exports.useKosTimeZones=pM;exports.useKosTranslation=YE;exports.useKosTranslationContext=wE;exports.useLocalComputed=vM;exports.useModelFromHierarchy=tE;exports.useMonths=th;exports.useMonthsOptions=sh;exports.useMutationObserver=EM;exports.useNetworkInterfaceContainer=jd;exports.useOta=Bd;exports.usePressGesture=MM;exports.useProjectReload=mh;exports.useRegionTimeProps=TM;exports.useRegionalTimeDate=ch;exports.useSoftwareInfo=ui;exports.useSoftwareInfoContext=mE;exports.useStateProperty=LE;exports.useStorageDeviceContainer=Kd;exports.useSuspenseData=Uo;exports.useTimeOptions=vh;exports.useTimeProps=Eh;exports.useTimeValues=jo;exports.useTimer=NE;exports.useTranslationContainer=qd;exports.useTroubleContainerModel=fi;exports.useTroubleModel=QE;exports.useTroublePresence=ZE;exports.useUsbUpdateContainer=zd;exports.useYears=gi;exports.useYearsOptions=eh;exports.uuid=ot;exports.variableToHex=nf;exports.waitForAppToStart=Zg;exports.waitForAppsToStart=ml;exports.waitForRequest=bn;exports.whenReady=de;exports.withDevice=CE;exports.withKosTime=xE;exports.withNetworkInterfaceContainer=AE;exports.withOta=RE;exports.withProjectReloading=_M;exports.withSoftwareInfo=pE;exports.withStorageDeviceContainer=FE;exports.withTranslationContainer=WE;exports.withTroubleContainer=XE;exports.withUsbUpdateContainer=JE;exports.wrapPromise=Xo;
|
|
198
198
|
//# sourceMappingURL=index.cjs.map
|