@kosdev-code/kos-ui-sdk 2.0.28 → 2.0.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.cjs +33 -33
- package/index.cjs.map +1 -1
- package/index.js +1957 -1932
- package/index.js.map +1 -1
- package/models/utils/timer-manager.d.ts +5 -0
- package/models/utils/timer-manager.d.ts.map +1 -1
- package/package.json +2 -2
- package/ui/hooks/timer/use-timer.d.ts +8 -4
- package/ui/hooks/timer/use-timer.d.ts.map +1 -1
package/index.cjs
CHANGED
|
@@ -1,80 +1,80 @@
|
|
|
1
|
-
"use strict";var Xl=Object.defineProperty;var ed=(e,t,s)=>t in e?Xl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var a=(e,t,s)=>(ed(e,typeof t!="symbol"?t+"":t,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T=require("loglevel"),v=require("mobx"),m=require("robot3"),me=require("date-fns"),M=require("@emotion/react/jsx-runtime"),Po=require("@emotion/styled"),Tn=require("react-dom"),Ie=require("@emotion/react"),g=require("react"),ko=require("mobx-react-lite"),td=require("@use-gesture/react"),Fs="method",$n="topic",Qe="url",Kt="request-id",Ns="response-id",xo="status",fe="dst-addr",On="src-addr",le="type",Fo="ordered",No="tracker",Dn="Content-Type",Sn="Cache-Control",An="requestId",Cn=process.env.KOS_LOGIN_URL||"http://localhost",Rn=process.env.KOS_APP_PORT||"8080",sd=`${Cn}:${Rn}`,hs="{MODEL_ID}";var Gt=(e=>(e.SEND="/ws/log/msg/send",e.RECEIVED="/ws/log/msg/receive",e))(Gt||{}),Ln=(e=>(e.MSG_RECEIVE="/mock/msg/receive",e))(Ln||{});const Uo="/kos/model/ready/";T.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const L=globalThis.kos.subscriptions,od=()=>Symbol("eventKey");function jo(e){return L[e]&&Object.getOwnPropertySymbols(L[e]).length>0}function j(e,t){const s=od();return L[e]||(T.debug(`Initializing subscription for ${e}`),L[e]={}),T.debug(`Subscribing to ${e} with id ${s.toString()}`),L[e][s]=t,{count:L[e]?Object.getOwnPropertySymbols(L[e]).length:0,unsubscribe:()=>(T.debug(`Unsubscribing from ${e} with id ${s.toString()}`),L[e]&&L[e][s]&&delete L[e][s],L[e]&&Object.getOwnPropertySymbols(L[e]).length===0&&delete L[e],{count:L[e]?Object.getOwnPropertySymbols(L[e]).length:0})}}function N(e,t,s={}){if(!L[e]||Object.getOwnPropertySymbols(L[e]).length===0)return T.debug(`No subscriptions for ${e}. Not publishing.`),{eventType:e,subscribers:0};const o=Object.getOwnPropertySymbols(L[e]).length;return Object.getOwnPropertySymbols(L[e]).forEach(r=>{if(s.sync){const n=s.sync;T.debug(`Performing sync publish for ${e} with sync id ${n}`),L[e][r]({body:t,headers:s}).then(i=>{T.debug(`Response recieved for ${n}, publishing back to source.`),N(n,i)})}else T.debug(`Performing async publish for ${e}`),L[e][r]({body:t,headers:s})}),{eventType:e,subscribers:o}}function rd(){T.warn("Resetting event bus"),Object.keys(L).forEach(e=>delete L[e])}const nd=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:jo,publish:N,reset:rd,subscribe:j},Symbol.toStringTag,{value:"Module"})),id=(e,t=0)=>{if(!+e)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,o=t<0?0:t,r=["bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(e)/Math.log(s)),i=parseFloat((e/Math.pow(s,n)).toFixed(o)),c=r[n];return{value:i,scale:c,toString:()=>`${i} ${c}`}};function Bo(e){let t="pending",s;const o=e.then(n=>{t="success",s=n},n=>{t="error",s=n});return{read:()=>{switch(t){case"pending":throw o;case"error":throw s;default:return s}}}}function Xe(){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 ad(e,t){t.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(o=>{const r=Object.getOwnPropertyDescriptor(s.prototype,o);Object.defineProperty(e.prototype,o,r)})})}function cd(e,t){const s=e??[],o=t??[];return s.length!==o.length?!1:s.every((r,n)=>r===o[n])}const Ko=(e,t)=>{const s=e.map(n=>n.id);return t.map(n=>n.id).filter(n=>!s.includes(n))},ld=({container:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o),c=Ko(n,e.data).map(s).filter(Boolean);e.removeAll(c);const l=n.map(t).filter(Boolean);e.addAll(l)},dd=({container:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o);Ko(n,e.models).forEach(s),n.forEach(t)},ud=({items:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o);Ko(n,e).forEach(s),n.forEach(t)},hd=(e,t="parent-")=>{let s=e;return s.startsWith(t)&&(s=s.replace(t,"")),s},Br=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),Kr=[{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 Pn(e){let t=(e.getTime()-Date.now())/1e3;for(let s=0;s<=Kr.length;s++){const o=Kr[s];if(Math.abs(t)<o.amount)return Br.format(Math.round(t),o.name);t/=o.amount}return Br.format(Math.round(t),"years")}const Go=e=>e%4===0&&e%100!==0||e%400===0,Vo=(e,t)=>[31,Go(e)?29:28,31,30,31,30,31,31,30,31,30,31][t],kn=(e,t)=>{const s=new Date(e),o=e.getDate();return s.setDate(1),s.setMonth(s.getMonth()+t),s.setDate(Math.min(o,Vo(s.getFullYear(),s.getMonth()))),s},xn=(e,t)=>{const s=new Date(e);return s.setDate(s.getDate()+t),s},Ke="en-US",Fn={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"}},Nn={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"}},Un=(e,{dateStyle:t="short",locales:s=Ke}={dateStyle:"short",locales:Ke})=>{const o=t==="short"?Fn.short:{dateStyle:t};return new Intl.DateTimeFormat(s,o).format(e)},jn=(e,{locales:t=Ke,timeStyle:s="short"}={locales:Ke,timeStyle:"short"})=>{const o=Nn[s];return new Intl.DateTimeFormat(t,o).format(e)},Bn=(e,{dateStyle:t="short",locales:s=Ke,timeStyle:o="short"}={dateStyle:"short",locales:Ke,timeStyle:"short"})=>{const r={...t&&Fn[t],...o&&Nn[o]};return new Intl.DateTimeFormat(s,r).format(e)},gd=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:xn,addMonthsToDate:kn,formatDate:Un,formatDateSince:Pn,formatDateTime:Bn,formatTime:jn,getDaysInMonth:Vo,isLeapYear:Go},Symbol.toStringTag,{value:"Module"}));function Kn(e,t,s=300){let o;return(...r)=>{clearTimeout(o),o=setTimeout(()=>{t.apply(e,r)},s)}}class Gn{constructor(t={}){a(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 Gn;const fd=window.KosFeatureFlags,ee=(e=null)=>(e||window.location.search.replace("?","")).split("&").map(t=>{const[s,o]=t.split("=");return[s,decodeURIComponent(o||"")]}).reduce((t,[s,o])=>(t[s]=o,t),{}),Vn=(e,t,s)=>{s/=100;const o=t*Math.min(s,1-s)/100,r=n=>{const i=(n+e/30)%12,c=s-o*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*c).toString(16).padStart(2,"0")};return`#${r(0)}${r(8)}${r(4)}`},Hn=e=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(e);if(!s)throw Error("Invalid HSL string");return Vn(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},Yn=(e,t)=>getComputedStyle(e).getPropertyValue(t),pd=(e,t)=>Hn(Yn(e,t)),zn="studio.tools.preview",md="studio.relax.store.validation",qn="studio.log.debug",Wn="studio.log.info",yd={profiles:[zn]};var In;const bd=((In=globalThis.getKosConfig)==null?void 0:In.call(globalThis))||JSON.stringify(yd),Zn=JSON.parse(bd);globalThis.kosConfig=Zn;const Ho=Zn,Jn=()=>Ho.profiles||[],fo=e=>Jn().includes(e),vd=()=>Ho.logging||!1,wd=(e,t)=>{const s={...e};return s.id&&delete s.id,s},po=(e,t,s=wd)=>{const o=s(e,t);v.runInAction(()=>{Object.assign(t,o)})},to=new Map,Qn={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)})}},Md=()=>{const e=fo(qn),t=fo(Wn);return e?"DEBUG":t?"INFO":void 0},Xn=()=>{const e=ee(),t=Md(),o=e.kosLogLevel??t??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return o||"WARN"},ei=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",ti=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",si="ws-log",_d=T.methodFactory,oi=ei(),Ed=ti();T.methodFactory=function(e,t,s){const o=_d(e,t,s);return function(r,n){var l;const i=s?String(s):"",c=i?`[${String(i).substring(i.lastIndexOf(":")+1)}] | `:"[root] | ";o(`${c}${r}`,n||""),(l=globalThis==null?void 0:globalThis.kosConfig)!=null&&l.logging&&globalThis.kosLog&&(s!==si||oi&&Ed)&&globalThis.kosLog(`UI: ${c}${r}`)}};let ri=Xn();T.setLevel(ri);window.setKosLogLevel=e=>{ri=e,T.setLevel(e)};const gs=T.getLogger(si);window.enableKosMessageLog=()=>{gs.setLevel(T.levels.INFO)};window.disableKosMessageLog=()=>{gs.setLevel(T.levels.ERROR)};oi?window.enableKosMessageLog():window.disableKosMessageLog();const Id=["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(";"),Td=["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(";"),Zt=e=>t=>{T.getLevel()<=e&&t()},f={...T,ifDebug:Zt(T.levels.DEBUG),ifInfo:Zt(T.levels.INFO),ifWarn:Zt(T.levels.WARN),ifError:Zt(T.levels.ERROR),getLogger:e=>T.getLogger(`kos::${e}`),createLogger:({name:e,group:t})=>T.getLogger(`${t?`${t}:`:"kos"}::${e}`),wsSend:(...e)=>{const t=String(e).replace(/\n/g,"\\n");gs.info(`%c⬆ ${t}`,Id)},wsReceive:(...e)=>{const t=String(e).replace(/\n/g,"\\n");gs.info(`%c⬇ ${t}`,Td)}},$d=f.createLogger({name:"kos-dependency-manager"});class Od{constructor(){a(this,"_usedByCache",new Map);a(this,"_usesCache",new Map)}add(t,s){Qn.cancelDeletion(s);const o=this._usedByCache.get(s)||[];o.includes(t)||o.push(t),this._usedByCache.set(s,o);const r=this._usesCache.get(t)||[];r.includes(s)||r.push(s),this._usesCache.set(t,r)}remove(t,s){const o=this._usedByCache.get(s)||[];this._usedByCache.set(s,o.filter(n=>n!==t));const r=this._usesCache.get(t)||[];this._usesCache.set(t,r.filter(n=>n!==s))}canDestroy(t){const s=this._usedByCache.get(t);return s!=null&&s.length?($d.info(`Model ${t} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}var y=(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))(y||{}),D=(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))(D||{});const Gr=f.createLogger({name:"kos-model-cache"});class Dd{constructor(t=[]){a(this,"_modelsById",v.observable.map(new Map));a(this,"_toDelete",new Map);a(this,"_preloaded",[]);a(this,"_isPreloaded",!1);this.preloadKeys=t}get models(){return Array.from(this._modelsById.values()).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?(Gr.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(Gr.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),t(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const so=new Map,Vr=new Map,oo=new Map,ro=new Map,Yo=(e,t)=>{ni[e]=t},ni={indexExtension:{registerIndexExtension:(e,t)=>{const s=ro.get(e)||{};Object.assign(s,t),ro.set(e,t)},loadIndexExtensions:e=>ro.get(e)||{}},loader:{registerLoader:(e,t)=>{Vr.set(e,t)},executeLoader:async(e,t)=>{const s=Vr.get(e);if(s)return await s(t)}},propertyMapper:{registerPropertyMapper:(e,t)=>{oo.set(e,t)},hasMapper:e=>oo.has(e),executeMapper:(e,t,s)=>{const o=oo.get(e);return o?o(t,s):""}},dataMapper:{registerDataMapper:(e,t)=>{const s=so.get(e)||[];s.push(t),so.set(e,s)},executeMapper:async(e,t,s)=>{const o=so.get(e);if(!o)return{};const r={};for(const n of o){const i=await n(t,s);Object.assign(r,i)}return r}}},C=ni;function ii(e,t){return`${Uo}${e}${t?`/${t}`:`/${e}`}`}function ai(e){return`${Uo}${e}`}var x=(e=>(e.INIT="init",e.LOAD="load",e.READY="ready",e.ACTIVATE="activate",e.ONLINE="online",e))(x||{});const Sd=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:x},Symbol.toStringTag,{value:"Module"}));function Hr(e){const t=[];return new Promise((s,o)=>{for(const{condition:r,onMatch:n}of e){const i=v.when(r,()=>{t.forEach(c=>c());try{n==null||n(),s()}catch(c){o(c)}});t.push(i)}})}const G=Symbol("SubscriptionHandlers"),P=Symbol("DependencyModels"),wt=Symbol("FutureService"),Mt=Symbol("ChildModels"),_t=Symbol("ParentModel"),Et=Symbol("LogConfig"),is=Symbol("ReferenceConfig"),ci=Symbol("KosModelSymbol"),$e=Symbol("ModelEffects"),ie=(e,t)=>{e[Mt]=e[Mt]||{},e[Mt][t]=!0},Se=e=>`{PROP_${String(e)}}`,Ad=e=>`{PROP_${String(e)}}`,Cd=Se("kosParentId"),Us=e=>t=>{t[_t]=t[_t]||{};const s=(e==null?void 0:e.parentId)||Cd;t[_t]={parentId:s}},Ge=({value:e,modelId:t,modelData:s})=>{let o=e;if(Array.isArray(o))return[...e];if(typeof o!="string"&&typeof o!="object")return o;if(typeof o=="object")o=Object.keys(o).reduce((r,n)=>(r[n]=Ge({value:o[n],modelId:t,modelData:s}),r),{});else if(typeof o=="string"){const r=new RegExp(".*({PROP_(.+)})");let n=o!=null&&o.includes(hs)?o.replace(hs,t):o;const i=n.match(r);if(i&&s&&(Object.getOwnPropertyNames(s).includes(i[2])||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(i[2]))){const c=s[i[2]];n=c?n.replace(i[1],c):void 0}return n}else return o;return o},Rd=f.createLogger({name:"kos-model"});function Ld(e,t,s){var n;const o=(n=e[_t])==null?void 0:n.parentId;if(!o)return;const r=Ge({value:o,modelData:s,modelId:t});r&&typeof r=="string"&&k.setParentContext(t,r)}function Pd(e){const t=e[wt];t&&Object.entries(t).forEach(([s,{handler:o}])=>{e[s]=o})}function kd(e,t){const s=e[P]||{};Object.entries(s).forEach(([o,r])=>{const n=Ge({value:r.id||r.modelType,modelData:e,modelId:t}),i=Object.entries((r==null?void 0:r.options)||{}).reduce((c,[l,d])=>(c[l]=Ge({value:d,modelData:e,modelId:t}),c),{});if(typeof n=="string"){if(!r.lazy){const c=E.getInstance().modelManager.createModelInstance(r.modelType,n,i);e[o]=c.data}E.getInstance().modelManager.addDependency(t,n)}})}function xd(e){try{return v.makeAutoObservable(e)}catch(t){return Rd.error("Failed to make observable:",t),e}}const Fd={construct(e,t){var c;const[s,o={}]=t,r=k.createContext(s);Ld(e,s,o);const n=f.createLogger({name:e.prototype.modelTypeId,group:((c=e[Et])==null?void 0:c.group)??"kos-model"}),i=new e(s,o,{logger:n,kosContext:r});return Pd(i),kd(i,s),xd(i)}};function O(e){return t=>{var o,r;const s=t;return s.prototype.modelTypeId=e,s.prototype[ci]=!0,(o=s.prototype)[G]??(o[G]={}),(r=s.prototype)[P]??(r[P]={}),f.ifDebug(()=>{f.debug(`Registering model with id ${e}`)}),new Proxy(s,Fd)}}const Nd=({modelType:e})=>t=>{Us()(t),O(e)(t)};function Ud(e,t,s){const o=s.value;s.value=function(...r){const n=k.getContext(this.id);return r.push(n),o.apply(this,r)}}const jd=({group:e}={group:""})=>t=>{t[Et]=t[Et]||{},t[Et]={group:e}};function li(e){return(t,s,o)=>{t[$e]=t[$e]||{},t[$e][s]={dependencies:e==null?void 0:e.dependencies,value:o.value},o.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const Bd=e=>(t,s)=>{t[is]=t[is]||{},t[is][s]=e},Ae=({modelType:e,id:t,options:s,lifecycle:o})=>(r,n)=>{r[P]=r[P]||{},r[P][n]={modelType:e,id:t,options:s,lifecycle:o||x.INIT}},Kd=({topic:e,handler:t,websocket:s=!1,condition:o=()=>!0})=>r=>{r[G]=r[G]||{},Array.isArray(e)?e.forEach(n=>{r[G][n]={websocket:s,handler:t,condition:o}}):r[G][e]={websocket:s,handler:Kn(r,v.action(t),200),condition:o}};function R({topic:e,condition:t=(d,u)=>!0,transform:s=d=>d,websocket:o=!1,fos:r=!1,bridge:n=!1,skipParse:i=!1,lifecycle:c,destinationAddress:l}){return(d,u,h)=>{d[G]=d[G]||{},Array.isArray(e)?e.forEach(p=>{d[G][p]={websocket:o,fos:r,bridge:n,handler:h.value,condition:t,transform:s,lifecycle:c,skipParse:i,destinationAddress:l}}):d[G][e]={websocket:o,fos:r,bridge:n,handler:h.value,condition:t,transform:s,lifecycle:c,skipParse:i,destinationAddress:l}}}const di=5e3;class Gd extends Error{constructor(s,o){super(s);a(this,"model");this.model=o}}const ui=(e,t,s)=>{let o;return{promise:new Promise((i,c)=>{o=setTimeout(()=>{f.error(`Model ${t.modelId} - ${t.modelTypeName} - ${s} timed out after ${e}ms`),c(new Gd(`${t.modelId} - ${t.modelTypeName} - ${s}`,t))},e)}),cancel:()=>{o&&clearTimeout(o)}}},hi=e=>e.fsm.transitionTo(D.GO_ACTIVE,y.ACTIVE),gi=e=>e.whenReady(),fi=e=>e.fsm.transitionTo(D.LOAD,y.LOADED),Vd=e=>e.fsm.transitionTo(D.UNLOAD,y.UNLOADED),pi=e=>e.fsm.transitionTo(D.INITIALIZE,y.INITIALIZED);var zo=(e=>(e.ACTIVE="active",e.READY="ready",e.LOAD="load",e.UNLOAD="unload",e.INIT="init",e))(zo||{});const as={active:hi,ready:gi,load:fi,init:pi},mi=(e,t)=>{const s=t.id||t.modelType,o=Ge({value:s,modelData:e.modelData,modelId:e.modelId});f.debug(`activating dependent model ${t.modelType} with id ${o}`);const r=Object.keys((t==null?void 0:t.options)||{}).reduce((i,c)=>{const l=t.options[c];return i[c]=Ge({value:l,modelData:e.modelData,modelId:e.modelId}),i},{});return{dependentModel:E.getInstance().modelManager.createModelInstance(t.modelType,o,r),dataModelId:o}},yi=(e,t=x.READY)=>{var r;const s=((r=e.modelData)==null?void 0:r[P])||{};return Object.keys(s).length===0?(f.debug(`${e.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===t).map(n=>{const i=s[n],{dependentModel:c,dataModelId:l}=mi(e,i);e.modelData[n]=c.data,f.debug(`waiting for dependent model ${i.modelType} with id ${l} - waiting for WHENREADY`);const d=async(p,w,b)=>{var _;await((_=p.whenReady)==null?void 0:_.call(p)),f.debug(`dependent model ${w} with id ${b} - READY`)},{promise:u,cancel:h}=ui(di,e,e.status);return Promise.race([d(c.model,i.modelType,l).then(()=>{h()}).catch(p=>{console.error(`Error waiting for dependent model ${i.modelType} with id ${l}:`,p),h()}),u])}).filter(n=>!!n)},bi=async(e,t,s,o)=>{if(f.debug(`Execute lifecycle with ${t.length} models`),t.length===0){f.debug(`${e.modelId} has no children. Returning`);return}if(!s){f.error(`${e.modelId} is not transitioning with a valid target ${s}`);return}const r=t.map(c=>{let l;return as[s]&&c?l=as[s](c):(c||f.error("model is undefined. This shouldn't happen"),as[s]||f.error(`There is no promise in the Transition Map for ${s}`)),{promise:l,modelId:c==null?void 0:c.modelId,model:c,type:c==null?void 0:c.modelTypeName,status:c==null?void 0:c.status}}).filter(c=>c.promise?c.model?!0:(f.error(`No model found ${c.modelId}`),!1):(f.error(`No promise found ${c.modelId}`),!1)),i=(await Promise.allSettled(r.map(c=>{var u;const{promise:l,cancel:d}=ui(di,c.model,c.status);return Promise.race([(u=c.promise)==null?void 0:u.then(()=>{d()}).catch(h=>{f.error(`Model ${c.modelId} - ${c.type} failed to transition to ${s}: ${h.message}`),d()}),l])}))).filter(c=>c.status==="rejected");i.length>0&&f.error(`Model ${e.modelId} had ${i.length} failed child models on ${o}`)},vi=async(e,t,s)=>{await bi(e,e.getChildren().filter(o=>!!o),t,s)},ct=async(e,t)=>{const o=(await Promise.allSettled(yi(e,t))).filter(r=>r.status==="rejected");o.length&&(f.error(`There were ${o.length} failed dependent models on ${t}`),f.error(o))},Hd=e=>typeof e.toJSON=="function",It=e=>e[P]!==void 0,qo=e=>e.revision!==void 0&&e.index!==void 0,wi=e=>{if(e){if(It(e))return e;if(qo(e))return e.data;if(e instanceof Map||e instanceof v.ObservableMap||e instanceof Set)return Array.from(e.values()).filter(It);if(Array.isArray(e))return e.filter(It)}};function Yd(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 o of s)o in e&&Object.defineProperty(e,o,{enumerable:!1});Object.defineProperty(e,"debugState",{enumerable:!1,configurable:!0,get(){var o,r,n;return{id:e.modelId,type:e.modelTypeName,initialized:e.initialized,loaded:e.loaded,status:e.status,onlineStatus:e.onlineStatus,activeStatus:e.activeStatus,companions:(r=(o=e.companionManager)==null?void 0:o.all())==null?void 0:r.map(i=>i.modelTypeName),children:(n=e.getChildren)==null?void 0:n.call(e).map(i=>i.modelId),effects:!!e.effectManager,subs:!!e.subscriptionManager}}}),zd(e.modelData,e.modelTypeName,e.modelId,e)}function zd(e,t,s,o){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 c,l,d;const r=((c=o.getChildren)==null?void 0:c.call(o))||[],n=((l=o.companionManager)==null?void 0:l.all())||[],i=o.modelData[P]||{};return{id:s,type:t,companions:{count:n.length,data:n.map(u=>({type:u.modelTypeName,id:u.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(u=>({id:u.id||u.modelType,type:u.modelType,options:u.options,lifecycle:u.lifecycle}))},children:{count:r.length,data:r.map(u=>({id:u.modelId,type:u.modelTypeName}))},data:((d=e.toJSON)==null?void 0:d.call(e))||{},subs:!!o.subscriptionManager}}}),Object.defineProperty(e,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const r={};for(const n of Object.keys(e))if(!(n.startsWith("_")||typeof e[n]=="function"))try{const i=e[n];It(i)?r[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:qo(i)?r[`[KOS Container] ${n}`]=typeof i.toJSON=="function"?i.toJSON():["Container"]:Array.isArray(i)?r[n]=`[Array(${i.length})]`:typeof i=="object"&&i!==null?r[n]=JSON.parse(JSON.stringify(i)):r[n]=i}catch{r[n]="[unreadable]"}return r}})}class qd{constructor(t){this.model=t}resolve(){const t=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(t).map(o=>this.model.modelManager.getModelById(o.id||"")).filter(o=>o&&o.status!==y.FAILED).filter(o=>!!o);return s.forEach(o=>{try{k.setParentContext(o.modelId,this.model.modelId)}catch(r){console.error(`Failed to set parent context for ${o.modelId} under ${this.model.modelId}`,r)}}),s}getResolvedDecoratedChildren(){var s;const t=((s=this.model.modelData)==null?void 0:s[Mt])||{};return Object.keys(t).map(o=>wi(this.model.modelData[o])).filter(o=>!!o).flat()}getAdditionalChildren(){var t,s;return((s=(t=this.model.modelData)==null?void 0:t.getChildren)==null?void 0:s.call(t))||[]}}class Wd{constructor(t){a(this,"companions",new v.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 Zd{constructor(t,s,o,r){a(this,"disposers",[]);this.modelTypeName=t,this.modelId=s,this.modelData=o,this.log=r}setup(){var s;const t=((s=this.modelData)==null?void 0:s[$e])||{};for(const o of Object.keys(t)){const{value:r,dependencies:n,options:i}=t[o],c=r.bind(this.modelData),l=()=>{this.log.info(`Running effect ${o} for ${this.modelTypeName} (${this.modelId})`),v.runInAction(()=>c())},d=n?v.reaction(()=>n(this.modelData),l,{fireImmediately:!!(i!=null&&i.fireImmediately)}):v.autorun(l);this.disposers.push(d)}}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 Jd=f.createLogger({name:"model-active-machine"}),Qd=e=>{const t=m.createMachine(y.INACTIVE,{[y.FAILED]:m.state(m.transition(D.GO_ACTIVE,y.ACTIVATING)),[y.INACTIVE]:m.state(m.transition(D.GO_ACTIVE,y.ACTIVATING)),[y.ACTIVATING]:m.invoke(()=>(e.activeStatus=y.ACTIVATING,e.activate()),m.transition("done",y.ACTIVE,m.action(()=>{e.activeStatus=y.ACTIVE})),m.transition("error",y.FAILED,m.action(()=>{e.activeStatus=y.FAILED}))),[y.ACTIVE]:m.state(m.transition(D.GO_INACTIVE,y.DEACTIVATING)),[y.DEACTIVATING]:m.invoke(()=>(e.activeStatus=y.DEACTIVATING,e.deactivate()),m.transition("done",y.INACTIVE,m.action(()=>{e.activeStatus=y.INACTIVE})),m.transition("error",y.FAILED,m.action(()=>{e.activeStatus=y.FAILED})))});return{service:m.interpret(t,o=>Jd.debug(o.machine.current)),machine:t}},Yr=f.createLogger({name:"model-online-machine"}),Xd=e=>{const t=m.createMachine(y.OFFLINE,{[y.ONLINE]:m.state(m.transition(D.GO_OFFLINE,y.OFFLINE,m.action(async()=>{await e.offline(),e.onlineStatus=y.OFFLINE}))),[y.OFFLINE]:m.state(m.transition(D.GO_ONLINE,y.ONLINE,m.action(async()=>{Yr.debug(`Going online with model ${e.modelId}`),await e.online(),e.onlineStatus=y.ONLINE,await e.fsm.transitionTo(D.INITIALIZE,y.INITIALIZED)})))}),s=m.interpret(t,o=>Yr.debug(o.machine.current));return{machine:t,service:s}},eu=e=>{var o;const t=Qd(e).service,s=Xd(e).service;return m.createMachine(y.CREATING,{[y.CREATING]:m.state(m.transition(D.CREATE,y.CREATED)),[y.CREATED]:m.state(m.immediate(y.INITIALIZING)),[y.INITIALIZING]:m.invoke(()=>(z(()=>{e.status=y.INITIALIZING}),e.init()),m.transition("done",y.INITIALIZED,m.action(()=>{e.status=y.INITIALIZED})),m.transition("error",y.FAILED,m.action(()=>{f.error(`Model ${e.modelId} - ${e.modelTypeName} failed to initialize. Transitioning to FAILED state.`),e.status=y.FAILED}))),[y.INITIALIZED]:m.state(m.immediate(y.LOADING)),[y.LOADING]:m.invoke(()=>(z(()=>{e.status=y.LOADING}),e.load()),m.transition("done",y.LOADED,m.action(()=>{e.status=y.LOADED})),m.transition("error",y.FAILED,m.action(()=>{e.status=y.FAILED}))),[y.LOADED]:m.state(m.immediate(y.READYING),m.transition(D.UNLOAD,y.UNLOADING)),[y.RESETTING]:m.invoke(()=>{var r;return z(()=>{e.status=y.RESETTING}),(r=e.unload)==null||r.call(e),e.load()},m.transition("done",y.LOADED,m.action(()=>{e.status=y.LOADED}))),[y.READYING]:m.invoke(()=>(z(()=>{e.status=y.READYING}),e.ready()),m.transition("done",y.READY,m.action(()=>{z(()=>{e.status=y.READY}),s.send(D.GO_ONLINE)})),m.transition("error",y.FAILED,m.action(()=>{e.status=y.FAILED}))),[y.READY]:m.state(m.transition(D.UNLOAD,y.UNLOADED,m.action((o=e.unload)==null?void 0:o.bind(e))),m.transition(D.RESET,y.RESETTING),m.transition(D.GO_ONLINE,y.READY,m.action(()=>{s.send(D.GO_ONLINE)})),m.transition(D.GO_OFFLINE,y.READY,m.action(()=>{s.send(D.GO_OFFLINE)})),m.transition(D.GO_ACTIVE,y.READY,m.action(()=>{t.send(D.GO_ACTIVE)})),m.transition(D.GO_INACTIVE,y.READY,m.action(()=>{t.send(D.GO_INACTIVE)}))),[y.UNLOADED]:m.state(),[y.FAILED]:m.state()})},tu=f.createLogger({name:"kos-model-lifecycle"}),su=e=>({service:m.interpret(eu(e),s=>tu.debug(`state machine for model ${e.modelId}: ${s.machine.current});`))});class ou{constructor(t,s){a(this,"disposer");a(this,"service");this.model=t,this.log=s;const o=su(t);this.service=o.service,this.service.send(D.CREATE)}get current(){return this.service.machine.current}async transitionTo(t,s,o=y.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 c;(c=this.disposer)==null||c.call(this),this.disposer=v.when(()=>{const l=this.getTransitionStatusFor(s);return l===s||l===o},()=>{this.getTransitionStatusFor(s)===o?(this.log.error(`Model ${this.model.modelId} entered error state ${o} 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[y.ACTIVE,y.INACTIVE].includes(t)?this.model.activeStatus:this.model.status}}class ru{static create({modelId:t,modelTypeName:s,component:o}){const r=[o??"kos",s,t].filter(Boolean).join(".");return f.createLogger({name:r})}}class nu{constructor(t){a(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 iu{constructor(t,s){a(this,"unsubscribers",[]);this.model=t,this.log=s}register(){const t=this.model.modelId,s=j("/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(D.GO_ONLINE,y.ONLINE)}),o=j("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${t} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(D.GO_OFFLINE,y.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(o.unsubscribe)}dispose(){this.unsubscribers.forEach(t=>t()),this.unsubscribers=[]}}var Mi=(e=>(e.GET="GET",e.PUT="PUT",e.POST="POST",e.DELETE="DELETE",e))(Mi||{});const _i=({path:e,requestId:t,method:s,destinationAddress:o})=>{let r=`${Fs}:${s}
|
|
1
|
+
"use strict";var td=Object.defineProperty;var sd=(e,t,s)=>t in e?td(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var a=(e,t,s)=>(sd(e,typeof t!="symbol"?t+"":t,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T=require("loglevel"),v=require("mobx"),m=require("robot3"),me=require("date-fns"),M=require("@emotion/react/jsx-runtime"),ko=require("@emotion/styled"),On=require("react-dom"),Ie=require("@emotion/react"),g=require("react"),xo=require("mobx-react-lite"),od=require("@use-gesture/react"),Fs="method",Dn="topic",Qe="url",Kt="request-id",Ns="response-id",Fo="status",fe="dst-addr",Sn="src-addr",le="type",No="ordered",Uo="tracker",Cn="Content-Type",An="Cache-Control",Rn="requestId",Ln=process.env.KOS_LOGIN_URL||"http://localhost",Pn=process.env.KOS_APP_PORT||"8080",rd=`${Ln}:${Pn}`,hs="{MODEL_ID}";var Gt=(e=>(e.SEND="/ws/log/msg/send",e.RECEIVED="/ws/log/msg/receive",e))(Gt||{}),kn=(e=>(e.MSG_RECEIVE="/mock/msg/receive",e))(kn||{});const jo="/kos/model/ready/";T.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const L=globalThis.kos.subscriptions,nd=()=>Symbol("eventKey");function Bo(e){return L[e]&&Object.getOwnPropertySymbols(L[e]).length>0}function U(e,t){const s=nd();return L[e]||(T.debug(`Initializing subscription for ${e}`),L[e]={}),T.debug(`Subscribing to ${e} with id ${s.toString()}`),L[e][s]=t,{count:L[e]?Object.getOwnPropertySymbols(L[e]).length:0,unsubscribe:()=>(T.debug(`Unsubscribing from ${e} with id ${s.toString()}`),L[e]&&L[e][s]&&delete L[e][s],L[e]&&Object.getOwnPropertySymbols(L[e]).length===0&&delete L[e],{count:L[e]?Object.getOwnPropertySymbols(L[e]).length:0})}}function F(e,t,s={}){if(!L[e]||Object.getOwnPropertySymbols(L[e]).length===0)return T.debug(`No subscriptions for ${e}. Not publishing.`),{eventType:e,subscribers:0};const o=Object.getOwnPropertySymbols(L[e]).length;return Object.getOwnPropertySymbols(L[e]).forEach(r=>{if(s.sync){const n=s.sync;T.debug(`Performing sync publish for ${e} with sync id ${n}`),L[e][r]({body:t,headers:s}).then(i=>{T.debug(`Response recieved for ${n}, publishing back to source.`),F(n,i)})}else T.debug(`Performing async publish for ${e}`),L[e][r]({body:t,headers:s})}),{eventType:e,subscribers:o}}function id(){T.warn("Resetting event bus"),Object.keys(L).forEach(e=>delete L[e])}const ad=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:Bo,publish:F,reset:id,subscribe:U},Symbol.toStringTag,{value:"Module"})),cd=(e,t=0)=>{if(!+e)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,o=t<0?0:t,r=["bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(e)/Math.log(s)),i=parseFloat((e/Math.pow(s,n)).toFixed(o)),c=r[n];return{value:i,scale:c,toString:()=>`${i} ${c}`}};function Ko(e){let t="pending",s;const o=e.then(n=>{t="success",s=n},n=>{t="error",s=n});return{read:()=>{switch(t){case"pending":throw o;case"error":throw s;default:return s}}}}function Xe(){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 ld(e,t){t.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(o=>{const r=Object.getOwnPropertyDescriptor(s.prototype,o);Object.defineProperty(e.prototype,o,r)})})}function dd(e,t){const s=e??[],o=t??[];return s.length!==o.length?!1:s.every((r,n)=>r===o[n])}const Go=(e,t)=>{const s=e.map(n=>n.id);return t.map(n=>n.id).filter(n=>!s.includes(n))},ud=({container:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o),c=Go(n,e.data).map(s).filter(Boolean);e.removeAll(c);const l=n.map(t).filter(Boolean);e.addAll(l)},hd=({container:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o);Go(n,e.models).forEach(s),n.forEach(t)},gd=({items:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o);Go(n,e).forEach(s),n.forEach(t)},fd=(e,t="parent-")=>{let s=e;return s.startsWith(t)&&(s=s.replace(t,"")),s},Gr=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),Vr=[{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 xn(e){let t=(e.getTime()-Date.now())/1e3;for(let s=0;s<=Vr.length;s++){const o=Vr[s];if(Math.abs(t)<o.amount)return Gr.format(Math.round(t),o.name);t/=o.amount}return Gr.format(Math.round(t),"years")}const Vo=e=>e%4===0&&e%100!==0||e%400===0,Ho=(e,t)=>[31,Vo(e)?29:28,31,30,31,30,31,31,30,31,30,31][t],Fn=(e,t)=>{const s=new Date(e),o=e.getDate();return s.setDate(1),s.setMonth(s.getMonth()+t),s.setDate(Math.min(o,Ho(s.getFullYear(),s.getMonth()))),s},Nn=(e,t)=>{const s=new Date(e);return s.setDate(s.getDate()+t),s},Ke="en-US",Un={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"}},jn={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"}},Bn=(e,{dateStyle:t="short",locales:s=Ke}={dateStyle:"short",locales:Ke})=>{const o=t==="short"?Un.short:{dateStyle:t};return new Intl.DateTimeFormat(s,o).format(e)},Kn=(e,{locales:t=Ke,timeStyle:s="short"}={locales:Ke,timeStyle:"short"})=>{const o=jn[s];return new Intl.DateTimeFormat(t,o).format(e)},Gn=(e,{dateStyle:t="short",locales:s=Ke,timeStyle:o="short"}={dateStyle:"short",locales:Ke,timeStyle:"short"})=>{const r={...t&&Un[t],...o&&jn[o]};return new Intl.DateTimeFormat(s,r).format(e)},pd=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Nn,addMonthsToDate:Fn,formatDate:Bn,formatDateSince:xn,formatDateTime:Gn,formatTime:Kn,getDaysInMonth:Ho,isLeapYear:Vo},Symbol.toStringTag,{value:"Module"}));function Vn(e,t,s=300){let o;return(...r)=>{clearTimeout(o),o=setTimeout(()=>{t.apply(e,r)},s)}}class Hn{constructor(t={}){a(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 Hn;const md=window.KosFeatureFlags,ee=(e=null)=>(e||window.location.search.replace("?","")).split("&").map(t=>{const[s,o]=t.split("=");return[s,decodeURIComponent(o||"")]}).reduce((t,[s,o])=>(t[s]=o,t),{}),Yn=(e,t,s)=>{s/=100;const o=t*Math.min(s,1-s)/100,r=n=>{const i=(n+e/30)%12,c=s-o*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*c).toString(16).padStart(2,"0")};return`#${r(0)}${r(8)}${r(4)}`},zn=e=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(e);if(!s)throw Error("Invalid HSL string");return Yn(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},qn=(e,t)=>getComputedStyle(e).getPropertyValue(t),yd=(e,t)=>zn(qn(e,t)),Wn="studio.tools.preview",bd="studio.relax.store.validation",Zn="studio.log.debug",Jn="studio.log.info",vd={profiles:[Wn]};var $n;const wd=(($n=globalThis.getKosConfig)==null?void 0:$n.call(globalThis))||JSON.stringify(vd),Qn=JSON.parse(wd);globalThis.kosConfig=Qn;const Yo=Qn,Xn=()=>Yo.profiles||[],po=e=>Xn().includes(e),Md=()=>Yo.logging||!1,_d=(e,t)=>{const s={...e};return s.id&&delete s.id,s},mo=(e,t,s=_d)=>{const o=s(e,t);v.runInAction(()=>{Object.assign(t,o)})},to=new Map,ei={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)})}},Ed=()=>{const e=po(Zn),t=po(Jn);return e?"DEBUG":t?"INFO":void 0},ti=()=>{const e=ee(),t=Ed(),o=e.kosLogLevel??t??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return o||"WARN"},si=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",oi=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",ri="ws-log",Id=T.methodFactory,ni=si(),Td=oi();T.methodFactory=function(e,t,s){const o=Id(e,t,s);return function(r,n){var l;const i=s?String(s):"",c=i?`[${String(i).substring(i.lastIndexOf(":")+1)}] | `:"[root] | ";o(`${c}${r}`,n||""),(l=globalThis==null?void 0:globalThis.kosConfig)!=null&&l.logging&&globalThis.kosLog&&(s!==ri||ni&&Td)&&globalThis.kosLog(`UI: ${c}${r}`)}};let ii=ti();T.setLevel(ii);window.setKosLogLevel=e=>{ii=e,T.setLevel(e)};const gs=T.getLogger(ri);window.enableKosMessageLog=()=>{gs.setLevel(T.levels.INFO)};window.disableKosMessageLog=()=>{gs.setLevel(T.levels.ERROR)};ni?window.enableKosMessageLog():window.disableKosMessageLog();const $d=["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(";"),Od=["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(";"),Zt=e=>t=>{T.getLevel()<=e&&t()},f={...T,ifDebug:Zt(T.levels.DEBUG),ifInfo:Zt(T.levels.INFO),ifWarn:Zt(T.levels.WARN),ifError:Zt(T.levels.ERROR),getLogger:e=>T.getLogger(`kos::${e}`),createLogger:({name:e,group:t})=>T.getLogger(`${t?`${t}:`:"kos"}::${e}`),wsSend:(...e)=>{const t=String(e).replace(/\n/g,"\\n");gs.info(`%c⬆ ${t}`,$d)},wsReceive:(...e)=>{const t=String(e).replace(/\n/g,"\\n");gs.info(`%c⬇ ${t}`,Od)}},Dd=f.createLogger({name:"kos-dependency-manager"});class Sd{constructor(){a(this,"_usedByCache",new Map);a(this,"_usesCache",new Map)}add(t,s){ei.cancelDeletion(s);const o=this._usedByCache.get(s)||[];o.includes(t)||o.push(t),this._usedByCache.set(s,o);const r=this._usesCache.get(t)||[];r.includes(s)||r.push(s),this._usesCache.set(t,r)}remove(t,s){const o=this._usedByCache.get(s)||[];this._usedByCache.set(s,o.filter(n=>n!==t));const r=this._usesCache.get(t)||[];this._usesCache.set(t,r.filter(n=>n!==s))}canDestroy(t){const s=this._usedByCache.get(t);return s!=null&&s.length?(Dd.info(`Model ${t} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}var y=(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))(y||{}),D=(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))(D||{});const Hr=f.createLogger({name:"kos-model-cache"});class Cd{constructor(t=[]){a(this,"_modelsById",v.observable.map(new Map));a(this,"_toDelete",new Map);a(this,"_preloaded",[]);a(this,"_isPreloaded",!1);this.preloadKeys=t}get models(){return Array.from(this._modelsById.values()).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?(Hr.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(Hr.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),t(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const so=new Map,Yr=new Map,oo=new Map,ro=new Map,zo=(e,t)=>{ai[e]=t},ai={indexExtension:{registerIndexExtension:(e,t)=>{const s=ro.get(e)||{};Object.assign(s,t),ro.set(e,t)},loadIndexExtensions:e=>ro.get(e)||{}},loader:{registerLoader:(e,t)=>{Yr.set(e,t)},executeLoader:async(e,t)=>{const s=Yr.get(e);if(s)return await s(t)}},propertyMapper:{registerPropertyMapper:(e,t)=>{oo.set(e,t)},hasMapper:e=>oo.has(e),executeMapper:(e,t,s)=>{const o=oo.get(e);return o?o(t,s):""}},dataMapper:{registerDataMapper:(e,t)=>{const s=so.get(e)||[];s.push(t),so.set(e,s)},executeMapper:async(e,t,s)=>{const o=so.get(e);if(!o)return{};const r={};for(const n of o){const i=await n(t,s);Object.assign(r,i)}return r}}},A=ai;function ci(e,t){return`${jo}${e}${t?`/${t}`:`/${e}`}`}function li(e){return`${jo}${e}`}var x=(e=>(e.INIT="init",e.LOAD="load",e.READY="ready",e.ACTIVATE="activate",e.ONLINE="online",e))(x||{});const Ad=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:x},Symbol.toStringTag,{value:"Module"}));function zr(e){const t=[];return new Promise((s,o)=>{for(const{condition:r,onMatch:n}of e){const i=v.when(r,()=>{t.forEach(c=>c());try{n==null||n(),s()}catch(c){o(c)}});t.push(i)}})}const G=Symbol("SubscriptionHandlers"),P=Symbol("DependencyModels"),wt=Symbol("FutureService"),Mt=Symbol("ChildModels"),_t=Symbol("ParentModel"),Et=Symbol("LogConfig"),is=Symbol("ReferenceConfig"),di=Symbol("KosModelSymbol"),$e=Symbol("ModelEffects"),ie=(e,t)=>{e[Mt]=e[Mt]||{},e[Mt][t]=!0},Se=e=>`{PROP_${String(e)}}`,Rd=e=>`{PROP_${String(e)}}`,Ld=Se("kosParentId"),Us=e=>t=>{t[_t]=t[_t]||{};const s=(e==null?void 0:e.parentId)||Ld;t[_t]={parentId:s}},Ge=({value:e,modelId:t,modelData:s})=>{let o=e;if(Array.isArray(o))return[...e];if(typeof o!="string"&&typeof o!="object")return o;if(typeof o=="object")o=Object.keys(o).reduce((r,n)=>(r[n]=Ge({value:o[n],modelId:t,modelData:s}),r),{});else if(typeof o=="string"){const r=new RegExp(".*({PROP_(.+)})");let n=o!=null&&o.includes(hs)?o.replace(hs,t):o;const i=n.match(r);if(i&&s&&(Object.getOwnPropertyNames(s).includes(i[2])||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(i[2]))){const c=s[i[2]];n=c?n.replace(i[1],c):void 0}return n}else return o;return o},Pd=f.createLogger({name:"kos-model"});function kd(e,t,s){var n;const o=(n=e[_t])==null?void 0:n.parentId;if(!o)return;const r=Ge({value:o,modelData:s,modelId:t});r&&typeof r=="string"&&k.setParentContext(t,r)}function xd(e){const t=e[wt];t&&Object.entries(t).forEach(([s,{handler:o}])=>{e[s]=o})}function Fd(e,t){const s=e[P]||{};Object.entries(s).forEach(([o,r])=>{const n=Ge({value:r.id||r.modelType,modelData:e,modelId:t}),i=Object.entries((r==null?void 0:r.options)||{}).reduce((c,[l,d])=>(c[l]=Ge({value:d,modelData:e,modelId:t}),c),{});if(typeof n=="string"){if(!r.lazy){const c=E.getInstance().modelManager.createModelInstance(r.modelType,n,i);e[o]=c.data}E.getInstance().modelManager.addDependency(t,n)}})}function Nd(e){try{return v.makeAutoObservable(e)}catch(t){return Pd.error("Failed to make observable:",t),e}}const Ud={construct(e,t){var c;const[s,o={}]=t,r=k.createContext(s);kd(e,s,o);const n=f.createLogger({name:e.prototype.modelTypeId,group:((c=e[Et])==null?void 0:c.group)??"kos-model"}),i=new e(s,o,{logger:n,kosContext:r});return xd(i),Fd(i,s),Nd(i)}};function O(e){return t=>{var o,r;const s=t;return s.prototype.modelTypeId=e,s.prototype[di]=!0,(o=s.prototype)[G]??(o[G]={}),(r=s.prototype)[P]??(r[P]={}),f.ifDebug(()=>{f.debug(`Registering model with id ${e}`)}),new Proxy(s,Ud)}}const jd=({modelType:e})=>t=>{Us()(t),O(e)(t)};function Bd(e,t,s){const o=s.value;s.value=function(...r){const n=k.getContext(this.id);return r.push(n),o.apply(this,r)}}const Kd=({group:e}={group:""})=>t=>{t[Et]=t[Et]||{},t[Et]={group:e}};function ui(e){return(t,s,o)=>{t[$e]=t[$e]||{},t[$e][s]={dependencies:e==null?void 0:e.dependencies,value:o.value},o.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const Gd=e=>(t,s)=>{t[is]=t[is]||{},t[is][s]=e},Ce=({modelType:e,id:t,options:s,lifecycle:o})=>(r,n)=>{r[P]=r[P]||{},r[P][n]={modelType:e,id:t,options:s,lifecycle:o||x.INIT}},Vd=({topic:e,handler:t,websocket:s=!1,condition:o=()=>!0})=>r=>{r[G]=r[G]||{},Array.isArray(e)?e.forEach(n=>{r[G][n]={websocket:s,handler:t,condition:o}}):r[G][e]={websocket:s,handler:Vn(r,v.action(t),200),condition:o}};function R({topic:e,condition:t=(d,u)=>!0,transform:s=d=>d,websocket:o=!1,fos:r=!1,bridge:n=!1,skipParse:i=!1,lifecycle:c,destinationAddress:l}){return(d,u,h)=>{d[G]=d[G]||{},Array.isArray(e)?e.forEach(p=>{d[G][p]={websocket:o,fos:r,bridge:n,handler:h.value,condition:t,transform:s,lifecycle:c,skipParse:i,destinationAddress:l}}):d[G][e]={websocket:o,fos:r,bridge:n,handler:h.value,condition:t,transform:s,lifecycle:c,skipParse:i,destinationAddress:l}}}const hi=5e3;class Hd extends Error{constructor(s,o){super(s);a(this,"model");this.model=o}}const gi=(e,t,s)=>{let o;return{promise:new Promise((i,c)=>{o=setTimeout(()=>{f.error(`Model ${t.modelId} - ${t.modelTypeName} - ${s} timed out after ${e}ms`),c(new Hd(`${t.modelId} - ${t.modelTypeName} - ${s}`,t))},e)}),cancel:()=>{o&&clearTimeout(o)}}},fi=e=>e.fsm.transitionTo(D.GO_ACTIVE,y.ACTIVE),pi=e=>e.whenReady(),mi=e=>e.fsm.transitionTo(D.LOAD,y.LOADED),Yd=e=>e.fsm.transitionTo(D.UNLOAD,y.UNLOADED),yi=e=>e.fsm.transitionTo(D.INITIALIZE,y.INITIALIZED);var qo=(e=>(e.ACTIVE="active",e.READY="ready",e.LOAD="load",e.UNLOAD="unload",e.INIT="init",e))(qo||{});const as={active:fi,ready:pi,load:mi,init:yi},bi=(e,t)=>{const s=t.id||t.modelType,o=Ge({value:s,modelData:e.modelData,modelId:e.modelId});f.debug(`activating dependent model ${t.modelType} with id ${o}`);const r=Object.keys((t==null?void 0:t.options)||{}).reduce((i,c)=>{const l=t.options[c];return i[c]=Ge({value:l,modelData:e.modelData,modelId:e.modelId}),i},{});return{dependentModel:E.getInstance().modelManager.createModelInstance(t.modelType,o,r),dataModelId:o}},vi=(e,t=x.READY)=>{var r;const s=((r=e.modelData)==null?void 0:r[P])||{};return Object.keys(s).length===0?(f.debug(`${e.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===t).map(n=>{const i=s[n],{dependentModel:c,dataModelId:l}=bi(e,i);e.modelData[n]=c.data,f.debug(`waiting for dependent model ${i.modelType} with id ${l} - waiting for WHENREADY`);const d=async(p,w,b)=>{var _;await((_=p.whenReady)==null?void 0:_.call(p)),f.debug(`dependent model ${w} with id ${b} - READY`)},{promise:u,cancel:h}=gi(hi,e,e.status);return Promise.race([d(c.model,i.modelType,l).then(()=>{h()}).catch(p=>{console.error(`Error waiting for dependent model ${i.modelType} with id ${l}:`,p),h()}),u])}).filter(n=>!!n)},wi=async(e,t,s,o)=>{if(f.debug(`Execute lifecycle with ${t.length} models`),t.length===0){f.debug(`${e.modelId} has no children. Returning`);return}if(!s){f.error(`${e.modelId} is not transitioning with a valid target ${s}`);return}const r=t.map(c=>{let l;return as[s]&&c?l=as[s](c):(c||f.error("model is undefined. This shouldn't happen"),as[s]||f.error(`There is no promise in the Transition Map for ${s}`)),{promise:l,modelId:c==null?void 0:c.modelId,model:c,type:c==null?void 0:c.modelTypeName,status:c==null?void 0:c.status}}).filter(c=>c.promise?c.model?!0:(f.error(`No model found ${c.modelId}`),!1):(f.error(`No promise found ${c.modelId}`),!1)),i=(await Promise.allSettled(r.map(c=>{var u;const{promise:l,cancel:d}=gi(hi,c.model,c.status);return Promise.race([(u=c.promise)==null?void 0:u.then(()=>{d()}).catch(h=>{f.error(`Model ${c.modelId} - ${c.type} failed to transition to ${s}: ${h.message}`),d()}),l])}))).filter(c=>c.status==="rejected");i.length>0&&f.error(`Model ${e.modelId} had ${i.length} failed child models on ${o}`)},Mi=async(e,t,s)=>{await wi(e,e.getChildren().filter(o=>!!o),t,s)},ct=async(e,t)=>{const o=(await Promise.allSettled(vi(e,t))).filter(r=>r.status==="rejected");o.length&&(f.error(`There were ${o.length} failed dependent models on ${t}`),f.error(o))},zd=e=>typeof e.toJSON=="function",It=e=>e[P]!==void 0,Wo=e=>e.revision!==void 0&&e.index!==void 0,_i=e=>{if(e){if(It(e))return e;if(Wo(e))return e.data;if(e instanceof Map||e instanceof v.ObservableMap||e instanceof Set)return Array.from(e.values()).filter(It);if(Array.isArray(e))return e.filter(It)}};function qd(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 o of s)o in e&&Object.defineProperty(e,o,{enumerable:!1});Object.defineProperty(e,"debugState",{enumerable:!1,configurable:!0,get(){var o,r,n;return{id:e.modelId,type:e.modelTypeName,initialized:e.initialized,loaded:e.loaded,status:e.status,onlineStatus:e.onlineStatus,activeStatus:e.activeStatus,companions:(r=(o=e.companionManager)==null?void 0:o.all())==null?void 0:r.map(i=>i.modelTypeName),children:(n=e.getChildren)==null?void 0:n.call(e).map(i=>i.modelId),effects:!!e.effectManager,subs:!!e.subscriptionManager}}}),Wd(e.modelData,e.modelTypeName,e.modelId,e)}function Wd(e,t,s,o){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 c,l,d;const r=((c=o.getChildren)==null?void 0:c.call(o))||[],n=((l=o.companionManager)==null?void 0:l.all())||[],i=o.modelData[P]||{};return{id:s,type:t,companions:{count:n.length,data:n.map(u=>({type:u.modelTypeName,id:u.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(u=>({id:u.id||u.modelType,type:u.modelType,options:u.options,lifecycle:u.lifecycle}))},children:{count:r.length,data:r.map(u=>({id:u.modelId,type:u.modelTypeName}))},data:((d=e.toJSON)==null?void 0:d.call(e))||{},subs:!!o.subscriptionManager}}}),Object.defineProperty(e,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const r={};for(const n of Object.keys(e))if(!(n.startsWith("_")||typeof e[n]=="function"))try{const i=e[n];It(i)?r[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:Wo(i)?r[`[KOS Container] ${n}`]=typeof i.toJSON=="function"?i.toJSON():["Container"]:Array.isArray(i)?r[n]=`[Array(${i.length})]`:typeof i=="object"&&i!==null?r[n]=JSON.parse(JSON.stringify(i)):r[n]=i}catch{r[n]="[unreadable]"}return r}})}class Zd{constructor(t){this.model=t}resolve(){const t=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(t).map(o=>this.model.modelManager.getModelById(o.id||"")).filter(o=>o&&o.status!==y.FAILED).filter(o=>!!o);return s.forEach(o=>{try{k.setParentContext(o.modelId,this.model.modelId)}catch(r){console.error(`Failed to set parent context for ${o.modelId} under ${this.model.modelId}`,r)}}),s}getResolvedDecoratedChildren(){var s;const t=((s=this.model.modelData)==null?void 0:s[Mt])||{};return Object.keys(t).map(o=>_i(this.model.modelData[o])).filter(o=>!!o).flat()}getAdditionalChildren(){var t,s;return((s=(t=this.model.modelData)==null?void 0:t.getChildren)==null?void 0:s.call(t))||[]}}class Jd{constructor(t){a(this,"companions",new v.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 Qd{constructor(t,s,o,r){a(this,"disposers",[]);this.modelTypeName=t,this.modelId=s,this.modelData=o,this.log=r}setup(){var s;const t=((s=this.modelData)==null?void 0:s[$e])||{};for(const o of Object.keys(t)){const{value:r,dependencies:n,options:i}=t[o],c=r.bind(this.modelData),l=()=>{this.log.info(`Running effect ${o} for ${this.modelTypeName} (${this.modelId})`),v.runInAction(()=>c())},d=n?v.reaction(()=>n(this.modelData),l,{fireImmediately:!!(i!=null&&i.fireImmediately)}):v.autorun(l);this.disposers.push(d)}}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 Xd=f.createLogger({name:"model-active-machine"}),eu=e=>{const t=m.createMachine(y.INACTIVE,{[y.FAILED]:m.state(m.transition(D.GO_ACTIVE,y.ACTIVATING)),[y.INACTIVE]:m.state(m.transition(D.GO_ACTIVE,y.ACTIVATING)),[y.ACTIVATING]:m.invoke(()=>(e.activeStatus=y.ACTIVATING,e.activate()),m.transition("done",y.ACTIVE,m.action(()=>{e.activeStatus=y.ACTIVE})),m.transition("error",y.FAILED,m.action(()=>{e.activeStatus=y.FAILED}))),[y.ACTIVE]:m.state(m.transition(D.GO_INACTIVE,y.DEACTIVATING)),[y.DEACTIVATING]:m.invoke(()=>(e.activeStatus=y.DEACTIVATING,e.deactivate()),m.transition("done",y.INACTIVE,m.action(()=>{e.activeStatus=y.INACTIVE})),m.transition("error",y.FAILED,m.action(()=>{e.activeStatus=y.FAILED})))});return{service:m.interpret(t,o=>Xd.debug(o.machine.current)),machine:t}},qr=f.createLogger({name:"model-online-machine"}),tu=e=>{const t=m.createMachine(y.OFFLINE,{[y.ONLINE]:m.state(m.transition(D.GO_OFFLINE,y.OFFLINE,m.action(async()=>{await e.offline(),e.onlineStatus=y.OFFLINE}))),[y.OFFLINE]:m.state(m.transition(D.GO_ONLINE,y.ONLINE,m.action(async()=>{qr.debug(`Going online with model ${e.modelId}`),await e.online(),e.onlineStatus=y.ONLINE,await e.fsm.transitionTo(D.INITIALIZE,y.INITIALIZED)})))}),s=m.interpret(t,o=>qr.debug(o.machine.current));return{machine:t,service:s}},su=e=>{var o;const t=eu(e).service,s=tu(e).service;return m.createMachine(y.CREATING,{[y.CREATING]:m.state(m.transition(D.CREATE,y.CREATED)),[y.CREATED]:m.state(m.immediate(y.INITIALIZING)),[y.INITIALIZING]:m.invoke(()=>(z(()=>{e.status=y.INITIALIZING}),e.init()),m.transition("done",y.INITIALIZED,m.action(()=>{e.status=y.INITIALIZED})),m.transition("error",y.FAILED,m.action(()=>{f.error(`Model ${e.modelId} - ${e.modelTypeName} failed to initialize. Transitioning to FAILED state.`),e.status=y.FAILED}))),[y.INITIALIZED]:m.state(m.immediate(y.LOADING)),[y.LOADING]:m.invoke(()=>(z(()=>{e.status=y.LOADING}),e.load()),m.transition("done",y.LOADED,m.action(()=>{e.status=y.LOADED})),m.transition("error",y.FAILED,m.action(()=>{e.status=y.FAILED}))),[y.LOADED]:m.state(m.immediate(y.READYING),m.transition(D.UNLOAD,y.UNLOADING)),[y.RESETTING]:m.invoke(()=>{var r;return z(()=>{e.status=y.RESETTING}),(r=e.unload)==null||r.call(e),e.load()},m.transition("done",y.LOADED,m.action(()=>{e.status=y.LOADED}))),[y.READYING]:m.invoke(()=>(z(()=>{e.status=y.READYING}),e.ready()),m.transition("done",y.READY,m.action(()=>{z(()=>{e.status=y.READY}),s.send(D.GO_ONLINE)})),m.transition("error",y.FAILED,m.action(()=>{e.status=y.FAILED}))),[y.READY]:m.state(m.transition(D.UNLOAD,y.UNLOADED,m.action((o=e.unload)==null?void 0:o.bind(e))),m.transition(D.RESET,y.RESETTING),m.transition(D.GO_ONLINE,y.READY,m.action(()=>{s.send(D.GO_ONLINE)})),m.transition(D.GO_OFFLINE,y.READY,m.action(()=>{s.send(D.GO_OFFLINE)})),m.transition(D.GO_ACTIVE,y.READY,m.action(()=>{t.send(D.GO_ACTIVE)})),m.transition(D.GO_INACTIVE,y.READY,m.action(()=>{t.send(D.GO_INACTIVE)}))),[y.UNLOADED]:m.state(),[y.FAILED]:m.state()})},ou=f.createLogger({name:"kos-model-lifecycle"}),ru=e=>({service:m.interpret(su(e),s=>ou.debug(`state machine for model ${e.modelId}: ${s.machine.current});`))});class nu{constructor(t,s){a(this,"disposer");a(this,"service");this.model=t,this.log=s;const o=ru(t);this.service=o.service,this.service.send(D.CREATE)}get current(){return this.service.machine.current}async transitionTo(t,s,o=y.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 c;(c=this.disposer)==null||c.call(this),this.disposer=v.when(()=>{const l=this.getTransitionStatusFor(s);return l===s||l===o},()=>{this.getTransitionStatusFor(s)===o?(this.log.error(`Model ${this.model.modelId} entered error state ${o} 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[y.ACTIVE,y.INACTIVE].includes(t)?this.model.activeStatus:this.model.status}}class iu{static create({modelId:t,modelTypeName:s,component:o}){const r=[o??"kos",s,t].filter(Boolean).join(".");return f.createLogger({name:r})}}class au{constructor(t){a(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 cu{constructor(t,s){a(this,"unsubscribers",[]);this.model=t,this.log=s}register(){const t=this.model.modelId,s=U("/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(D.GO_ONLINE,y.ONLINE)}),o=U("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${t} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(D.GO_OFFLINE,y.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(o.unsubscribe)}dispose(){this.unsubscribers.forEach(t=>t()),this.unsubscribers=[]}}var Ei=(e=>(e.GET="GET",e.PUT="PUT",e.POST="POST",e.DELETE="DELETE",e))(Ei||{});const Ii=({path:e,requestId:t,method:s,destinationAddress:o})=>{let r=`${Fs}:${s}
|
|
2
2
|
`;return r+=`topic:${e}
|
|
3
3
|
`,r+=`${Qe}:${e}
|
|
4
4
|
`,r+=`${Kt}:${t}
|
|
5
5
|
`,o&&(r+=`${fe}:${o}
|
|
6
6
|
`),r+=`${le}:kos.studio.request
|
|
7
7
|
`,r+=`
|
|
8
|
-
`,r},
|
|
8
|
+
`,r},Ti=({path:e,requestId:t,method:s,destinationAddress:o,ordered:r,tracker:n})=>{let i=`${Dn}:/http${e}
|
|
9
9
|
`;return i+=`${Fs}:${s}
|
|
10
10
|
`,i+=`${Qe}:${e}
|
|
11
|
-
`,i+=`${
|
|
11
|
+
`,i+=`${Rn}:${t}
|
|
12
12
|
`,o&&(i+=`${fe}:${o}
|
|
13
|
-
`),r&&(i+=`${
|
|
14
|
-
`),n&&(i+=`${
|
|
13
|
+
`),r&&(i+=`${No}:true
|
|
14
|
+
`),n&&(i+=`${Uo}:${n}
|
|
15
15
|
`),i+=`${le}:fos.http.request
|
|
16
16
|
`,i+=`
|
|
17
|
-
`,i}
|
|
17
|
+
`,i},$i=({path:e,requestId:t,method:s,destinationAddress:o,ordered:r,tracker:n,bridge:i,headers:c})=>{let l=`${Fs}:${s}
|
|
18
18
|
`;return l+=`${Qe}:${e}
|
|
19
19
|
`,l+=`${Kt}:${t}
|
|
20
20
|
`,o&&(l+=`${fe}:${o}
|
|
21
|
-
`),r&&(l+=`${
|
|
22
|
-
`),n&&(l+=`${
|
|
21
|
+
`),r&&(l+=`${No}:true
|
|
22
|
+
`),n&&(l+=`${Uo}:${n}
|
|
23
23
|
`),c&&Object.keys(c).forEach(d=>{l+=`${d}:${c[d]}
|
|
24
24
|
`}),l+=`${le}:${i?"fos":"kos"}.http.request
|
|
25
25
|
`,l+=`
|
|
26
|
-
`,l},ve=(e,t)=>{let s=e;return t&&(s+=t),s};function
|
|
26
|
+
`,l},ve=(e,t)=>{let s=e;return t&&(s+=t),s};function yo(e){const t={...e};return{append(s,o){t[s]=o},delete(s){delete t[s]},get(s){return t[s]},forEach(s){Object.keys(t).forEach(o=>s(t[o],o,this))},has(s){return Object.hasOwn(t,s)},set(s,o){t[s]=o},keys(){return Object.keys(t)},values(){return Object.values(t)},entries(){return Object.entries(t)}}}function bo(e){let t=!1;return window.ReadableStream?new ReadableStream({start(o){function r(){return Promise.resolve({done:t,value:e}).then(({done:n,value:i})=>{if(n){o.close();return}o.enqueue(i),t=!0,r()})}r()}}):e}const Oi=({path:e,requestId:t,destinationAddress:s})=>{let o=`topic:${e}
|
|
27
27
|
`;return o+=`${Qe}:${e}
|
|
28
28
|
`,o+=`${Kt}:${t}
|
|
29
29
|
`,o+=`${fe}:${s}
|
|
30
30
|
`,o+=`${le}:kos.studio.request
|
|
31
31
|
`,o+=`
|
|
32
|
-
`,o}
|
|
32
|
+
`,o},Di=({requestId:e,destinationAddress:t,requestType:s,headers:o})=>{let r=`${Kt}:${e}
|
|
33
33
|
`;return r+=`${fe}:${t}
|
|
34
34
|
`,r+=`${le}:${s}
|
|
35
35
|
`,o&&Object.keys(o).forEach(n=>{r+=`${n}:${o[n]}
|
|
36
36
|
`}),r+=`
|
|
37
|
-
`,r},
|
|
37
|
+
`,r},lu=(e,t)=>{const s=e,o=ve(Di(t),typeof s=="string"?s:JSON.stringify(s)),r=E.getInstance().transport.socket;r?(f.debug("Sending message",o),r.socket.send(o)):f.error("socket transport is not initialized")},Si=({path:e,responseId:t,status:s,destinationAddress:o})=>{let r=`topic:${e}
|
|
38
38
|
`;return r+=`${Qe}:${e}
|
|
39
39
|
`,t&&(r+=`${Ns}:${t}
|
|
40
|
-
`),r+=`${
|
|
40
|
+
`),r+=`${Fo}:${s}
|
|
41
41
|
`,r+=`${fe}:${o}
|
|
42
42
|
`,r+=`${le}:kos.studio.response
|
|
43
43
|
`,r+=`
|
|
44
|
-
`,r},
|
|
44
|
+
`,r},du=(e,t)=>{const s=e,o=ve(Oi(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},uu=(e,t)=>{const s=t.responseId?{status:t.status,data:e}:e,o=ve(Si(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},Ci=({topic:e})=>{let t=`topic:${e}
|
|
45
45
|
`;return t+=`${le}:kos.broker.send
|
|
46
46
|
`,t+=`
|
|
47
|
-
`,t},
|
|
47
|
+
`,t},Ai=({responseId:e,destinationAddress:t,type:s,sourceAddress:o,status:r})=>{let n=`${Ns}:${e}
|
|
48
48
|
`;return n+=`${fe}:${t}
|
|
49
|
-
`,n+=`${
|
|
49
|
+
`,n+=`${Sn}:${o}
|
|
50
50
|
`,n+=`${le}:${s??"kos.message.request"}
|
|
51
|
-
`,n+=`${
|
|
52
|
-
`,n+=`${
|
|
53
|
-
`,n+=`${
|
|
51
|
+
`,n+=`${Fo}:${r}
|
|
52
|
+
`,n+=`${Cn}:application/json
|
|
53
|
+
`,n+=`${An}:no-cache
|
|
54
54
|
`,n+=`
|
|
55
|
-
`,n},
|
|
55
|
+
`,n},Ri=({topic:e,responseId:t,destinationAddress:s,type:o})=>{let r=`topic:${e}
|
|
56
56
|
`;return t&&(r+=`${Ns}:${t}
|
|
57
57
|
`),r+=`${fe}:${s}
|
|
58
58
|
`,r+=`${le}:${o??"kos.message.request"}
|
|
59
59
|
`,r+=`
|
|
60
|
-
`,r},
|
|
60
|
+
`,r},hu=({msg:e,options:t})=>{const s=e,o=ve(Ci(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},Li=({msg:e,options:t})=>{const s=e,o=ve(Ri(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},Pi=({msg:e,options:t})=>{const s=e,o=ve(Ai(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},vo=(e,t)=>{try{return t?e.body??e:JSON.parse(e.body)}catch{return e.body||e}};class gu extends WebSocket{constructor(t){super(t)}}function Wr(e){const t=`
|
|
61
61
|
|
|
62
62
|
`,s=`
|
|
63
|
-
`,o=/:(.*)/s,[r,n]=e.split(t).map(c=>c.trim());return{headers:r.split(s).reduce((c,l)=>{const[d,u]=l.split(o).map(h=>h.trim());return d&&u&&(c[d]=u),c},{}),body:n}}function
|
|
63
|
+
`,o=/:(.*)/s,[r,n]=e.split(t).map(c=>c.trim());return{headers:r.split(s).reduce((c,l)=>{const[d,u]=l.split(o).map(h=>h.trim());return d&&u&&(c[d]=u),c},{}),body:n}}function fu(e){const t=`
|
|
64
64
|
|
|
65
65
|
`,s=`
|
|
66
|
-
`,o=/:(.*)/s,[,r,n]=e.split(t).map(c=>c.trim());return{headers:r.split(s).reduce((c,l)=>{const[d,u]=l.split(o).map(h=>h.trim());return d&&u&&(c[d]=u),c},{}),body:n}}class
|
|
66
|
+
`,o=/:(.*)/s,[,r,n]=e.split(t).map(c=>c.trim());return{headers:r.split(s).reduce((c,l)=>{const[d,u]=l.split(o).map(h=>h.trim());return d&&u&&(c[d]=u),c},{}),body:n}}class Zo{constructor({host:t,port:s,protocol:o,alias:r,onConnectionEstablished:n,onConnectionLost:i,Transport:c=gu}){a(this,"host");a(this,"port");a(this,"protocol");a(this,"socket");a(this,"connectionEstablished");a(this,"alias");a(this,"onConnectionEstablished");a(this,"onConnectionLost");a(this,"offlineMessages",[]);a(this,"oldSend");this.host=t,this.port=s,this.protocol=o,this.onConnectionEstablished=n,this.onConnectionLost=i,this.alias=r,this.socket=new c(`${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,U("/mock/msg/receive",l=>{var d,u;if(l!=null&&l.body){f.wsReceive(l==null?void 0:l.body);const h={data:l.body};(u=(d=this.socket)==null?void 0:d.onmessage)==null||u.call(d,h)}}),v.makeObservable(this,{connectionEstablished:v.observable})}addOfflineMessage(t){this.offlineMessages.push({msg:t})}processMessageEvent(t){const{data:s}=t;return Wr(s)}onMessage(t){try{f.debug("webSocketTransport: onMessage received");const{headers:s,body:o}=this.processMessageEvent(t);f.wsReceive(t.data);const r=s.subscription||s[this.RESPONSE_ID_HEADER]||s.topic||s.type;if(r){let n=o,i=s;if(r==="kos.sniffer.msg"){const{headers:c,body:l}=fu(t.data);n=l,i={...s,...c}}F(r,n,i)}}catch(s){f.error("onMessage exception",s.message,s.stack)}}onOpen(t){f.info("websocket connection opened"),this.socket=t.currentTarget,v.runInAction(()=>{var s;this.connectionEstablished=!0,this.alias&&this.socket.send(`type:kos.addr.alias
|
|
67
67
|
alias:${this.alias}
|
|
68
68
|
|
|
69
|
-
`),f.debug(`sending ${this.offlineMessages.length} offline FOS messages`),this.offlineMessages.forEach(o=>{var r;f.debug(`sending offline message ${o.msg}`),(r=this.socket)==null||r.send(o.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(){this.socket&&this.socket.close(),v.runInAction(()=>{this.connectionEstablished=!1}),f.debug("websocket disconnected. Attempting calling callback"),this.onConnectionLost&&setTimeout(this.onConnectionLost,2500)}send(t){var s,o;if(f.wsSend(t),window.kosLogEvents){const{headers:r,body:n}=
|
|
69
|
+
`),f.debug(`sending ${this.offlineMessages.length} offline FOS messages`),this.offlineMessages.forEach(o=>{var r;f.debug(`sending offline message ${o.msg}`),(r=this.socket)==null||r.send(o.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(){this.socket&&this.socket.close(),v.runInAction(()=>{this.connectionEstablished=!1}),f.debug("websocket disconnected. Attempting calling callback"),this.onConnectionLost&&setTimeout(this.onConnectionLost,2500)}send(t){var s,o;if(f.wsSend(t),window.kosLogEvents){const{headers:r,body:n}=Wr(String(t));F(Gt.SEND,{headers:r,body:n})}if(window.kosTopicIntercept&&window.kosEnableMocks){const{handler:r,requestId:n}=window.kosTopicIntercept(t);if(r){t=`mocked:true
|
|
70
70
|
${t}`;const c={data:`mocked:true
|
|
71
|
-
${r(n)}`};(o=(s=this.socket)==null?void 0:s.onmessage)==null||o.call(s,c)}else this.oldSend.call(this.socket,t)}else this.oldSend.call(this.socket,t)}}class
|
|
71
|
+
${r(n)}`};(o=(s=this.socket)==null?void 0:s.onmessage)==null||o.call(s,c)}else this.oldSend.call(this.socket,t)}else this.oldSend.call(this.socket,t)}}class pu{constructor(t){a(this,"addEventListener");a(this,"dispatchEvent");a(this,"removeEventListener");a(this,"_onclose");a(this,"_onerror");a(this,"_onmessage");a(this,"_onopen");a(this,"messageQueue",[]);a(this,"isSending",!1);T.debug(`called Bridge Transport with addr ${t}`);const s=this;globalThis.kosWindowWebsocketRecv=o=>{if(s.onmessage){const r={data:o};s.onmessage(r)}},T.debug("Opening bridge transport"),globalThis.kosWindowWebsocketOpen(),T.debug("Opened bridge transport"),this._onclose=null,this._onerror=null,this._onmessage=null,this._onopen=null,this.addEventListener=()=>T.debug("not implemented"),this.dispatchEvent=()=>T.debug("not implemented"),this.removeEventListener=()=>T.debug("not implemented")}close(){T.debug("closing")}sendNextMessage(){if(this.messageQueue.length>0){const t=this.messageQueue.shift();globalThis.kosWindowWebsocketSend(t),setTimeout(()=>this.sendNextMessage(),1)}else this.isSending=!1}enqueueMessage(t){this.messageQueue.push(t),this.isSending||(this.isSending=!0,this.sendNextMessage())}send(t){globalThis.kosWindowWebsocketSend(t)}get onmessage(){return this._onmessage}set onmessage(t){this._onmessage=t}get onopen(){return this._onopen}set onopen(t){this._onopen=t}get onclose(){return this._onclose}set onclose(t){this._onclose=t}get onerror(){return this._onerror}set onerror(t){this._onopen=t}}class mu extends Zo{constructor({host:s,port:o,alias:r}){super({host:s,port:o,Transport:pu,alias:r,protocol:"kos://"});a(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}class yu extends Zo{constructor({host:s,port:o}){super({host:s,port:o,protocol:"ws://"});a(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="requestId"}}class bu extends Zo{constructor({host:s,port:o,protocol:r,onConnectionEstablished:n,onConnectionLost:i,alias:c}){super({host:s,port:o,onConnectionEstablished:n,onConnectionLost:i,alias:c,protocol:r});a(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 wo{static build({host:t,port:s,protocol:o,fos:r,alias:n,onConnectionEstablished:i,onConnectionLost:c}){return f.debug("initializing websocket connection"),f.warn(`kosWindowWebsocketOpen: ${globalThis.kosWindowWebsocketOpen?"true":"false"}`),f.warn(`fos: ${r?"true":"false"}`),window.kosMockWs||globalThis.kosWindowWebsocketOpen&&!r?(f.warn("Using bridged message transport"),new mu({host:t,port:s,protocol:o,onConnectionEstablished:i,onConnectionLost:c,alias:n})):r?new yu({host:t,port:s,protocol:o,alias:n,onConnectionEstablished:i,onConnectionLost:c}):new bu({host:t,port:s,protocol:o,alias:n,onConnectionEstablished:i,onConnectionLost:c})}}const vu=ee();vu.fos&&(window.kosUseFos=!0);const Zr=process.env.KOS_FOS_PORT;window.kosUseFos=!!(window.kosUseFos||process.env.KOS_USE_FOS==="true");window.kosFosPort=Zr?parseInt(Zr):0;const Ee=T.getLogger("web-socket-transport");var ki=(e=>(e.NOT_INITIALIZED="not_initialized",e.INITIALIZED="initialized",e.OFFLINE="OFFLINE",e.ONLINE="ONLINE",e))(ki||{}),Tt=(e=>(e.CONNECTED="websocket.connected",e.DISCONNECTED="websocket.disconnected",e.RELOAD="websocket.reload",e))(Tt||{});class Vt{constructor({host:t="localhost",port:s=8080,protocol:o="ws://",token:r,initialize:n,alias:i,fos:c}){a(this,"host");a(this,"port");a(this,"protocol");a(this,"_token");a(this,"webSocketSupported",!!globalThis.WebSocket);a(this,"authorized");a(this,"alias");a(this,"socket");a(this,"fosSocket");a(this,"fosPort");a(this,"useFosTransport");this.host=t,this.port=s,this.protocol=o,this._token=r,this.alias=i,this.authorized=process.env.KOS_ALLOW_ANONYMOUS==="true",this.useFosTransport=!!c,this.fosPort=c==null?void 0:c.port,this.socket=void 0,this.fosSocket=void 0;let l=!1;v.makeObservable(this,{authorized:v.observable,socket:v.observable,fosSocket:v.observable,init:v.action,connectionEstablished:v.computed}),v.reaction(()=>this.connectionEstablished,d=>{d&&(Ee.warn("Connection Established"),F("websocket.connected","websocket.connected"),l&&F("websocket.reload","websocket.reload"),l=!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 t,s;if(f.warn(`Initializing WebSocketTransport on ${this.host}:${this.port}`),this.useFosTransport&&(this.fosSocket=wo.build({host:this.host,port:this.fosPort||9854,protocol:this.protocol,fos:!0})),this.socket=wo.build({host:this.host,port:this.port,protocol:this.protocol,alias:this.alias,onConnectionLost:()=>{Ee.error("Connection Lost"),F("websocket.disconnected","websocket.disconnected"),this.init()}}),globalThis.kosWindowWebsocketOpen){const o={currentTarget:this.socket.socket};(s=(t=this.socket.socket)==null?void 0:t.onopen)==null||s.call(t,o)}return this}_sendSubscriptionMessage(t,s,o=!1,r=!1,n){var p,w,b,_;Ee.debug(`${s} to topic ${t}`);const i=ee(),c=i==null?void 0:i.connId,l=n??c??((p=window==null?void 0:window.kosBridge)==null?void 0:p.call(window,"connId"));Ee.debug(`subscribing with connId ${l}`);const d=l?`dst-addr:${l}
|
|
72
72
|
`:"",u=o?`subscribe:${t}`:r?`type:fos.broker
|
|
73
73
|
cmd:${s}
|
|
74
74
|
${d}topics:${t}
|
|
75
75
|
`:`${d}type:kos.broker.${s}
|
|
76
76
|
|
|
77
|
-
["${t}"]`;if(o?(w=this.fosSocket)==null?void 0:w.connectionEstablished:(b=this.socket)==null?void 0:b.connectionEstablished){const I=o?this.fosSocket:this.socket;(_=I==null?void 0:I.socket)==null||_.send(u)}else{Ee.debug("no connection adding to offline messages");const I=o?this.fosSocket:this.socket;I==null||I.addOfflineMessage(u)}}subscribeTopic({topic:t,callback:s,fos:o,bridge:r,destinationAddress:n}){const{unsubscribe:i,count:c}=j(t,s);return Ee.debug(`Topic ${t} currently has ${c} subscribers`),this._sendSubscriptionMessage(t,"subscribe",o,r,n),()=>{const{count:l}=i();Ee.debug(`Topic ${t} currently has ${l} subscribers`),l===0&&this._sendSubscriptionMessage(t,"unsubscribe",o,r,n)}}async whenReady(){const t=this;return this.webSocketSupported?(await v.when(()=>{var s,o;return!!((s=t.socket)!=null&&s.connectionEstablished)&&(!t.useFosTransport||!!((o=t.fosSocket)!=null&&o.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 o=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:t,token:s,fos:o})}return this._instance}}a(Vt,"_instance");class bu{constructor(t,s,o,r,n){a(this,"disposers",[]);a(this,"activatableDisposers",[]);this.model=t,this.modelData=s,this.modelId=o,this.offlineQueue=r,this.log=n}registerAll(t){var r;const s=((r=this.modelData)==null?void 0:r[G])||{},o=Object.keys(s);this.log.debug(`Found ${o.length} subscriptions in ${this.modelId} (lifecycle: ${t??"any"})`),o.forEach(n=>{const i=s[n],c=i.lifecycle;if(t&&t!==c)return;const l=this.resolvePropKey(n);this.log.debug(`Resolved topic: ${n} → ${l}`);const d=this.createHandler(l,i);this.subscribe(i,l,d,c===x.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 of t)try{s()}catch(o){this.log.error("Error during subscription disposal",o)}this.disposers=[],this.activatableDisposers=[]}subscribe(t,s,o,r){const n=t.destinationAddress?this.resolvePropKey(t.destinationAddress):null;if(t.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=Vt.getInstance().subscribeTopic({topic:s,callback:o,fos:t.fos,bridge:t.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=j(s,o);r?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(t,s){return async o=>{var r;try{const n=(r=o==null?void 0:o.headers)==null?void 0:r["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),c=i?n===i:!0;if(this.model.isReady()){const l=bo(o,s.skipParse),d=s.transform(l);if(c&&s.condition(d,this.modelData,o))return s.handler.call(this.modelData,d,o,this.modelData)}else{this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${t}`);const l=()=>{const d=bo(o,s.skipParse),u=s.transform(d);if(c&&s.condition(u,this.modelData,o))return s.handler.call(this.modelData,u,o,this.modelData)};this.offlineQueue.enqueue(l)}}catch(n){this.log.error(`Error handling subscription for ${t}`,n)}}}resolvePropKey(t){const s=/.*({PROP_(.+)})/;let o=t.includes("{MODEL_ID}")?t.replace("{MODEL_ID}",this.modelId):t;const r=o.match(s);return r&&r[2]in this.modelData&&(o=o.replace(r[1],this.modelData[r[2]])),o}}function nt(e,t){const s=`[Model:${t}]`;return{debug:(...o)=>e.debug(s,...o),info:(...o)=>e.info(s,...o),warn:(...o)=>e.warn(s,...o),error:(...o)=>e.error(s,...o)}}function vu(e){return!!(e!=null&&e[$e])&&Object.keys(e[$e]).length>0}function wu(e){return!!(e!=null&&e[G])&&Object.keys(e[G]).length>0}class Mu{static createAll(t){const{modelId:s,modelTypeName:o,modelData:r}=t,n=ru.create({modelId:s,modelTypeName:o}),i=new ou(t,nt(n,"fsm")),c=new nu(nt(n,"offline-queue")),l=new Wd(t),d=new qd(t),u={fsm:i,offlineQueue:c,companionManager:l,childResolver:d};if(vu(r)&&(u.effectManager=new Zd(o,s,r,nt(n,"effect"))),wu(r)){const h=nt(n,"subscription");u.subscriptionManager=new bu(t,r,s,c,h),u.onlineLifecycleManager=new iu(t,nt(n,"online"))}return u}}const S=T.getLogger("kos-model"),_u="kos.extension.model.loader";class Pi{constructor({modelTypeName:t,id:s,modelData:o}){a(this,"_id");a(this,"_status");a(this,"_activeStatus");a(this,"_onlineStatus");a(this,"modelData");a(this,"modelTypeName");a(this,"initialized");a(this,"loaded");a(this,"offlineQueue");a(this,"subscriptionManager");a(this,"effectManager");a(this,"onlineLifecycleManager");a(this,"companionManager");a(this,"childResolver");a(this,"fsm");this._id=typeof s<"u"?`${s}`:t,this.modelTypeName=t,this.initialized=!1,this.loaded=!1,this.modelData=o,this._status=y.CREATED,this._activeStatus=y.INACTIVE,this._onlineStatus=y.OFFLINE;const r=Mu.createAll(this);this.fsm=r.fsm,this.offlineQueue=r.offlineQueue,this.companionManager=r.companionManager,this.childResolver=r.childResolver,r.effectManager&&(this.effectManager=r.effectManager),r.subscriptionManager&&(this.subscriptionManager=r.subscriptionManager),r.onlineLifecycleManager&&(this.onlineLifecycleManager=r.onlineLifecycleManager),v.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),Yd(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===y.ACTIVE}isOnline(){return this._onlineStatus===y.ONLINE}isReady(){return this._status===y.READY}async deactivate(){var t,s,o;S.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const r=k.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.deactivate)==null?void 0:s.call(t,r)),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(o=this.subscriptionManager)==null||o.deactivate()}catch(r){throw S.debug(`Model ${this.modelId} failed to deactivated`),r}}async activate(){var t,s,o;S.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await ct(this,x.ACTIVATE);try{const r=k.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.activate)==null?void 0:s.call(t,r)),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(x.ACTIVATE),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(r){throw S.debug(`Model ${this.modelId} failed to activate`),r}}async whenInitialized(){await Hr([{condition:()=>this.status===y.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{S.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await Hr([{condition:()=>this.status===y.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===y.READY,onMatch:()=>{S.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var t,s,o;if(this.fsm.current===y.READY){S.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{S.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await ct(this,x.READY),await vi(this,zo.READY,x.READY);const r=k.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.ready)==null?void 0:s.call(t,r)),this.offlineQueue.flush(),(o=this.subscriptionManager)==null||o.registerAll(x.READY),S.debug(`Model ${this.modelId} is ready`);const n={modelId:this.modelId,modelType:this.modelTypeName};N(ii(this.modelTypeName,this.modelId),n),N(ai(this.modelTypeName),n)}catch(r){throw S.error(r),Error(r)}}async load(){var o,r,n,i;const{modelTypeName:t,modelId:s}=this;if(this.fsm.current===y.LOADED||this.fsm.current===y.LOADING){S.debug(`Model ${t} with id ${s} already loaded or loading`);return}S.debug(`Loading model ${t} with id ${s}`),await ct(this,x.LOAD);try{const c=k.getContext(s),l=`${_u}.${t}`,d=await C.loader.executeLoader(l,{});d&&(S.info(`Setting loaded context for ${s}, type: ${t}`),c==null||c.set(l,d)),await((r=(o=this.modelData)==null?void 0:o.load)==null?void 0:r.call(o,c)),this.loaded=!0,S.debug(`Model ${t} with id ${s} successfully loaded`),(n=this.subscriptionManager)==null||n.registerAll(x.LOAD),(i=this.effectManager)==null||i.setup()}catch(c){throw S.error(`Model ${s} failed to load`,c),c}}async unload(){var t,s,o,r,n;S.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const i=this.getChildren().map(l=>{var d;return(d=l.unload)==null?void 0:d.call(l)}).filter(l=>!!l);await Promise.allSettled(i);const c=k.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.unload)==null?void 0:s.call(t,c)),this.loaded=!1,(o=this.onlineLifecycleManager)==null||o.dispose(),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(r=this.effectManager)==null||r.disposeAll(),(n=this.subscriptionManager)==null||n.disposeAll()}catch(i){throw S.debug(`Model ${this.modelId} failed to unload`),i}}async init(){var r,n,i;const{modelId:t,modelTypeName:s}=this,o=k.getContext(t);S.debug(`Initializing model ${s} with id ${t}`),await ct(this,x.INIT);try{await((n=(r=this.modelData)==null?void 0:r.init)==null?void 0:n.call(r,o)),this.initialized=!0,S.debug(`Model ${s} with id ${t} initialized`),(i=this.onlineLifecycleManager)==null||i.register(),this.registerSubscribers(x.INIT)}catch(c){throw S.error(`Model ${t} failed to initialize`,c),c}}async registerSubscribers(t){var s;S.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(t)}async online(){var s,o;S.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const t=k.getContext(this.modelId);await((o=(s=this.modelData)==null?void 0:s.online)==null?void 0:o.call(s,t))}async offline(){var s,o,r;S.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const t=k.getContext(this.modelId);await((r=(o=this.modelData)==null?void 0:o.offline)==null?void 0:r.call(o,t))}accept(t){t.visit(this)}getChildren(){return this.childResolver.resolve()}addCompanionModel(t){this.companionManager.add(t)}clearCompanionModels(){this.companionManager.clear()}}const ki=e=>typeof e=="function",Wr=f.createLogger({name:"kos-model-instantiator"});class Eu{constructor(t,s){this.registry=t,this.cache=s}createModelInstance(t,s,o={}){const r=this.registry.models[t];if(!r)throw new Error(`No model registered for type ${t}`);const n=r.singleton?t:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){Wr.debug(`Creating model instance: ${t} [${n}]`);const c=r.create?r.create({modelTypeId:t,id:n,options:o}):new r.class(n,o),l=new Pi({modelTypeName:t,id:n,modelData:c});this.cache.addModel(l),this._createCompanionModels(l,o)}const i=this.cache.getModelById(n);if(!i)throw Wr.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 o=t.modelTypeName,r=((n=this.registry.companionModels)==null?void 0:n[o])||[];for(const{type:i}of r){const c=ki(i)?i(t.modelData,s):i;if(!c)continue;const l=`${c}-${t.modelId}`,d=this.createModelInstance(c,l,{data:s,companionParent:t.modelData,kosParentId:t.modelId});d!=null&&d.model&&t.addCompanionModel(d.model)}}}let Iu=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 o,r;(o=this.registry).companionModels??(o.companionModels={}),(r=this.registry.companionModels)[t]??(r[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 o;const s=(o=this.getModelTypeRegistry(t))==null?void 0:o.builder;if(!s)throw new Error(`No builder found for model type ${t}`);return s}getModelFactory(t){return et(t)}};const xi=10,Zr=f.createLogger({name:"kos-model-manager"});class Fi{constructor(){a(this,"cache");a(this,"instantiator");a(this,"dependencies");a(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Od,globalThis.kos.modelManager=this,globalThis.kos.resolveKosModel=t=>{const s=this.getModelById(t);if(s)return s.modelData||{}},globalThis.kos.kosModelJson=t=>{var o,r;const s=this.getModelById(t);if(s)return((r=(o=s.modelData).toJSON)==null?void 0:r.call(o))||{}},globalThis.kos.kosModelDebug=t=>{var o;const s=this.getModelById(t);if(s)return((o=s.modelData)==null?void 0:o.debugState)||{}},globalThis.kos.kmd=globalThis.kos.kosModelDebug,globalThis.kos.kmj=globalThis.kos.kosModelJson}static create(t,s){const o=this.getInstance(s);return o._registry=new Iu(t),o.cache=new Dd(t.preloadModels),o.instantiator=new Eu(t,o.cache),o}static getInstance(t){var s,o;return(!((s=globalThis.kos)!=null&&s.modelManager)||t)&&(Zr.debug("Creating new instance of KosModelManager"),new this),(o=globalThis.kos)==null?void 0:o.modelManager}get registry(){return this._registry.registry}get preloadedModels(){return this.cache.preload(t=>(Zr.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(o=>o.modelTypeName===t).filter(o=>s?s(o.modelData):!0).map(o=>o.modelData)}getModelSubscriptions(t){return this._registry.getModelSubscriptions(t)}getDataModelBuilder(t){return this._registry.getDataModelBuilder(t)}getModelFactory(t){return et(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(D.RESET,y.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),Qn.addToDeletionQueue(t.id,setTimeout(()=>this.destroyModel(s),xi)))}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,o={}){return this.instantiator.createModelInstance(t,s,o)}registerCompanionModel(t,s){this._registry.registerCompanionModel(t,s)}registerModel(t){this._registry.registerModel(t)}}const Tu=async({context:e,extension:t})=>{const s=await C.loader.executeLoader(t,{});return e==null||e.set(t,s),s},$u=async({extension:e,contextData:t,data:s})=>await C.dataMapper.executeMapper(e,s,t),Ou=async({extension:e,contextData:t,data:s})=>await C.propertyMapper.executeMapper(e,s,t),Du=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:$u,executeLoaderExtension:Tu,executePropertyMapperExtension:Ou},Symbol.toStringTag,{value:"Module"})),Su="Extensions";class Au{constructor(){a(this,"extensions");this.extensions={}}register(t,s,o){this.extensions[t]={},this.extensions[t][s]={component:o}}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}}var cs=(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))(cs||{}),Ue=(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))(Ue||{});const Cu=e=>{const t=m.createMachine("offline",{online:m.state(m.transition("go_offline","offline",m.action(()=>{e.offline(),v.runInAction(()=>{e.isOnline=!1})}))),offline:m.state(m.transition("go_online","online",m.action(()=>{e.online(),v.runInAction(()=>{e.isOnline=!0})})))}),s=m.interpret(t,n=>T.debug(n.machine.current)),o=m.createMachine({creating:m.state(m.transition("create","created")),created:m.state(m.immediate("initializing")),initializing:m.invoke(()=>e.init(),m.transition("done","initialized")),initialized:m.state(m.immediate("loading")),loading:m.invoke(()=>e.load(),m.transition("done","loaded")),loaded:m.state(m.immediate("readying"),m.transition("unload","unloading")),readying:m.invoke(()=>e.ready(),m.transition("done","ready",m.action(()=>{v.runInAction(()=>{e.status="ready"})}))),reloading:m.invoke(()=>e.reload(),m.transition("done","loading")),ready:m.state(m.transition("reload","reloading"),m.transition("unload","unloaded",m.action(e.unload.bind(e))),m.transition("go_online","ready",m.action(()=>{s.send("go_online")})),m.transition("go_offline","ready",m.action(()=>{s.send("go_offline")}))),unloaded:m.state()});return{service:m.interpret(o,n=>T.debug(n.machine.current)),online:s}},J=async e=>{if(e.id){const t=E.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},Oe=async e=>{await E.getInstance().whenReady(),await E.getInstance().modelManager.initiateDestroyModel(e)},Ru=async e=>{if(await E.getInstance().whenReady(),!e.id)throw new Error("Model ID is required");const t=E.getInstance().modelManager.getModelById(e.id);t&&await t.fsm.transitionTo(D.UNLOAD,y.UNLOADED)},Ni=async e=>{await E.getInstance().whenReady(),await E.getInstance().modelManager.reloadModel(e),f.debug(`reload model initiated for model ${e.id}, model ready: ${fs(e)} - ${Date.now()} `),await J(e),f.debug(`reload model complete for model ${e.id}, model ready: ${fs(e)} - ${Date.now()} `)},Lu=async e=>{if(await E.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=E.getInstance().modelManager.getModelById(e);return t==null?void 0:t.modelTypeName},Ui=async e=>{if(await E.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=E.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},Ce=e=>{if(!e)throw new Error("Model ID is required");const t=E.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},ji=(e,t)=>{if(!e)throw new Error("Model type is required");return E.getInstance().modelManager.getModelsByType(e).filter(r=>Object.keys(t).every(n=>r[n]===t[n]))},Pu=(e,t)=>ji(e,t)[0],ku=(e,t)=>{if(!e.id)throw new Error("Model ID is required");const s=E.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error("Model not found");const o=s.companionModels.get(t);return o==null?void 0:o.modelData},xu=e=>{if(!e.id)throw new Error("Model ID is required");const t=E.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return Array.from(t.companionModels.all()).map(o=>o.modelData)},Fu=e=>{if(!e)throw new Error("Model ID is required");const t=E.getInstance().modelManager.getModelById(e);if(!t)throw new Error("Model not found");return t.companionModels.data},wo=(e,t)=>{const s=E.getInstance().modelManager.getModelById(e);if(!s){f.info(`Model not found for id ${e}`);return}return Array.from(s.companionModels.all()).find(r=>t(r.modelData))},te=e=>t=>Object.getPrototypeOf(t).modelTypeId===e,fs=e=>{const t=E.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return t.isReady()},Nu=f.createLogger({name:"kos-model-factory"}),$t={byModelType:e=>E.getInstance().modelManager.getModelFactory(e),getModelInstance:(e,t,s)=>{const o=$t.byModelType(t);if(!o)throw Nu.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 o.build(e,s)}},H={Factory:{create:e=>t=>(s,o)=>(o&&k.setParentContext(t,o),$t.getModelInstance(t,e,s))},Singleton:{create:e=>(t,s)=>(s&&k.setParentContext(e,s),$t.getModelInstance(e,e,t))},Model:{instance:e=>t=>$t.getModelInstance(t,e)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const Jr=window.KosRegistry.coreModels,no=window.KosRegistry.preloadModels,io=window.KosRegistry.companionModels,Jt=window.KosRegistry.models,$={model:{registerLegacyModel:e=>(t,s)=>(Jr.set(t,s),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}),preloadModel:e=>t=>(no.includes(t)||no.push(t),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}),register:e=>(t,s)=>{const o=ao(t)?t.registration():t;return Jt.set(o.type,o),ao(t)&&t.relatedModels.forEach(r=>Jt.set(r.type,r.registration())),E.getInstance().isReady&&(E.getInstance().modelManager.registry.models[o.type]||(console.info(`Model with type ${o.type} doesn't exist. Adding new registration`),E.getInstance().modelManager.registry.models[o.type]=o.registration[o.type],ao(t)&&t.relatedModels.forEach(r=>E.getInstance().modelManager.registry.models[r.type]=r.registration().registration))),s&&$.model.preloadModel(e)(o.type),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}},get:e=>Jt.get(e),getAll:()=>Array.from(Jt.entries()),getPreloadModels:()=>no,getLegacyModels:()=>Array.from(Jr.entries()).reduce((e,[t,s])=>(e[t]=s,e),{})},companion:{register:e=>(t,s)=>{const o=io.get(t)||[];return o.push(s),io.set(t,o),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}},getAll:()=>Array.from(io.entries())}},Bi=$.model.registerLegacyModel,Ki=$.model.register,Uu=$.companion.register,ju=$.model.preloadModel,Gi=e=>typeof e.updateModel=="function",ao=e=>e.registration!==void 0&&typeof e.registration=="function";class Vi{constructor(t){a(this,"singleton");a(this,"type");a(this,"loader");a(this,"class");a(this,"guard");a(this,"factory");a(this,"relatedModels",[]);this.singleton=t.singleton,this.guard=te(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(){$.model.register({})(this.registration()),this.registerRelatedModels()}}class ae extends Vi{constructor(t){super({...t,singleton:!1,factory:H.Factory.create(t.type)})}instance(t){const s=this.factory(t);return{get:()=>{const o=Ce(t);if(!o)throw new Error("Model not found with id "+t);if(this.guard(o))return o;throw new Error("Model is not of type "+this.type)},forceUpdate:{options:o=>({build:()=>{const r=s(o);if(this.guard(r)){if(Gi(r))r.updateModel(o);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return r}else throw new Error("Model is not of type "+this.type)}})},options:o=>({build:()=>{const r=s(o);if(this.guard(r))return r;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 pe extends Vi{constructor(t){super({...t,singleton:!0,factory:H.Singleton.create(t.type)})}instance(){const t=this.factory;return{get:()=>{const o=Ce(this.type);if(!o)throw new Error("Model not found with id "+this.type);if(this.guard(o))return o;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)},forceUpdate:{options:o=>({build:()=>{const r=t(o);if(this.guard(r)){if(Gi(r))r.updateModel(o);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return r}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)}})},options:o=>({build:()=>{const r=t(o);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const U=f.createLogger({name:"kos-core"}),Bu=()=>{const e=ee(),t=e==null?void 0:e.alias,s=process.env.KOS_CONNECTION_ALIAS;return t||s||void 0},Ku=()=>{const e=window.location.protocol,t=ee(),s=t==null?void 0:t.host;let o;try{o=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return o||(e==="https:"?"wss://":"ws://")},Gu=()=>{const e=window.location.hostname,t=process.env.KOS_HOST,s=ee(),o=s==null?void 0:s.host;let r;try{r=new URL(o).hostname}catch{}return r??t??e},Vu=()=>{const e=window.location.port,t=process.env.KOS_PORT,s=ee(),o=s==null?void 0:s.host;let r;try{r=new URL(o).port}catch{}return r??t??e},Hu=(e,t)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{t?f.error(`Model ${t.modelId} - ${t.modelTypeName} preloading - timed out after ${e}ms`):f.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)}}},Qr=e=>typeof e.reload=="function",Yu=e=>typeof e.unload=="function";var Hi=(e=>(e.LOGGED_IN="logged_in",e.LOGGED_OUT="logged_out",e))(Hi||{});class E{constructor(t){a(this,"fsmService");a(this,"status");a(this,"initialized");a(this,"loaded");a(this,"_transport");a(this,"modelManager");a(this,"authState");a(this,"isOnline");a(this,"_reloading");a(this,"_unloading");a(this,"connectionAlias");this.initialized=!1,this.connectionAlias=t,this.loaded=!1,this.isOnline=!1,this.status=cs.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,v.makeAutoObservable(this),j("token",c=>{c&&(this.transport.token=c.body)}),j(Tt.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(Ue.GO_ONLINE)}),j(Tt.DISCONNECTED,async()=>{this.fsmService.service.send(Ue.GO_OFFLINE)}),j("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),j("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),j(Tt.RELOAD,()=>{this.fsmService.service.send(Ue.RELOAD)}),j("/studio/project/reload",()=>{this.fsmService.service.send(Ue.RELOAD)});const s=Vt.getInstance(),o=Gu(),r=Vu(),n=Ku();s.host=o,s.port=Number.parseInt(r),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=Bu()??t;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=Cu(this),this.fsmService.service.send(Ue.CREATE)}get onlineStatus(){return this.isOnline&&!this._reloading&&!this._unloading}get reloading(){return this._reloading}get unloading(){return this._unloading}async reload(){var r,n,i,c;const t=Date.now();if(this._reloading){U.info("reload already in progress");return}this._reloading=!0,U.warn("reloading KOS Core"),U.warn("reloading preloaded models");const s=this.modelManager;for(const l of s.preloadedModels)Qr(l.modelData)&&(U.info(`reloading model ${l.modelId}`),(r=l.unload)==null||r.call(l),await l.modelData.reload(),(n=l.registerSubscribers)==null||n.call(l),U.info(`reloading model ${l.modelId} complete`));for(const l of s.models)!s.preloadedModels.includes(l)&&Qr(l.modelData)&&((i=l.unload)==null||i.call(l),await l.modelData.reload(),(c=l.registerSubscribers)==null||c.call(l));const o=Date.now()-t;setTimeout(()=>{v.runInAction(()=>{U.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-o)}async online(){U.debug("KOS Core going online"),await this._transport.whenReady(),U.debug("KOS Transport Ready. Calling online() for models"),N("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){U.debug("KOS Core going offline"),N("/kosCore/offline","/kosCore/offline")}async unload(){var r;U.debug("Unloading KOS Core");const t=Date.now();this._unloading=!0,U.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)Yu(n.modelData)&&((r=n.unload)==null||r.call(n));const o=Date.now()-t;setTimeout(()=>{v.runInAction(()=>{this._unloading=!1})},1e3-o)}async whenReady(){await v.when(()=>this.status===cs.READY)}async ready(){U.debug("Readying KOS Core"),await this._transport.whenReady();const t=this.modelManager.preloadedModels.map(r=>({modelId:r.modelId,model:r,promise:r.whenReady()})),o=(await Promise.allSettled(t.map(r=>{const{promise:n,cancel:i}=Hu(5e3,r.model);Promise.race([r.promise.then(()=>{i()}),n])}))).filter(r=>r.status==="rejected");if(o.length)throw U.error(`There were ${o.length} failed models on model preloading`),Error(`There were ${o.length} failed models on model preloading`);U.debug("leaving kos-core ready() ")}get isReady(){return this.status===cs.READY}set transport(t){this._transport=t}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){U.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,U.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){U.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,U.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(t,s,o){var i,c,l;const r=this.getInstance({reset:s,connectionAlias:o});(i=t.extensions)!=null&&i.dataMapper&&Object.keys(t.extensions.dataMapper).forEach(d=>{var h,p;const u=(p=(h=t.extensions)==null?void 0:h.dataMapper)==null?void 0:p[d];u&&(Array.isArray(u)?u.forEach(w=>{C.dataMapper.registerDataMapper(d,w)}):C.dataMapper.registerDataMapper(d,u))}),(c=t.extensions)!=null&&c.propertyMapper&&Object.keys(t.extensions.propertyMapper).forEach(d=>{var h,p;const u=(p=(h=t.extensions)==null?void 0:h.propertyMapper)==null?void 0:p[d];u&&C.propertyMapper.registerPropertyMapper(d,u)}),(l=t.extensions)!=null&&l.contextLoader&&Object.keys(t.extensions.contextLoader).forEach(d=>{var h,p;const u=(p=(h=t.extensions)==null?void 0:h.contextLoader)==null?void 0:p[d];u&&C.loader.registerLoader(d,u)}),$.model.getAll().forEach(([,d])=>{t.models={...t.models,...d.registration}}),t.models={...t.models,...$.model.getLegacyModels()},$.companion.getAll().forEach(([d,u])=>{t.companionModels={...t.companionModels},t.companionModels[d]=t.companionModels[d]||[];for(const h of u)t.companionModels[d].push({type:h})}),$.model.getPreloadModels().forEach(d=>{t.preloadModels.includes(d)||t.preloadModels.push(d)});const n=Fi.create(t,s);return r.modelManager=n,r}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}}a(E,"_instance");const Xr=f.createLogger({name:"kos-fetch"}),zu=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,qu=()=>new Promise(e=>{setTimeout(()=>{e(!0)},0)}),Wu=e=>e!=null&&e.studio?_i:e!=null&&e.fos?Ei:Ii,Zu=async(e,t)=>{const s=E.getInstance().transport;await s.whenReady();const o=Xe(),r=new URL(e),n=`${r.pathname}${r.search}`;Xr.debug(`path: ${n}`);const i=(t==null?void 0:t.timeout)||zu,c=Wu(t),l=ve(c({path:n,requestId:o,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}),t==null?void 0:t.body);return new Promise(d=>{const u=new AbortController,h=setTimeout(()=>{Xr.error(`Timeout occurred - url: ${e}`),u.abort(),d({headers:mo({}),status:404,ok:!1,json:async()=>null,body:yo(""),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),{unsubscribe:p}=j(o,b=>{var I,A,se;clearTimeout(h);const _={headers:mo((b==null?void 0:b.headers)||{}),status:((I=b==null?void 0:b.headers)==null?void 0:I.status)&&parseInt((A=b==null?void 0:b.headers)==null?void 0:A.status)||200,ok:((se=b==null?void 0:b.headers)==null?void 0:se.status)==="200",json:async()=>{var we;try{return(we=b==null?void 0:b.body)!=null&&we.length?JSON.parse(b.body):null}catch{throw Error("Not a JSON response")}},text:async()=>(b==null?void 0:b.body)||"",body:yo((b==null?void 0:b.body)||""),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.")}};p(),qu().then(()=>d(_))}),w=t!=null&&t.fos?s.fosSocket:s.socket;if(!w)throw Error(`No web socket transport available: ${t}`);w==null||w.send(l)})};exports.BASE_URL="kos:";exports.kosFetch=Zu;if(process.env.KOS_MOCK_FETCH==="true"){const e=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${e}`}const Ju=f.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Qu{constructor(){a(this,"visitedModels",new Set);this.visitedModels=new Set}start(t){var o;if(t.id===void 0)throw new Error("rootModel must have an id");const s=E.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error(`Could not find rootModel with id: ${t.id}`);this.visitedModels.clear(),(o=s.accept)==null||o.call(s,this)}visit(t){var o;if(this.visitedModels.has(t.modelId)){Ju.info(`model ${t.modelId} already visited`);return}const s=!!this.visitModel(t.modelData,this);this.visitedModels.add(t.modelId),!s&&((o=t.getChildren)==null||o.call(t).forEach(r=>{var n;(n=r.accept)==null||n.call(r,this)}))}}const Yi=()=>({isMock:!1,URL:exports.BASE_URL}),Xu=f.createLogger({name:"kos-service-request"}),eh="errUnknown";async function Qt(e,t,s,o,r){const n=o!=null&&o.path?Object.keys(o.path).reduce((h,p)=>String(h).replace(`{${p}}`,o==null?void 0:o.path[p]),String(e)):String(e),i=o!=null&&o.query?Object.keys(o.query).map(h=>`${h}=${o.query[h]}`).join("&"):"",c=`${Yi().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;Xu.debug(`fullUrl: ${c}`);const l={method:String(t).toUpperCase(),body:null,...s};r&&(l.body=JSON.stringify(r));const d=await exports.kosFetch(c,l);return d.status<200||d.status>=400?[`${d.statusText||eh}`,null]:[null,(await d.json()).data]}function Zo(){return{get:(e,t,s)=>Qt(e,"get",s,t),post:(e,t,s,o)=>Qt(e,"post",o,t,s),put:(e,t,s,o)=>Qt(e,"put",o,t,s),delete:(e,t,s)=>Qt(e,"delete",s,t)}}class zi{constructor(){a(this,"middlewares",[])}use(t){this.middlewares.push(t)}async execute(t){let s=0;const o=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](t,o)};await this.middlewares[s](t,o)}}const th=async(e,t)=>{const s=new zi;t.forEach(r=>s.use(r));const o={data:e,result:{}};return await s.execute(o),o.result},et=e=>({type:e,build:(t,s)=>E.getInstance().modelManager.createModelInstance(e,t,s).data,buildAsync:async(t,s)=>{const o=E.getInstance().modelManager.createModelInstance(e,t,s);return await o.model.whenInitialized(),o.data}}),sh=e=>{E.getInstance().modelManager.registerModel(e)},oh=(e,t)=>{E.getInstance().modelManager.registerCompanionModel(e,t)},qi=Symbol("KosObservableData");class Wi{constructor(){a(this,"map");a(this,"atomMap",new Map);a(this,"proxyHandler",{get:(t,s)=>{var o;return t[s]!==void 0?t[s]:this.atomMap.has(s)&&(o=this.atomMap.get(s))!=null&&o.reportObserved()?this.getValue(s):this.getValue(s)},set:(t,s,o)=>{var r;return this.setValue(s,o),this.atomMap.has(s)||this.atomMap.set(s,v.createAtom(s.toString())),(r=this.atomMap.get(s))==null||r.reportChanged(),!0},ownKeys:()=>Array.from(this.map.keys())});this.map=v.observable.map(new Map)}setValue(t,s){this.map.set(t,s)}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 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)}}Wi.prototype[qi]=!0;function rh(e,t){return new Proxy(e,{construct:(s,o)=>{const r=new e(...o);return r.setValues(t),r.proxy}})}const ye=e=>{const t=rh(Wi,e);return new t(e)},en="/kos/ui/internal/heartbeat/",nh=({relationshipId:e,destinationAddress:t,onAbort:s,waitTime:o,beatTime:r})=>{const n=E.getInstance().transport,i=new AbortController;let c=performance.now();const l=n.subscribeTopic({topic:`${en}${e}`,callback:()=>{c=performance.now()}}),d=o??3e3,u=window.setInterval(()=>{let _=performance.now()-c;_=_/1e3,_>d/1e3&&i.abort()},d),h=r??2e3,p=window.setInterval(()=>{Ci({msg:{},options:{topic:`${en}${e}`,destinationAddress:t}})},h),w=()=>{window.clearInterval(p),window.clearInterval(u),l()},b=()=>{w(),s&&s(),i.signal.removeEventListener("abort",b)};return i.signal.addEventListener("abort",b),{cleanUpHeartbeat:w}},Zi=(...e)=>t=>e.reduce((s,o)=>o(s),t),ih={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function ah(e,t){let s=1;const o={...ih,...t},{maxAttempts:r,baseDelayMs:n,backoffFactor:i}=o;let c=n;for(;s<=r;)try{return await e()}catch(l){if(f.error(`Attempt ${s} failed: ${l}`),s<r)c=n*Math.pow(i,s),await new Promise(d=>setTimeout(d,c)),s++;else throw l}throw new Error("All attempts failed")}const ch=f.createLogger({name:"kos-service-request"}),q=e=>({isMock:!1,URL:exports.BASE_URL}),lh=(e,t,s)=>async({id:o,tracker:r,urlOverride:n,ordered:i,studio:c,fos:l,bridge:d,destinationAddress:u})=>{const h={method:"DELETE"};e&&(h.destinationAddress=e),r&&(h.tracker=r),tt(h,{ordered:i,studio:c,fos:l,bridge:d,destinationAddress:u});const p=await s(n||`${t}/${o}`,h);if(!p.ok)throw Error(`There was a problem deleting the model; returned status ${p.status}`);return await p.json()},tt=(e,{ordered:t,studio:s,fos:o,destinationAddress:r,bridge:n,timeout:i})=>(i&&(e.timeout=i),t&&(e.ordered=t),s&&(e.studio=s),o&&(e.fos=o),n&&(e.bridge=n),(r||r==="")&&(e.destinationAddress=r),e),dh=(e,t,s)=>async({urlOverride:o,ordered:r,studio:n,fos:i,bridge:c,timeout:l,destinationAddress:d})=>{const u={method:"GET"};e&&(u.destinationAddress=e),tt(u,{timeout:l,ordered:r,studio:n,fos:i,bridge:c,destinationAddress:d});const p=await s(o||t,u);if(!p.ok){let b;try{b=await p.json()}catch{}throw new ce(`There was a problem retrieving the model; returned status ${p.status}`,b)}return await p.json()},uh=(e,t,s)=>async({urlOverride:o,ordered:r,studio:n,fos:i,bridge:c,tracker:l,timeout:d,destinationAddress:u})=>{const h={method:"GET"};e&&(h.destinationAddress=e),l&&(h.tracker=l),tt(h,{timeout:d,ordered:r,studio:n,fos:i,bridge:c,destinationAddress:u});const p=o||t;ch.debug(`resolvedUrl: ${p}`);const w=await s(p,h);if(!w.ok){let _;try{_=await w.json()}catch{}throw new ce(`There was a problem retrieving the model; returned status ${w.status}`,_)}return await w.json()},hh=(e,t,s)=>async({urlOverride:o,id:r,ordered:n,studio:i,fos:c,bridge:l,timeout:d,destinationAddress:u})=>{const h={method:"GET"};e&&(h.destinationAddress=e),tt(h,{timeout:d,ordered:n,studio:i,fos:c,bridge:l,destinationAddress:u});const p=o||`${t}/${r}`,w=await s(p,h);if(!w.ok){let _;try{_=await w.json()}catch{}throw new ce(`There was a problem retrieving the model; returned status ${w.status}`,_)}return await w.json()};class ce extends Error{constructor(s,o){super(s);a(this,"payload");this.name="FetchException",this.payload=o}}const tn=(e,t,s)=>async({model:o,urlOverride:r,ordered:n,tracker:i,studio:c,fos:l,bridge:d,timeout:u,destinationAddress:h})=>{const p={method:"POST",body:typeof o=="string"?o:JSON.stringify(o)};e&&(p.destinationAddress=e),i&&(p.tracker=i),tt(p,{timeout:u,ordered:n,studio:c,fos:l,bridge:d,destinationAddress:h});const w=await s(r||t,p);if(!w.ok){let _;try{_=await w.json()}catch{}throw new ce(`There was a problem sending the POST data; returned status ${w.status}`,_)}return await w.json()},sn=(e="POST",t,s,o)=>async({model:r,id:n,urlOverride:i,ordered:c,studio:l,fos:d,bridge:u,timeout:h,destinationAddress:p})=>{const w={method:e};r&&(w.body=JSON.stringify(r)),t&&(w.destinationAddress=t),tt(w,{timeout:h,ordered:c,studio:l,fos:d,bridge:u,destinationAddress:p});const b=await o(i||`${s}/${n}`,w);if(!b.ok){let I;try{I=await b.json()}catch{}throw new ce(`There was a problem modifying the model; returned status ${b.status}`,I)}return await b.json()},Y={build:({destinationAddress:e="",basePath:t,getAllPath:s,getOnePath:o,deleteModelPath:r,addModelPath:n,modifyModelPath:i,mock:c=!1})=>{const l=c?fetch:exports.kosFetch;return{getAll:dh(e,s||t,l),getModelById:hh(e,o||t,l),getOne:uh(e,o||t,l),addModel:tn(e,n||t,l),deleteModel:lh(e,r||t,l),modifyModel:sn("POST",e,i||t,l),putModel:sn("PUT",e,i||t,l),postModel:tn(e,n||t,l)}}},gh=Xe(),Ji=()=>`kos-${gh}`,fh=e=>!!e&&!e.includes("VM_SERVICE")&&e.startsWith(Ji()),Jo=async(e,t=6e4)=>new Promise((s,o)=>{const{unsubscribe:r}=j(e,i=>{T.debug(`recieved response for refId ${e}: ${i}`),r(),clearTimeout(n);try{const c=i!=null&&i.body?JSON.parse(i.body):{};s(c)}catch{const c=(i==null?void 0:i.body)||{};s(c)}}),n=setTimeout(()=>{r(),o(Error(`Request with ID ${e} timed out. Cancelling.`))},t)}),ph=async(e,t,s)=>{const o=Jo(s),r=await Promise.allSettled([e(t),o]);if(r[0].status==="fulfilled"){if(r[1].status==="rejected")throw Error(r[1].reason);if(r[0].value){if(r[1].value.error)throw Error(r[1].value.error);return r[0].value.data=r[1].value,r[0].value}}else throw Error(r[0].reason)},mh=async({topic:e,msg:t,requestId:s})=>{const o=s??Xe(),r=Jo(o);N(e,t,{sync:o});const n=await r;if(n.error)throw Error(n.error);return n},ue=new Map;class Qi{constructor(t){a(this,"_context");a(this,"_parent");a(this,"_id");this._id=t,this._context=new v.ObservableMap({}),this._parent="",v.makeAutoObservable(this)}setParent(t){z(()=>{this._parent=t})}get id(){return this._id}get context(){return this._context}get parentModel(){var t;if(this._parent)return(t=Ce(this._parent))==null?void 0:t.model}get(t){var s;if(this._context.has(t))return this._context.get(t);if(this._parent)return(s=ue.get(this._parent))==null?void 0:s.get(t)}set(t,s){this._context.set(t,s)}remove(t){this._context.delete(t)}clear(){this._context.clear()}}const k={createContext:(e,t)=>{const s=ue.get(e)??new Qi(e);if(t){if(!ue.has(t))throw new Error(`Parent context ${t} does not exist`);s.setParent(t)}else e!=="root"&&s.setParent("root");return ue.set(e,s),s},getContext:e=>ue.get(e),deleteContext:e=>{ue.delete(e)},setParentContext:(e,t)=>{var s;if(!ue.has(t))throw new Error(`Parent context ${t} does not exist`);(s=ue.get(e))==null||s.setParent(t)},rootContext:()=>ue.get("root")};k.createContext("root");const yh=e=>k.getContext(e.id);function bh(e,t){return e.length!==t.length?!1:e.every(s=>t.includes(s))}class Qo{constructor({container:t,key:s}){a(this,"_container");a(this,"_map");a(this,"_key");a(this,"data");this._container=t,this._map=v.observable.map(new Map),this._key=s,this.data=ye(),this.generateIndex(),v.autorun(()=>{this._container.revision&&this.generateIndex()}),v.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(t,s,o=this._map,r=this.data){const n=o.get(t)||new Set;n.add(s),o.set(t,n),r[t]=Array.from(n)}resolveIndex(t,s){this.data.keys.filter(r=>!Object.keys(s).includes(r)).forEach(r=>{delete this.data[r],this._map.delete(r)}),Object.keys(s).forEach(r=>{const n=s[r],i=this.data[r]||[];if(bh(n,i))f.debug(`KosContainerIndex - Index ${r} is the same`);else{this.data[r]=n;const c=t.get(r)||new Set;this._map.set(r,c)}})}generateIndex(){v.runInAction(async()=>{const t=new Map,s={};for(const o of this._container.data){const r=typeof this._key=="function"?await this._key(o):o[this._key];Array.isArray(r)?r.forEach(n=>{this.addItemToIndex(n,o,t,s)}):typeof r=="string"||typeof r=="number"?this.addItemToIndex(String(r),o,t,s):typeof r=="boolean"&&this.addItemToIndex(String(r),o,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 vh(e,t,s=[]){const o=Object.getOwnPropertyDescriptors(e);return Object.keys(o).filter(i=>v.isComputedProp(e,i)).filter(i=>s.includes(i)).map(i=>v.reaction(()=>e[i],(c,l)=>{t({name:i,newValue:c,oldValue:l})}))}const it=f.createLogger({name:"kos-container-model"});class de{constructor(t){a(this,"_data");a(this,"_sortKey");a(this,"_revision");a(this,"_index");a(this,"_optionsMap");a(this,"_disposerMap",new Map);a(this,"_parentId");a(this,"idx");this._data=v.observable.map(new Map),this._sortKey=t==null?void 0:t.sortKey,this._revision=1;const s=t!=null&&t.extensionId?C.indexExtension.loadIndexExtensions(t.extensionId):{},o=(t==null?void 0:t.indexMap)||{};this._optionsMap={...o,...s};const r=t!=null&&t.indexMap?Object.keys(t.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=v.observable.map(r),this.idx=ye(),this._parentId=t==null?void 0:t.parentId,v.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],o=new Qo({container:this,key:s});this._index.set(t,o),this.idx[t]=o.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 o;return t[s]=(o=this.index.get(s))==null?void 0:o.keys,t},{})}sortFn(t,s){const o=this._sortKey;return o?String(t[o]).localeCompare(String(s[o]),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(){v.runInAction(()=>{this._revision=this._revision+1})}addAll(t){v.runInAction(()=>{t.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(t){v.runInAction(()=>{t.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(t,s){this._data.set(t.id||"",t),t.id&&this._parentId&&k.setParentContext(t.id,this._parentId),s||this.increment();const o=this._disposerMap.get(t.id);o&&(o(),this._disposerMap.delete(t.id));const r=Object.entries(this._optionsMap||{}),n=Object.values(this._optionsMap||{}),i=new Map(r.map(([u,h])=>[h,u])),c=u=>{var p,w;n.includes(u.name)&&((p=this.index.get(i.get(u.name)))==null||p.refresh());const h=r.filter(([,b])=>typeof b=="function");for(const[b]of h)(w=this.index.get(b))==null||w.refresh()},l=vh(t,c,n.filter(u=>typeof u=="string")),d=v.observe(t,c);this._disposerMap.set(t.id||"",()=>[d,...l].forEach(u=>u()))}removeModel(t,s){this._data.delete(t),s||this.increment();const o=this._disposerMap.get(t);o&&(o(),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??[]:(it.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(t,s){if(this.index.has(t)){const o=this.index.get(t);return o.index.has(s)?o.getByKey(s):(it.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return it.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(t=>{const s=t.id;Oe(t).then(()=>{it.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(o=>it.error(o))}),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 co=f.createLogger({name:"kos-data-container"});class Xi{constructor(t){a(this,"_data");a(this,"_sortKey");a(this,"_revision");a(this,"_index");a(this,"_optionsMap");a(this,"_disposerMap",new Map);a(this,"idx");this._data=v.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((o,r)=>(o[r]=void 0,o),{}):{};this._index=v.observable.map(s),this.idx=ye(),v.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],o=new Qo({container:this,key:s});this._index.set(t,o),this.idx[t]=o.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 o;return t[s]=(o=this.index.get(s))==null?void 0:o.keys,t},{})}get revision(){return this._revision}addAll(t){v.runInAction(()=>{t.forEach(s=>this.addModel(s))})}removeAll(t){v.runInAction(()=>{t.forEach(s=>this.removeModel(s))})}sortFn(t,s){const o=this._sortKey;return o?String(t[o]).localeCompare(String(s[o]),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(){v.runInAction(()=>{this._revision=this._revision+1})}addModel(t,s){const o=v.isObservable(t)?t:v.observable.object(t),r=this._disposerMap.get(t.id);r&&(r(),this._disposerMap.delete(t.id)),this._data.set(o.id||"",o),s||this.increment();const n=v.observe(o,i=>{Object.values(this._optionsMap||{}).includes(i.name)&&this.increment()});this._disposerMap.set(o.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=v.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??[]:(co.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(t,s){if(this.index.has(t)){const o=this.index.get(t);return o.index.has(s)?o.getByKey(s):(co.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return co.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 wh{constructor({type:t,model:s,childRegistration:o}){a(this,"type");a(this,"childRegistration");a(this,"model");this.type=t,this.model=s,this.childRegistration=o}get factory(){return H.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 Mh{constructor({type:t,model:s,childRegistration:o}){a(this,"type");a(this,"model");a(this,"childRegistration");this.type=t,this.model=s,this.childRegistration=o}get factory(){return H.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 ea{constructor(){a(this,"_token");v.makeAutoObservable(this),j("token",t=>{this.token=t==null?void 0:t.body})}get token(){return this._token}set token(t){this._token=t}}class ta{constructor(){a(this,"routes",[]);a(this,"openApiRoutes",[])}use(t,s,...o){this.routes.push({method:t,path:s,middlewares:o});const r=this.extractOpenApiParams(s);this.openApiRoutes.push({method:t,path:s,parameters:r})}async handle(t,s){var c;const{path:o,query:r,params:n}=this.extractPathParams(t.path),i={...t,params:n,query:r};for(const l of this.routes){const d=this.matchRoute(l.path,o);if(l.method===t.method&&d){i.params=d;let u=0;const h=async()=>{if(u<l.middlewares.length){const p=l.middlewares[u++];await p(i,s,h)}};await h();return}}(c=s.status)==null||c.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,o]=t.split("?"),r=this.parseQueryParams(o);for(const n of this.routes){const i=this.matchRoute(n.path,s);if(i)return{path:s,query:r,params:i}}return{path:s,query:r,params:{}}}matchRoute(t,s){const o=t.split("/").filter(Boolean),r=s.split("/").filter(Boolean);if(o.length!==r.length)return null;const n={};for(let i=0;i<o.length;i++)if(o[i].startsWith(":"))n[o[i].slice(1)]=decodeURIComponent(r[i]);else if(o[i]!==r[i])return null;return n}parseQueryParams(t){return t?t.split("&").reduce((s,o)=>{const[r,n]=o.split("=").map(decodeURIComponent);return s[r]=n??"",s},{}):{}}}const sa=f.createLogger({name:"intent-service"}),_h=e=>{jo(`/kos/intent/${e.type}`)?N(`/kos/intent/${e.type}`,e.options,{"kos.intent.type":e.type}):sa.info(`No subscribers for intent ${e.type}. Intent not sent.`)},Eh=async e=>new Promise(t=>{const{type:s,options:o}=e;if(jo(`/kos/intent/${e.type}`)){const r=Xe(),{unsubscribe:n}=j(r,c=>{clearTimeout(i),n(),c&&(c.headers=c.headers||{},c.headers["kos.intent.type"]=s,c.headers.responseId=r),t([null,{body:c==null?void 0:c.body,payload:c}])}),i=setTimeout(()=>{n(),t([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);N(`/kos/intent/${s}`,o,{"kos.intent.type":s,sync:r})}else sa.info(`No subscribers for intent ${e.type}. Intent not sent.`),t([null,{body:void 0,payload:void 0}])}),Mo=v.when,Xo=v.computed,z=v.runInAction,F=v.autorun,oa=v.reaction,er=v.observable,tr="Not Assigned",Ih="kos.trouble.added",Th="kos.trouble.removed";var re=(e=>(e.TroubleRank="kos.trouble.rank.mapper",e.TroubleColor="kos.trouble.color.mapper",e.TroubleRole="kos.trouble.role.mapper",e))(re||{}),Ot=(e=>(e.TIME_CHANGE="/kos/internal/time/time",e.DAY_CHANGE="/kos/internal/time/day",e.TIMEZONE_CHANGE="/kos/internal/time/timezone",e))(Ot||{});const ra=f.createLogger({name:"config-bean-service",group:"Services"}),sr=exports.BASE_URL,na=e=>(e==null?void 0:e.decimals)!==void 0,{postModel:$h,getOne:Oh}=Y.build({destinationAddress:"",basePath:`${sr}/kos/config/`}),ia=async(e,t,s="/api/kos/config")=>(ra.debug(`sending modify request for ConfigBean: ${e}`),$h({model:t,urlOverride:`${sr}${s}/${e}`})),aa=async(e,t="/api/kos/config")=>(ra.debug(`sending get request for ConfigBean: ${e}`),await Oh({urlOverride:`${sr}${t}/details/${e}/15`})),or=e=>e.toLowerCase()==="true"||e.toLowerCase()==="false",js=e=>{try{const t=Number(e);return!isNaN(t)}catch{return!1}};function ca(e=[]){return e.reverse().reduce((t,s)=>{const{overrides:o}=s;return o&&(t={...t,...o}),t},{})}function la(e,t="",s={}){for(const o in e)if(Object.prototype.hasOwnProperty.call(e,o)){const r=t?`${t}.${o}`:o;typeof e[o]=="object"&&e[o]!==null&&!Array.isArray(e[o])?la(e[o],r,s):s[r]=e[o]}return s}const da=(e,t)=>{const s=e.details[0].bean||ca(e.details[0].scopes),o=la(s);v.runInAction(()=>{const r={...o};t.props.setValues(r)})},ua=(e,t)=>{v.runInAction(()=>{e.changes.forEach(s=>{const o=s.attr;let r=s.currentValue,n=s.previousValue;typeof r=="string"&&or(r)&&(r=r.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof r=="string"&&js(r)&&(r=Number(r),n=Number(n)),t.props[o]=r,t.prevProps[o]=n})})},ha=e=>Object.fromEntries(e.props.entries),Dh=e=>t=>s=>e.build(t,s);var Sh=Object.defineProperty,Ah=Object.getOwnPropertyDescriptor,ga=(e,t,s,o)=>{for(var r=o>1?void 0:o?Ah(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Sh(t,s,r),r};function Ch(e,t){for(const s of e)if(new RegExp(`^${s}$`).test(t))return s}const rr="config-bean-model",Xt=f.getLogger(rr),Rh=Se("path");let ps=class{constructor(e,t){a(this,"_modifyConfigBean");a(this,"_getConfigBean");a(this,"_schema");a(this,"id");a(this,"path");a(this,"props");a(this,"prevProps");a(this,"serviceBasePath");Object.assign(this,t),this.id=e,this.path=t.path,this.serviceBasePath=t.serviceBasePath;const{modifyConfigBean:s=ia,getConfigBean:o=aa}=t;this._modifyConfigBean=s,this._getConfigBean=o,this.props=ye(),this.prevProps=ye()}get values(){return this.props.values}async ready(){Xt.debug(`readying config bean ${this.path}`),Xt.debug(`complete readying config bean ${this.path}`)}async load(){Xt.debug(`loading config bean ${this.path}`);const e=await this._getConfigBean(this.path,this.serviceBasePath);if(e!=null&&e.data){const t=e.data;da(t,this),Xt.debug(this.values);const s=e==null?void 0:e.data.details[0].schema;z(()=>{s&&(this._schema=s)})}}get schemaKeys(){var e;return Object.keys(((e=this._schema)==null?void 0:e.schema)||{})}getSchemaForProperty(e){var s,o;if(this.schemaKeys.includes(e))return(s=this._schema)==null?void 0:s.schema[e];const t=Ch(this.schemaKeys,e);if(t)return(o=this._schema)==null?void 0:o.schema[t]}async updateProperty(e,t){this.props[e]=t,await this.updateConfigBean()}async updateConfigBean(){const e=ha(this);await this._modifyConfigBean(this.path,e,this.serviceBasePath)}handleConfigBeanUpdated(e){ua(e,this)}};ga([R({topic:`/kos/config/${Rh}`,websocket:!0})],ps.prototype,"handleConfigBeanUpdated",1);ps=ga([O(rr)],ps);const At=new ae({class:ps,type:rr}),Bs=({path:e,lazy:t,serviceBasePath:s})=>(o,r)=>{o[P]=o[P]||{},o[P][r]={modelType:At.type,id:`${At.type}-${e}`,options:{path:e,serviceBasePath:s},lifecycle:x.INIT,lazy:t}},{URL:fa}=q(),{getOne:Lh,getAll:Ph}=Y.build({basePath:`${fa}/api/kos/regions/info`}),pa=async()=>await Lh({}),ma=async()=>await Ph({urlOverride:`${fa}/api/kos/regions`}),kh=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:pa,getRegions:ma},Symbol.toStringTag,{value:"Module"}));var Z=(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))(Z||{});const ya={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 xh(e,t){const s=t.id,o=t.units.reduce((r,n)=>{const i=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return r[n.name]=i,n.alias&&(r[n.alias]=i),r},{...ya});return{...e,...o}}function Fh(e,t){const s=t.id,o=t.units.reduce((r,n)=>{const i=r[n.measure]||{},c=i[s]||{};i[s]=c;const l=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return c[n.name]=l,Object.hasOwn(n,"default")&&Object.defineProperty(c,"default",{value:l,writable:!0,enumerable:!0,configurable:!0}),r[n.measure]=i,n.alias&&(r[n.alias]=i),r},{time:{[s]:{...ya}}});return Object.keys(o).forEach(r=>{e[r]={...e[r],...o[r]}}),e}function Nh(e,t){const s=t.id,o=t.units.reduce((r,n)=>{const i=r[n.measure]||{};return Object.hasOwn(n,"default")&&(i[s]=n.name),r[n.measure]=i,r},{time:{[s]:"millisecond"}});return Object.keys(o).forEach(r=>{e[r]={...e[r],...o[r]}}),e}var Uh=Object.defineProperty,jh=Object.getOwnPropertyDescriptor,nr=(e,t,s,o)=>{for(var r=o>1?void 0:o?jh(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Uh(t,s,r),r};const ls="region-info-model",at=f.createLogger({name:"region-info-model"});let Ct=class{constructor(e){a(this,"id");a(this,"unitSystemMap");a(this,"measureMap");a(this,"defaultMeasureMap");a(this,"regionMap");a(this,"timeFormats");a(this,"dateFormats");a(this,"unitSystems");a(this,"regionSource");a(this,"region");a(this,"regions",[]);a(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[Z.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[Z.family]}getDefaultUnitDecimalPlaces(e,t,s){if(!e||!t)throw Error("Measure and unit system are required");const o=s==="drt"?"second":s,r=this.measureMap[e];if(!r)throw Error(`No unit systems found for measure: ${e}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const n=r[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(r).join(", ")}`);const i=n[o||"default"];if(!i)throw Error(`No unit "${o||"default"}" found for measure: ${e} and unit system: ${t}. Unit should come from list of units: ${Object.keys(n).join(", ")}`);return i[Z.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 o=s[t.toLowerCase()];if(!o)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 o}convertByUnit(e,t,s){if(t[Z.family]!==s[Z.family])throw new Error(`Cannot convert between units of different families: ${t[Z.family]} and ${s[Z.family]}`);const o=t[Z.offset],r=t[Z.scale],n=s[Z.scale],i=s[Z.offset],c=s[Z.decimals];return((e-o)/(r/n)+i).toFixed(c)}convertByUnitName(e,t,s){const o=this.unitSystemMap[t],r=this.unitSystemMap[s];if(!o||!r)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,o,r)}convert(e,t,s){var c,l;if(t.unit&&s.unit)return this.convertByUnitName(e,t.unit,s.unit);const o=t.unit||"",r=s.unit||"";let n=this.unitSystemMap[o],i=this.unitSystemMap[r];if(!i&&s.measure&&s.system){const d=this.measureMap[s.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(c=d[s.system])==null?void 0:c.default,i||at.info("Could not find default unit for measure",s.measure)}if(!n&&t.measure&&t.system){const d=this.measureMap[t.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(l=d[t.system])==null?void 0:l.default,n||at.info("Could not find default unit for measure",t.measure)}return!n||!i?(at.warn("Could not find unit to convert to or from. Return value as is"),String(e)):this.convertByUnit(e,n,i)}async init(){at.debug("initializing region info")}async load(){at.debug("loading region info");const e=await ma();e&&(this.regions=e.data.map(s=>s.id),this.timeZoneMap=e.data.reduce((s,o)=>({...s,[o.id]:o.timeZones}),this.timeZoneMap),this.regionMap=e.data.reduce((s,o)=>({...s,[o.id]:o}),{}));const t=await pa();t&&(this.unitSystems=t.data.unitSystems.reduce((s,o)=>{const r={id:o.id,name:o.id};return s[o.id]=r,s},this.unitSystems),this.unitSystemMap=t.data.unitSystems.reduce(xh,{}),this.measureMap=t.data.unitSystems.reduce(Fh,{}),this.defaultMeasureMap=t.data.unitSystems.reduce(Nh,{}),this.timeFormats=t.data.timeFormats.reduce((s,o)=>({...s,[o.id]:o}),{}),this.dateFormats=t.data.dateFormats.reduce((s,o)=>({...s,[o.id]:o}),{}))}async ready(){var e,t;await((t=(e=this.regionSource).ready)==null?void 0:t.call(e))}};nr([Bs({path:"kos:service:region:settings"})],Ct.prototype,"regionSource",2);nr([Bs({path:"kos:service:region"})],Ct.prototype,"region",2);Ct=nr([O(ls)],Ct);const V={registration:{[ls]:{class:Ct,singleton:!0}},type:ls,factory:H.Singleton.create(ls)},ms=({source:e,defaultSystem:t="si",defaultMeasure:s})=>{let o={system:t,measure:s};return typeof e=="string"?o={...o,unit:e}:o={...o,...e},o},ir=(e,t,s)=>{const{model:o}=Ce(V.type);if(!o)throw new Error("RegionInfo model not found");if(!fs(o))throw new Error("RegionInfo model not ready");const r={system:o.defaultUnitSystem},n=ms({source:t}),i=ms({source:s||r,defaultMeasure:o.getUnitMeasure(n.unit||"")});return o.convert(e,n,i)};function on(e,t,s){const o=t.toLowerCase().replace(/_/g,"-").replace(/s$/,""),r=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,c=(s==null?void 0:s.minDecimals)??0;return new Intl.NumberFormat(r,{style:"unit",unit:o,unitDisplay:n,minimumFractionDigits:c,maximumFractionDigits:i}).format(e)}catch{return t}}const Bh=(e,t,s,o)=>{const r=ir(e,t,s),n=ms({source:t}),{model:i}=Ce(V.type);if(!i)throw new Error("RegionInfo model not found");const c=i.getUnitMeasure(n.unit||""),l={system:i.defaultUnitSystem},d=ms({source:s||l,defaultMeasure:i.getUnitMeasure(n.unit||"")}),u=i.getDefaultUnitForMeasure(c,d.system),h=i.getDefaultUnitDecimalPlaces(c,d.system),p={...o,minDecimals:(o==null?void 0:o.minDecimals)??h,maxDecimals:(o==null?void 0:o.maxDecimals)??h};return{value:r,unit:u||n.unit||"",display:on(r,u||n.unit||"",{...p,mode:"long"}),shortDisplay:on(r,u||n.unit||"",{...p,mode:"short"})}};function rn({start:e,end:t,count:s,decimals:o=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 r=(t-e)/(s-1),n=[];for(let i=0;i<s;i++){const c=Math.round(e+i*r);n.push(c.toFixed(o))}return n}function nn({start:e,end:t,interval:s,decimals:o=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 r=[];let n=e;for(;n<=t;)r.push(n.toFixed(o)),n+=s;return r[r.length-1]!==t.toString()&&r.push(t.toString()),r}const ke=(e,t)=>s=>!e||!t?s:js(s)?ir(Number(s),e,t):s,Kh=(e,t,s,o)=>{if((e==null?void 0:e.type)==="enum"||!(e!=null&&e.options))return[];if(e.options.type==="rangeCount")return rn(e.options).map(ke(s,o));if(e.options.type==="rangeInterval")return nn(e.options).map(ke(s,o));if(e.options.type==="list"){const{list:r}=e.options;return r.map(ke(s,o))}else{if(e.options.type==="unitSystemRangeCount"&&t)return rn(e.options.unitSystems[t]).map(ke(s,o));if(e.options.type==="unitSystemRangeInterval"&&t)return nn(e.options.unitSystems[t]).map(ke(s,o));if(e.options.type==="unitSystemList"&&t){const{list:r}=e.options.unitSystems[t];return r.map(ke(s,o))}}return[]},Gh=(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 Vh=Object.defineProperty,Hh=Object.getOwnPropertyDescriptor,ar=(e,t,s,o)=>{for(var r=o>1?void 0:o?Hh(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Vh(t,s,r),r};function Yh(e){return(e==null?void 0:e.type)==="enum"}function zh(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 qh(e,t){const s=new Date;s.setHours(0,0,0,0);const o=new Date(s.getTime()+e*1e3);return me.format(o,t)}const ds="config-bean-prop-model",xe=f.createLogger({name:"config-bean-prop-model"}),Wh=Se("path"),Zh=Se("serviceBasePath");let Rt=class{constructor(e,t){a(this,"id");a(this,"path");a(this,"attribute");a(this,"converter");a(this,"formatter");a(this,"optionsExpander");a(this,"serviceBasePath");a(this,"regionInfo");a(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 na(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?zh(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,o=this.bean.getSchemaForProperty(this.attribute),r=Yh(o)?o.values:Kh(o,s,t==null?void 0:t.from,t==null?void 0:t.to),n=r.length>0?r.map(c=>({label:c,value:c})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,r):this.optionsExpander:n}convertUnit(e,t,s){const o=(e==null?void 0:e.measure)||s,r=(e==null?void 0:e.system)||t,n=e==null?void 0:e.unit;return{measure:o,system:r,unit:n}}getConverterUnits(){const e=this.regionInfo.defaultUnitSystem,t=this.getConverter();if(!t)throw Error("No converter defined");const s=t.measure,o=this.convertUnit(t.from,"si",s),r=this.convertUnit(t.to,e,s);return{backend:o,display:r}}set value(e){this.updateProperty(e)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var r,n;const e=this.value,t=this.regionInfo.defaultUnitSystem,s=this.getConverter(),o=(s==null?void 0:s.measure)||((r=s==null?void 0:s.to)==null?void 0:r.measure);if(!isNaN(e)&&s&&o){const i=this.getDefaultUnitDecimalPlaces(o,t,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const l=this.getFormatterOptions(s);if(l){let d=String(e);return d=l.formatToParts(Number(e))[0].value,Number(d)}}catch(l){xe.info(`error formatting value ${e}`,l)}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:o,display:r}=this.getConverterUnits();return this.regionInfo.convert(Number(t),o,r)}return t||""}async activate(){xe.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 qh(e,s)}if(!isNaN(e))try{const t=this.getConverter(),s=this.getFormatterOptions(t);if(s){let o=String(e);return o=s.format(Number(e)),o}}catch(t){xe.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 o=t.formatToParts(Number(this.value)).find(r=>r.type==="unit");return(o==null?void 0:o.value)??this.getDefaultUnit(e)}}return this.getDefaultUnit(e)}get displayOptions(){var r;const e=this.bean.getSchemaForProperty(this.attribute),t=this.regionInfo.defaultUnitSystem,s=this.getConverter(),o=((r=s==null?void 0:s.to)==null?void 0:r.system)??t;return Gh(e,o)}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 o,r;const t=this.regionInfo.defaultUnitSystem,s=e==null?void 0:e.measure;return s?((o=e==null?void 0:e.to)==null?void 0:o.unit)||this.getDefaultUnitForMeasure(s,((r=e==null?void 0:e.to)==null?void 0:r.system)||t):this.getConverterFromFormat().unit}getFormatterOptions(e){var n,i,c;const t=this.regionInfo.defaultUnitSystem,s=e==null?void 0:e.measure,o=new Intl.NumberFormat().resolvedOptions().locale;let r=null;if(s||this.formatter){const l=s?{style:"unit",unit:this.getDefaultUnit(e)}:null,d=this.formatter||l;if(d){let u=typeof d=="function"?d(((n=e==null?void 0:e.to)==null?void 0:n.system)||t):d;s&&(u={unit:this.getDefaultUnit(e),...u},u.style==="unit"&&(u.maximumFractionDigits=u.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=e==null?void 0:e.to)==null?void 0:i.system)||t,(c=e==null?void 0:e.to)==null?void 0:c.unit)));try{r=new Intl.NumberFormat(o,{...u})}catch(h){xe.error(`error creating formatter ${u}. Returning the raw value`,h)}}else xe.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return r}getConverter(){var o,r,n,i,c,l,d,u,h,p,w;const{unit:e,measure:t}=this.getConverterFromFormat(),s=e==="drt"?"second":e;if(this.converter){const b=(o=this.converter)==null?void 0:o.measure,_=(n=(r=this.converter)==null?void 0:r.to)==null?void 0:n.measure,I=(c=(i=this.converter)==null?void 0:i.from)==null?void 0:c.measure,A=b||_||I||t,se=((d=(l=this.converter)==null?void 0:l.to)==null?void 0:d.unit)||this.regionInfo.getDefaultUnitForMeasure(A,((h=(u=this.converter)==null?void 0:u.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),we=((w=(p=this.converter)==null?void 0:p.to)==null?void 0:w.system)??this.regionInfo.getUnitSystem(se),rt=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:rt,...this.converter.from},to:{...this.converter.to,unit:se,system:we},measure:A}}if(s&&t){const b=this.regionInfo.getDefaultUnitForMeasure(t,this.regionInfo.defaultUnitSystem),_=this.regionInfo.getUnitSystem(s),I=this.regionInfo.getUnitSystem(b);return{measure:t,to:{unit:_===I?s:b}}}}async updateProperty(e){xe.debug(`updating property ${this.attribute} with value ${e}`);let t=e;if(this.getConverter()&&!isNaN(t)){const{backend:r,display:n}=this.getConverterUnits();t=this.regionInfo.convert(Number(t),n,r)}const o=Array.isArray(t)?JSON.stringify(t):String(t);await this.bean.updateProperty(this.attribute,o)}};ar([Ae({modelType:V.type})],Rt.prototype,"regionInfo",2);ar([Bs({path:Wh,serviceBasePath:Zh})],Rt.prototype,"bean",2);Rt=ar([O(ds)],Rt);const Re={registration:{[ds]:{class:Rt,singleton:!1}},type:ds,factory:H.Factory.create(ds)};function Jh(e){const{path:t,attribute:s,converter:o,formatter:r,lazy:n,optionsExpander:i,serviceBasePath:c}=e,l=o;return l&&(typeof l!="function"&&typeof l.from=="string"&&(l.from={unit:l.from}),typeof l!="function"&&typeof l.to=="string"&&(l.to={unit:l.to})),(d,u)=>{d[P]=d[P]||{},d[P][u]={modelType:Re.type,id:`${t}-${s}`,options:{path:t,attribute:s,serviceBasePath:c,converter:l,formatter:r,optionsExpander:i},lifecycle:x.INIT,lazy:n}}}class Qh{constructor(t,s){a(this,"futures");a(this,"defaultContext");a(this,"context");a(this,"disposers",new Map);a(this,"container");this.futures=er.map(new Map),this.context="",this.defaultContext=s||"",this.container=t,v.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 o=F(()=>{var r,n;(t.endState||t.progress)&&((n=(r=this.container)==null?void 0:r.onFutureUpdate)==null||n.call(r,t))});this.disposers.set(s||t.id,o)}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 cr{constructor(t){a(this,"disposer");a(this,"_future");a(this,"container");a(this,"onFutureUpdate");this._future=void 0,this.container=t,v.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=F(()=>{var o,r;(t.endState||t.progress)&&((r=(o=this.container)==null?void 0:o.onFutureUpdate)==null||r.call(o,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 f.error(t),t}}}const ba="future-model",st=et(ba),Ks=f.createLogger({name:"future-service",group:"Services"}),{isMock:Xh,URL:Ht}=q();var Ve=(e=>(e.Success="SUCCESS",e.Fail="FAIL",e.Aborted="ABORT",e.Canceled="CANCEL",e))(Ve||{});const{getAll:eg,modifyModel:tg,addModel:sg,deleteModel:og,postModel:rg}=Y.build({destinationAddress:"",basePath:`${Ht}/api/future`,mock:Xh}),ng=async()=>await eg({}),va=async(e,t="/api/kos/future")=>(Ks.info(`sending delete request for Future: ${e}`),await og({id:e,urlOverride:`${Ht}${t}/${e}`})),wa=async(e,t="/api/kos/future")=>(Ks.info("sending add request for Future"),await sg({model:e,urlOverride:`${Ht}${t}`})),ig=async(e,t,s="/api/kos/future")=>(Ks.info(`sending modify request for Future: ${e}`),tg({model:t,id:e,urlOverride:`${Ht}${s}/${e}`})),Ma=async(e,t="/api/kos/future")=>(Ks.info(`sending cancel request for Future: ${e}`),rg({urlOverride:`${Ht}${t}/${e}/cancel`,ordered:!0,model:{}})),lr=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}),dr=(e,t)=>{f.debug(`future dto ${e.id} end state ${e.endState}`),f.debug(`future model ${t.id} end state ${t.endState}`),t.endState?f.debug(`future model ${t.id} is already complete`):(f.debug(`updating future model ${t.id}`),v.runInAction(()=>{const s=lr(e);z(()=>{Object.keys(s).forEach(o=>{o==="id"?(t.futureId=s.id,s.tracker||(t.id=s.id)):o==="tracker"?t.id=s.tracker:t[o]=s[o]})})}))},_a=e=>t=>s=>e.build(String(t),s),ur=e=>t=>Zi(lr,_a(e)(t.tracker||t.id))(t);var ag=Object.defineProperty,cg=Object.getOwnPropertyDescriptor,Ea=(e,t,s,o)=>{for(var r=o>1?void 0:o?cg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&ag(t,s,r),r};const lo=f.getLogger(st.type);let ys=class{constructor(e,t,s){a(this,"logger");a(this,"_cancelFuture");a(this,"futureId");Object.assign(this,t),this.logger=s.logger,this.id=e,this.futureId=t.id,this.namespace=t.namespace||"kos",this._cancelFuture=Ma,Mo(()=>this.status===Ve.Success||this.status===Ve.Fail,()=>{lo.info(`Future ${this.id} has completed with status ${this.status}`),Oe(this)})}async load(){lo.debug(`loading Future ${this.id}`)}unload(){lo.info(`unloading Future ${this.id}`)}async cancelFuture(){const e=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await Mo(()=>this.futureId!==tr),await this._cancelFuture(this.futureId,e)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var c,l;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",o=0;for(const[d,u]of Object.entries(t))if(Math.abs(e)>=u){s=d,o=Math.round(e/u);break}const n=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(o,s);return n.length===3?`${((c=n[1])==null?void 0:c.value)??0} ${((l=n[2])==null?void 0:l.value)??""}`:"0 seconds"}handleFutureUpdated(e){this.logger.debug(`Future ${this.id} updated. future: ${e.id} endState: ${e.endState} progress: ${e.progress} remainingTimeMs: ${e.remainingTimeMs}`),dr(e,this)}};Ea([R({topic:`kos.future/${hs}`})],ys.prototype,"handleFutureUpdated",1);ys=Ea([O(st.type)],ys);const Ia=ys,Ta=Zo();var lg=Object.defineProperty,dg=Object.getOwnPropertyDescriptor,$a=(e,t,s,o)=>{for(var r=o>1?void 0:o?dg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&lg(t,s,r),r};const Oa="browser-router-model",ug="kos.http.request",hg="kos.http.response";let bs=class{constructor(e,t,s){a(this,"_id");a(this,"logger");a(this,"router");this._id=e,this.logger=s.logger,this.router=new ta}get id(){return this._id}async handleRequest(e,t){const s=t.headers["src-addr"],o=t.headers["dst-addr"],r=t.headers.url,n=t.headers.method,i=t.headers["request-id"],c={id:i,method:n,path:r,body:e};let l=200;const d={send:u=>{this.logger.debug(`sending response to ${o}`),this.logger.debug(u),Ri({msg:u,options:{responseId:i,destinationAddress:s,type:hg,sourceAddress:o,status:l}})},status:function(u){return l=u,this}};if(c.path==="/openapi.json"){d.send(this.router.generateOpenApiSpec());return}await this.router.handle(c,d)}use(e,t,...s){this.router.use(e,t,...s)}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};$a([R({topic:ug})],bs.prototype,"handleRequest",1);bs=$a([O(Oa)],bs);const Gs=new pe({class:bs,type:Oa}),Da="future-container-model",be=et(Da),Sa=e=>ur(st)(e),gg=e=>{const t=Sa(e);return be.build(be.type,{}).addFutureModel(t),t},fg=e=>be.build(be.type,{}).getFuture(String(e)),De={buildFutureModel:Sa,initiateFuture:gg,getFuture:fg};var pg=Object.defineProperty,mg=Object.getOwnPropertyDescriptor,hr=(e,t,s,o)=>{for(var r=o>1?void 0:o?mg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&pg(t,s,r),r};const es=f.getLogger(be.type);let Lt=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_deleteFuture");a(this,"_addFuture");a(this,"_futures");a(this,"createModel");a(this,"deleteModel");const{deleteFuture:o=va,addFuture:r=wa}=t;this.logger=s.logger,this._deleteFuture=o,this._addFuture=r,this.id=e,this._futures=new de,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){es.error("error deleting a Future"),es.error(t)}}async createFuture(e){try{const t=await this._addFuture(e),s=t==null?void 0:t.data;if(s){const o=ur(st)(s);return this.addFutureModel(o),o}}catch(t){throw es.error("error creating a Future"),es.error(t),t}}handleFutureUpdated(e,t){const s=De.buildFutureModel(e);this.addFutureModel(s);const o=`kos.future/${e.tracker||e.id}`;this.logger.debug(`publishing future update to ${o}`),N(o,t.body,t.headers)}};hr([ie],Lt.prototype,"_futures",2);hr([R({topic:"kos.future"})],Lt.prototype,"handleFutureUpdated",1);Lt=hr([O(be.type)],Lt);const Aa=Lt,{URL:Yt}=q(),{getOne:yg,postModel:bg,deleteModel:Ca}=Y.build({basePath:`${Yt}/api/keyVal`}),_o=f.createLogger({name:"key-value-service",group:"Services"}),Ra=async(e,t)=>{await Ca({urlOverride:`${Yt}/api/keyVal/${e}/${t}`,id:t})},La=async(e,t,s)=>{const o=await bg({urlOverride:`${Yt}/api/keyVal/${e}/${t}`,model:s.toString()});if((o==null?void 0:o.status)!==200)throw _o.error("Failed to update studio-state data",o),new Error(`Failed to update studio-state data for namespace ${e}`);return o.data},Pa=async(e="studio")=>{_o.debug("sending GET for studio-state");const t=await yg({urlOverride:`${Yt}/api/keyVal/${e}`});if((t==null?void 0:t.status)!==200)throw _o.error("Failed to retrieve studio-state data",t),new Error(`Failed to retrieve studio-state data for namespace ${e}`);return t.data},vg=async e=>{await Ca({urlOverride:`${Yt}/api/keyVal/${e}}`,id:""})},wg=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Ra,deleteKeyValueNamespace:vg,getKeyValue:Pa,updateKeyValue:La},Symbol.toStringTag,{value:"Module"}));var Mg=Object.defineProperty,_g=Object.getOwnPropertyDescriptor,gr=(e,t,s,o)=>{for(var r=o>1?void 0:o?_g(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Mg(t,s,r),r};const ka="key-value-model";let Pt=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"namespace");a(this,"data");this.id=e,this.logger=s.logger,this.data=ye(),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 La(this.namespace,e,t),this.data[e]=t):(await Ra(this.namespace,e),this.data[e]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const e=await Pa(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)}};gr([R({topic:"/keyVal/set"})],Pt.prototype,"handleStateUpdate",1);gr([R({topic:"/keyVal/remove"})],Pt.prototype,"handleStateDelete",1);Pt=gr([O(ka)],Pt);const fr=new ae({class:Pt,type:ka}),{URL:zt}=q(),{postModel:pr,getOne:Eg}=Y.build({basePath:`${zt}/api/kos-time`});f.createLogger({name:"kos-time-service",group:"Services"});const xa=async e=>{const t=await pr({model:e,urlOverride:`${zt}/api/kos/time/time`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},Fa=async e=>{const t=await pr({model:e,urlOverride:`${zt}/api/kos/time/date`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},Na=async e=>{const t=await pr({model:{},urlOverride:`${zt}/api/kos/time/timezone?tz=${e}`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data},Ua=async()=>{const e=await Eg({urlOverride:`${zt}/api/kos/time/timezone`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data.timeZone},Ig=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:Ua,setDate:Fa,setTime:xa,setTimezone:Na},Symbol.toStringTag,{value:"Module"}));var Tg=Object.defineProperty,$g=Object.getOwnPropertyDescriptor,Vs=(e,t,s,o)=>{for(var r=o>1?void 0:o?$g(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Tg(t,s,r),r};const lt="kos-time-model",Og="/kos/time/time",Dg="/kos/time/day",Sg="/kos/time/timezone";let He=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"timezone");this.id=e,this.logger=s.logger,this.timezone=""}async updateSystemTime(e){await xa(e)}async updateSystemDate(e){await Fa(e)}async updateSystemTimezone(e){await Na(e)}handleTimeChange(){N(Ot.TIME_CHANGE,{})}handleDayChange(){N(Ot.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),N(Ot.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const e=await Ua();this.setTimezone(e)}setTimezone(e){this.timezone=e}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};Vs([R({topic:Og,websocket:!0})],He.prototype,"handleTimeChange",1);Vs([R({topic:Dg,websocket:!0})],He.prototype,"handleDayChange",1);Vs([R({topic:Sg,websocket:!0})],He.prototype,"handleTimeZoneChange",1);He=Vs([O(lt)],He);const vs={registration:{[lt]:{class:He,singleton:!0}},type:lt,predicate:te(lt),factory:H.Singleton.create(lt)};var Ag=Object.defineProperty,Cg=Object.getOwnPropertyDescriptor,ja=(e,t,s,o)=>{for(var r=o>1?void 0:o?Cg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Ag(t,s,r),r};const Ba="log-block-container-model";let ws=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new de({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}`)}};ja([ie],ws.prototype,"_models",2);ws=ja([O(Ba)],ws);const Le=Zo(),Rg=f.createLogger({name:"log-stream-container-service",group:"Services"}),Ka=()=>{var o;const e=ee(),s=(e==null?void 0:e.connId)||((o=window==null?void 0:window.kosBridge)==null?void 0:o.call(window,"connId"));return f.error(`getKosConnectionId: ${s}`),s},ot=Ka(),Lg="/api/kos/logs/node/{nodeId}/streams",Ga=async()=>(Rg.debug("sending GET for log-stream-container"),await Le.get(Lg,{path:{nodeId:"primary"}},{destinationAddress:ot})),Va=async(e,t="primary")=>{await Le.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:t,stream:e}},void 0,{destinationAddress:ot})},Ha=async e=>{await Le.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:e}},void 0,{destinationAddress:ot})},Pg=async()=>{await Le.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:ot})},Ya=async e=>await Le.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:e}},{destinationAddress:ot}),za=async(e,t)=>await Le.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:e,blockId:t}},{destinationAddress:ot}),kg=Object.freeze(Object.defineProperty({__proto__:null,createOverride:Pg,getKosConnectionId:Ka,getLogStreamBlock:za,getLogStreamBlocks:Ya,getLogStreams:Ga,subscribeToLogStream:Va,unsubscribeFromLogStream:Ha},Symbol.toStringTag,{value:"Module"}));var xg=Object.defineProperty,Fg=Object.getOwnPropertyDescriptor,Ng=(e,t,s,o)=>{for(var r=o>1?void 0:o?Fg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&xg(t,s,r),r};const qa="log-block-model";let Eo=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"nodeId");a(this,"stream");a(this,"blockNum");a(this,"startLineNum");a(this,"endLineNum");a(this,"startTime");a(this,"endTime");a(this,"lineCount");a(this,"lines");a(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 za(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}`)}};Eo=Ng([O(qa)],Eo);const kt=new ae({class:Eo,type:qa}),Hs=new ae({class:ws,type:Ba});Hs.addRelatedModel(kt);var Ug=Object.defineProperty,jg=Object.getOwnPropertyDescriptor,Wa=(e,t,s,o)=>{for(var r=o>1?void 0:o?jg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Ug(t,s,r),r};const Za="log-stream-model";let Ms=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"nodeId");a(this,"_blocks");a(this,"name");a(this,"currentBlockId");a(this,"isResetting");a(this,"generatorInstance");a(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=Hs.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 o;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=kt.instance(`${e.stream}-block-${e.blockNum}`).options(s).build(),this._blocks.addModel(t)),t&&t.updateModel(s),(!this.currentBlock||e.blockNum>=((o=this.currentBlock)==null?void 0:o.blockNum))&&(this.currentBlockId=`${e.stream}-block-${e.blockNum}`)}addBlock(e){var s;const t=kt.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 Va(this.name)}async unsubscribe(){await Ha(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 Ya(this.name);if(e){this.logger.error(`Error loading log stream: ${e}`);return}if(t)for(const o of t)this.addBlock(o);const s=this._blocks.data[this._blocks.data.length-1];if(s&&await s.syncLines(),this._blocks.data.length>1){const o=this._blocks.data[this._blocks.data.length-2];o&&await o.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,o=this.currentBlockId;const r=oa(()=>{const n=this.currentBlock;return n?{blockId:this.currentBlockId,lineCount:n.lines.length}:null},n=>{const i=this.currentBlock;if(i)if(o!==(n==null?void 0:n.blockId))o=n==null?void 0:n.blockId,s=0,e.push(...i.lines);else{const c=i.lines.slice(s);e.push(...c),s+=c.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{r()}}};Wa([ie],Ms.prototype,"_blocks",2);Ms=Wa([O(Za)],Ms);const Dt=new ae({class:Ms,type:Za});var Bg=Object.defineProperty,Kg=Object.getOwnPropertyDescriptor,Pe=(e,t,s,o)=>{for(var r=o>1?void 0:o?Kg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Bg(t,s,r),r};const Ja="log-stream-container-model",Gg="/kos/logs/subscription/addBlock/*",Vg="/kos/logs/subscription/updateBlock/*",Hg="/kos/logs/subscription/removeBlock/*",Yg="/kos/logs/subscription/lines/*",Qa="/kos/logs/streams/add/*";let he=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"selectedStream");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new de({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: ${Qa}`);const t=e.stream,s=Dt.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,o=this.models.getModel(s);o&&o.addBlock(e)}handleRemoveBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,o=this.models.getModel(s);o&&o.removeBlock(e.blockNum)}handleUpdateBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,o=this.models.getModel(s);o&&o.updateBlock(e)}handleLogLine(e,t){var r;this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,o=this.models.getModel(s);o&&((r=o.currentBlock)==null||r.addLines(e.lines))}async init(){this.logger.debug(`initializing log-stream-container container ${this.id}`)}async subscribeToLogStream(e){const t=Dt.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 Ga();if(e){this.logger.error(`Error loading log-streams: ${e}`);return}t&&t.forEach(s=>{const o=Dt.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(o)})}};Pe([ie],he.prototype,"_models",2);Pe([R({topic:[Qa],websocket:!0})],he.prototype,"handleStreamAdded",1);Pe([R({topic:[Gg],websocket:!0})],he.prototype,"handleAddBlock",1);Pe([R({topic:[Hg],websocket:!0})],he.prototype,"handleRemoveBlock",1);Pe([R({topic:[Vg],websocket:!0})],he.prototype,"handleUpdateBlock",1);Pe([R({topic:[Yg],websocket:!0})],he.prototype,"handleLogLine",1);he=Pe([O(Ja)],he);const qt=new pe({class:he,type:Ja});qt.addRelatedModel(Dt);qt.addRelatedModel(Hs);qt.addRelatedModel(kt);const zg=e=>e.rank!==void 0,qg=e=>e.visibleRole!==void 0,Wg=e=>e.color!==void 0,Zg=e=>{const t=e.info;return zg(t)?t.rank:0},Jg=e=>{const t=e.info;return Wg(t)?t.color:"orange"},Qg=e=>{const t=e.info;return qg(t)?t.visibleRole:"TECHNICIAN"},{URL:mr}=q(),{getAll:Xg,postModel:Xa}=Y.build({basePath:`${mr}/api/kos/troubles`}),ec=async()=>await Xg({}),tc=async(e,t)=>{try{const s=await Xa({model:{},urlOverride:`${mr}/api/kos/troubles/resolve/${e}`,tracker:t});return s!=null&&s.data&&De.initiateFuture(s.data),s.data}catch{const o={id:t||"",endState:Ve.Fail,tracker:t,reason:"Failed to resolve trouble"};return De.initiateFuture(o),o}},ef=async(e,t)=>{try{const s=await Xa({model:e,urlOverride:`${mr}/api/kos/troubles/resolve/`,tracker:t});return s!=null&&s.data&&De.initiateFuture(s.data),s.data}catch{const o={id:t||"",endState:Ve.Fail,tracker:t,reason:"Failed to resolve troubles"};return De.initiateFuture(o),o}},tf=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:ef,getTroubles:ec,resolveTrouble:tc},Symbol.toStringTag,{value:"Module"})),_s="troubleDataMapper",ts=new Map;Yo(_s,{register:(e,t)=>{var s;ts.has(e)||ts.set(e,[]),(s=ts.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=ts.get(e);if(!s)return{...t.data};const o=s.map(i=>i(t));return(await Promise.allSettled(o)).reduce((i,c)=>(c.status==="fulfilled"?i={...i,...c.value}:f.info(`Trouble mapper ${e} failed: ${c.reason}`),i),{...t.data})}});const Wt="troubleMapper",ss=new Map;Yo(Wt,{register:(e,t)=>{var s;ss.has(e)||ss.set(e,[]),(s=ss.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=ss.get(e);if(!s)return[];const o=s.map(i=>i(t)),n=(await Promise.allSettled(o)).map(i=>i.status==="fulfilled"?i.value:(f.info(`Trouble mapper ${e} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});C[Wt].register("nozzle",async e=>[e.data.nozzlePath]);C[Wt].register("path",async e=>[e.data.path]);const sf=async e=>{const t=new Set,s=e.ifaces,o=s==null?void 0:s.map(n=>C[Wt].execute(n,e));return(await Promise.allSettled(o)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>t.add(i))}),Array.from(t)},sc=async e=>{const t=e.ifaces,s=t==null?void 0:t.map(i=>C[_s].execute(i,e)),o=C[_s].execute(e.type,e);s.push(o);const n=(await Promise.allSettled(s)).reduce((i,c)=>(c.status==="fulfilled"&&(i={...i,...c.value}),i),{});return{...e.data,...n}};class of{constructor(){a(this,"type","ResolvableTrouble");a(this,"title","Resolvable Trouble");a(this,"subtitle","Trouble")}}class rf{constructor(){a(this,"type","BlockPumpTrouble");a(this,"title","Block Pump Trouble");a(this,"subtitle","Trouble")}}class Fe{static getHandler(t){switch(t){case"ResolvableTrouble":return new of;case"BlockPumpTrouble":return new rf;default:return}}}var nf=Object.defineProperty,af=Object.getOwnPropertyDescriptor,oc=(e,t,s,o)=>{for(var r=o>1?void 0:o?af(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&nf(t,s,r),r};const dt="trouble-model";function os(e){return typeof e.shouldDefer=="boolean"}let Es=class{constructor(e,{resolvable:t,tags:s,info:o,id:r,clientData:n,rank:i,ifaces:c,type:l,group:d,createTime:u,role:h,color:p,...w},b){a(this,"id");a(this,"logger");a(this,"_troubleId");a(this,"_resolvable");a(this,"type");a(this,"futureHandler");a(this,"ifaces");a(this,"clientData");a(this,"info");a(this,"role");a(this,"color");a(this,"tags");a(this,"data");a(this,"rank");a(this,"group");a(this,"createTime");a(this,"_mapped",{});this.id=e,this.logger=b.logger,this.type=l,this._troubleId=r,this._resolvable=!!t,this.ifaces=c,this.rank=i,this.role=h,this.color=p,this.tags=s,this.info=o,this.group=d,this.createTime=u,this.clientData=n,this.data={},Object.assign(this.data,w),this.futureHandler=new cr(this)}getTitleWithContext(e){var s,o;const t=e?(o=(s=Fe.getHandler(this.type))==null?void 0:s.context)==null?void 0:o[e]:Fe.getHandler(this.type);return(t==null?void 0:t.title)||"Trouble"}getSubtitleWithContext(e){var s,o;const t=e?(o=(s=Fe.getHandler(this.type))==null?void 0:s.context)==null?void 0:o[e]:Fe.getHandler(this.type);return(t==null?void 0:t.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var e;return((e=Fe.getHandler(this.type))==null?void 0:e.title)||"Trouble"}get subtitle(){var e;return((e=Fe.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 sc(this)}get deferredCompanion(){const e=wo(this.id,t=>os(t));if(e&&os(e.modelData))return e.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const e=wo(this.id,t=>os(t));return e&&os(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 tc(this._troubleId,e)}};oc([Cr()],Es.prototype,"resolve",1);Es=oc([O(dt)],Es);const xt={registration:{[dt]:{class:Es,singleton:!1}},type:dt,predicate:te(dt),factory:H.Factory.create(dt)};var cf=Object.defineProperty,lf=Object.getOwnPropertyDescriptor,Ys=(e,t,s,o)=>{for(var r=o>1?void 0:o?lf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&cf(t,s,r),r};const an=f.createLogger({name:"trouble-container-model"});function cn(e){return C.propertyMapper.hasMapper(re.TroubleRank)?C.propertyMapper.executeMapper(re.TroubleRank,e):Zg(e)}function ln(e){return(C.propertyMapper.hasMapper(re.TroubleColor)?C.propertyMapper.executeMapper(re.TroubleColor,e):Jg(e)).toLowerCase()}function dn(e){return(C.propertyMapper.hasMapper(re.TroubleRole)?C.propertyMapper.executeMapper(re.TroubleRole,e):Qg(e)).toLowerCase()}const df="trouble-container-model";class X{}a(X,"INDEX_TROUBLES_BY_IFACE","byIface"),a(X,"INDEX_TROUBLES_BY_TYPE","byType"),a(X,"INDEX_TROUBLES_BY_GROUP","byGroup"),a(X,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),a(X,"SORT_KEY_RANK","rank"),a(X,"TROUBLES_DEFERRED","true");let Ye=class{constructor(e){a(this,"id");a(this,"troubles");this.id=e,this.troubles=new de({indexMap:{[X.INDEX_TROUBLES_BY_IFACE]:sf,[X.INDEX_TROUBLES_BY_TYPE]:"type",[X.INDEX_TROUBLES_BY_GROUP]:"group",[X.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:X.SORT_KEY_RANK,parentId:e})}async load(){an.debug("loading trouble container");const e=await ec();try{e==null||e.data.forEach(t=>{const s={...t,rank:cn(t),color:ln(t),role:dn(t),id:String(t.id)},o=xt.factory(`trouble-${t.id}`)(s);this.troubles.addModel(o)})}catch(t){throw an.error(t),t}}handleTroubleRemoved(e){const t=`trouble-${e}`,s=this.troubles.getModel(t);this.troubles.removeModel(t),s&&Oe(s)}handleTroubleAdded(e){const t={...e,rank:cn(e),color:ln(e),role:dn(e),id:String(e.id)};if(t.role==="NONE")return;const s=xt.factory(`trouble-${e.id}`)(t);this.troubles.addModel(s)}};Ys([ie],Ye.prototype,"troubles",2);Ys([R({topic:"/kos/trouble/remove",websocket:!0,lifecycle:x.INIT})],Ye.prototype,"handleTroubleRemoved",1);Ys([R({topic:"/kos/trouble/add",websocket:!0})],Ye.prototype,"handleTroubleAdded",1);Ye=Ys([O(df)],Ye);const rs="trouble-container-model",ze={registration:{[rs]:{class:Ye,singleton:!0}},type:rs,predicate:te(rs),factory:H.Singleton.create(rs)},{URL:rc}=q(),{getAll:uf}=Y.build({basePath:`${rc}/api/kos/ota`}),un=f.createLogger({name:"ota-service",group:"Services"}),hf=async()=>{un.debug("sending GET request to /api/kos/ota/artifacts");const e=await uf({urlOverride:`${rc}/api/kos/ota/artifacts`});return un.debug("getArtifacts - response:",e),e==null?void 0:e.data};var gf=Object.defineProperty,ff=Object.getOwnPropertyDescriptor,zs=(e,t,s,o)=>{for(var r=o>1?void 0:o?ff(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&gf(t,s,r),r};const nc="ota-model",pf=e=>{let t=null;for(const s in e){const o=e[s],r=o.lastUpdateTime;(!t||t.lastUpdateTime<r)&&(t=o)}return t},uo=e=>{const t=e.artifactInfo,s=pf(e.requests),o=(t==null?void 0:t.identifier)||(s==null?void 0:s.kabId);if(!o)return;let r;switch(e.status){case"INSTALLED":r="ready";break;case"INVALID":r="error";break;case"MISSING":r=((s==null?void 0:s.currentSize)||0)>0?"downloading":"idle";break;case"STAGED":r="pending"}const n=t===void 0;return{id:o,manifest:n,label:t==null?void 0:t.version,name:t==null?void 0:t.name,status:r,error:r==="error"?s==null?void 0:s.lastErrorReason:void 0,errorCount:r==="error"?s==null?void 0:s.errorCount:0,progress:r==="downloading"&&s&&!n?s.currentSize/(t==null?void 0:t.size)*100:void 0,size:t==null?void 0:t.size}};let qe=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"data",new Xi);a(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 hf();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)}}};zs([Ae({modelType:ze.type})],qe.prototype,"troubleContainer",2);zs([R({topic:"/kos/ota/artifacts/all",websocket:!0})],qe.prototype,"handleAllArtifacts",1);zs([R({topic:"/kos/ota/artifacts/changed",websocket:!0})],qe.prototype,"handleChangedArtifacts",1);qe=zs([O(nc)],qe);const Is=new pe({class:qe,type:nc}),hn=f.createLogger({name:"software-info-service",group:"Services"}),ic=async()=>{hn.debug("sending GET for software-info");const[e,t]=await Ta.get("/api/kos/manifest/info");if(!t)throw hn.error("Failed to fetch software-info",e),new ce("Failed to fetch software-info");return t},mf=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:ic},Symbol.toStringTag,{value:"Module"}));var yf=Object.defineProperty,bf=Object.getOwnPropertyDescriptor,vf=(e,t,s,o)=>{for(var r=o>1?void 0:o?bf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&yf(t,s,r),r};const ut="software-info-model";let Io=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(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,o)=>(s[o[t]]=[...s[o[t]]||[],o],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const e=await ic(),t=(e==null?void 0:e.nodes)||{};z(()=>{const o=Object.keys(t).map(r=>t[r][0]).map(r=>({nodeName:r.node,group:this.groupBy(r.artifacts,"group")}));this.nodes=o})}catch(e){e instanceof ce&&this.logger.error("Failed to fetch software-info",e)}}};Io=vf([O(ut)],Io);const Ts={registration:{[ut]:{class:Io,singleton:!1}},type:ut,predicate:te(ut),factory:H.Factory.create(ut)},{URL:ac}=q(),{getOne:wf}=Y.build({basePath:`${ac}/api/kos/state`}),Mf=f.createLogger({name:"state-bean-service",group:"Services"}),cc=async({path:e})=>(Mf.debug("sending GET for state-bean"),await wf({urlOverride:`${ac}/api/kos/state/${e}`})),_f=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:cc},Symbol.toStringTag,{value:"Module"}));var Ef=Object.defineProperty,If=Object.getOwnPropertyDescriptor,lc=(e,t,s,o)=>{for(var r=o>1?void 0:o?If(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Ef(t,s,r),r};const ht="state-bean-model",Tf=Se("path");let $s=class{constructor(e,t,s){a(this,"id");a(this,"path");a(this,"props");a(this,"logger");this.id=e,this.logger=s.logger,this.props=er.map(new Map),po(t,this)}updateModel(e){po(e,this)}handleConfigBeanUpdated(e){Object.entries(e).forEach(([t,s])=>{let o=s;typeof o=="string"&&or(o)&&(o=o.toLowerCase()=="true"),typeof o=="string"&&js(o)&&(o=Number(o)),this.props.set(t,o)})}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 cc({path:this.path});e!=null&&e.data&&this.updateProps(e.data)}};lc([R({topic:`/kos/state/${Tf}`,websocket:!0})],$s.prototype,"handleConfigBeanUpdated",1);$s=lc([O(ht)],$s);const Ft={registration:{[ht]:{class:$s,singleton:!1}},type:ht,predicate:te(ht),factory:H.Factory.create(ht)};var $f=Object.defineProperty,Of=Object.getOwnPropertyDescriptor,dc=(e,t,s,o)=>{for(var r=o>1?void 0:o?Of(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&$f(t,s,r),r};const gt="state-prop-model",gn=Se("path");let Os=class{constructor(e,t,s){a(this,"id");a(this,"path");a(this,"attribute");a(this,"logger");a(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())??""}};dc([Ae({modelType:Ft.type,id:`state-bean-${gn}`,options:{path:gn}})],Os.prototype,"stateBean",2);Os=dc([O(gt)],Os);const yr={registration:{[gt]:{class:Os,singleton:!1}},type:gt,predicate:te(gt),factory:H.Factory.create(gt)},{URL:Df}=q(),{getAll:Sf}=Y.build({basePath:`${Df}/api/state-prop`}),Af=f.createLogger({name:"state-prop-service",group:"Services"}),Cf=async()=>(Af.debug("sending GET for state-prop"),await Sf({})),Rf=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:Cf},Symbol.toStringTag,{value:"Module"})),{URL:br}=q(),{getOne:uc}=Y.build({basePath:`${br}/api/translation`}),St=f.createLogger({name:"translation-service",group:"Services"}),Lf=()=>{const e=window.location.origin,t=ee();return(t==null?void 0:t.host)||e},hc=async(e,t)=>{St.debug("sending GET for translation");const s=t??Lf();try{const o=await fetch(`${s}${e}`);return o.status!==200?(St.warn(`Failed to fetch translations at ${e}: ${o.status}`),{}):await o.json()}catch(o){throw St.error("Error fetching translations",o),o}},Pf=async()=>{St.debug("getting localization descriptor");const e=await uc({urlOverride:`${br}/api/system/kos/localization`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get tool localization descriptor ${e==null?void 0:e.status}`);return e.data},gc=e=>async()=>{St.debug("getting kos localization descriptor");const t=await uc({urlOverride:`${br}/api/kos/localization/contexts`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get tool localization descriptor ${t==null?void 0:t.status}`);return t.data[e]},fc="langResolver";var kf=Object.defineProperty,xf=Object.getOwnPropertyDescriptor,Ff=(e,t,s,o)=>{for(var r=o>1?void 0:o?xf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&kf(t,s,r),r};const ft="translation-model";function Nf(e){const t=typeof e=="string",s=t?!1:!!(e!=null&&e.data)&&typeof(e==null?void 0:e.data)!="string",o=t?e:e==null?void 0:e.defaultValue,r=t||e==null?void 0:e.context,n=t?void 0:s?e==null?void 0:e.data:e;return{isBasicOptions:t,defaultValue:o,context:r,data:n}}function pc(e,t=""){return Object.keys(e).reduce((s,o)=>{const r=t?`${t}.${o}`:o;if(typeof e[o]=="object"&&e[o]!==null){const n=pc(e[o],r);return{...s,...n}}else return{...s,[r]:e[o]}},{})}function mc(e,t){const s={...e};for(const o in t)Object.prototype.hasOwnProperty.call(t,o)&&(typeof t[o]=="object"&&t[o]!==null&&typeof e[o]=="object"&&e[o]!==null?s[o]=mc(e[o],t[o]):s[o]=t[o]);return s}const To=(e,t)=>{const s=/__(.*?)__/g,o=e.replace(s,(r,n)=>Object.prototype.hasOwnProperty.call(t||{},n.trim())?t==null?void 0:t[n.trim()]:r);return o===e?o:s.test(o)?To(o,t):o},ns=(e,t,s)=>{const o=/{{(.*?)}}/g,n=To(e,t).replace(o,(c,l)=>Object.prototype.hasOwnProperty.call(s||{},l.trim())?s==null?void 0:s[l.trim()]:c);return To(n,t)},fn=(e,t)=>{if(t.includes(":")){const[s,o]=t.split(":");return{namespace:s,key:o}}else return{namespace:e,key:t}};let $o=class{constructor(e,t,s){a(this,"id");a(this,"namespace");a(this,"descriptor");a(this,"defaultLocale");a(this,"currentLocale");a(this,"bundleResolver");a(this,"data");a(this,"logger");a(this,"resolver");a(this,"disposer");a(this,"context");a(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(fc),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(o=>{if(this.bundleResolver){const r=k.getContext(this.id);return this.bundleResolver(this.namespace,o,r)}try{const r=this.resolver(this.namespace,o);return hc(r,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(t);z(()=>{const o=s.reduce((r,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${e[i]}`,n.value),n.value&&(r=mc(r,n.value))):this.logger.error(`failed to load translation ${this.id} for ${e[i]}`),r),{});this.data=pc(o)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(e){const{namespace:t,key:s}=fn(this.namespace,e);if(t!==this.namespace){const o=this.context.getModel(t);return o?o.exists(s):!1}return!!this.data[s]}resolveKey(e,t){if(!e)return this.logger.debug("key is empty"),"";const{defaultValue:s,context:o,data:r}=Nf(t),{namespace:n,key:i}=fn(this.namespace,e),c=`${i}_${o}`;if(n!==this.namespace){const l=this.context.getModel(n);return l?l.resolveKey(i,t):i}if(o&&this.data[c]){const l=this.data[c];return Array.isArray(l)?l.map(d=>ns(d,this.data,r)):ns(this.data[c],this.data,r)}if(this.data[i]){const l=this.data[c];return Array.isArray(l)?l.map(d=>ns(d,this.data,r)):ns(this.data[i],this.data,r)}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=v.reaction(()=>this.currentLocale,(e,t)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${t} to ${e}`),this.loadTranslations()})}};$o=Ff([Us(),O(ft)],$o);const Ds={registration:{[ft]:{class:$o,singleton:!1}},type:ft,predicate:te(ft),factory:H.Factory.create(ft)};var Uf=Object.defineProperty,jf=Object.getOwnPropertyDescriptor,yc=(e,t,s,o)=>{for(var r=o>1?void 0:o?jf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Uf(t,s,r),r};const pt="translation-container-model",Bf=(e,t="/")=>e.join(t).replace(new RegExp(t+"{1,}","g"),t);function Kf(e,t){const s=this.descriptor.namespaces[e];if(!s)throw new Error(`namespace ${e} not found in descriptor`);const o=s.basePath,r=s.locales[t].file;return Bf([o,r])}let Ss=class{constructor(e,t,s){a(this,"id");a(this,"lang");a(this,"rootUrl");a(this,"descriptor");a(this,"_defaultNamespace");a(this,"resolver");a(this,"logger");a(this,"descriptorUrl");a(this,"namespaces",[]);a(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||Kf.bind(this),s.kosContext.set(fc,this.resolver),this.logger=s.logger,this._models=new de({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(){this._models.clear(),await Ni(this);for(const e of this.namespaces){const t=this.resolveNamespace(e);await J(t)}}resolveNamespace(e){var s;if((s=this.descriptor.namespaces)==null?void 0:s[e]){const o=Object.keys(this.descriptor.namespaces[e].locales)[0],r=this.descriptor.namespaces[e].locales[o].defaultLocale,n=Ds.factory(`translation-${e}`)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:r,descriptor:this.descriptor.namespaces[e].locales,resolver:this.resolver});return this.addModel(n),this.namespaces.includes(e)||z(()=>{this.namespaces.push(e)}),n}else{this.logger.warn(`namespace ${e} not found in descriptor`);const o=Ds.factory(`translation-${e}`)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(o),o}}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}`)}};yc([ie],Ss.prototype,"_models",2);Ss=yc([O(pt)],Ss);const ge={registration:{[pt]:{class:Ss,singleton:!0}},type:pt,predicate:te(pt),factory:H.Singleton.create(pt)},Gf={set(e,t){const s=k.getContext(ge.type);s&&s.set(e,t)},get(e){const t=k.getContext(ge.type);return t==null?void 0:t.get(e)}},bc={async init(e){const t=ge.factory(e);return await J(t),{translations:t}}},Vf=(e,t)=>{const s=t.type;return e[s]||(e[s]=[]),e[s].push(t),e},vc="kos-ws-event",vr=et(vc);var Hf=Object.defineProperty,Yf=Object.getOwnPropertyDescriptor,wr=(e,t,s,o)=>{for(var r=o>1?void 0:o?Yf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Hf(t,s,r),r};const zf=({headers:e,body:t})=>Object.entries(e).map(([o,r])=>`${o}:${r}`).join("\\n")+"\\n\\n"+t;exports.WsEventModel=class{constructor(t){a(this,"id");a(this,"events");a(this,"_topicMap");this.id=t,this.events=v.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){f.debug("kos event received");const{body:o,headers:r}=t.body,n=r["request-id"]||r["response-id"],i=r["request-id"]||r["response-id"]||r.topic||r.type;if(i){let c=i;if(n)c=`${c}-${s?"send":"receive"}`;else{const d=this._topicMap.get(i)||0;c=`${c}-${d+1}`,this._topicMap.set(i,d+1)}const l={msgId:c,content:o,headers:r,timestamp:Date.now(),raw:zf({headers:r,body:o}),direction:s?"send":"receive",mocked:!!r.mocked};this.events.set(c,l),f.debug(`logged ${this.events.size} events`)}}};wr([R({topic:[Gt.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);wr([R({topic:[Gt.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=wr([O(vr.type)],exports.WsEventModel);const pn=ee(),qf=pn.debug==="true"||pn.debug===!0,Wf="/api/system/canvas",wc=async(e,t)=>{const s=t||Wf,o=`${exports.BASE_URL}${s}`;await exports.kosFetch(o,{method:"POST",headers:{hide:qf?"true":"false"},body:e})},Zf=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:wc},Symbol.toStringTag,{value:"Module"})),Jf=(e,t,s)=>e>>5<<5|t>>5<<2|s>>6;function Qf(e,t,s){if(t==="base64"){const o=s?e.filter((r,n)=>n%4!==3):Array.from(e);return btoa(String.fromCharCode(...o))}else{const o=[];for(let r=0;r<e.length;r+=4)o.push(Jf(e[r],e[r+1],e[r+2]));return String.fromCharCode(...o)}}var Xf=Object.defineProperty,ep=Object.getOwnPropertyDescriptor,Mc=(e,t,s,o)=>{for(var r=o>1?void 0:o?ep(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Xf(t,s,r),r};const _c="canvas-renderer-model";function mn(e){return typeof e.onDone=="function"}let As=class{constructor(e,t,s){a(this,"id");a(this,"router");a(this,"logger");a(this,"_renderer",null);a(this,"isStreaming",!1);a(this,"renderLoopId",null);a(this,"sendIntervalId",null);a(this,"timeoutId",null);a(this,"apiPath");a(this,"endpointName");a(this,"width",50);a(this,"height",30);a(this,"fps",10);a(this,"durationMs",null);a(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()}sendDataFrame(e,t){wc(e,t)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{this.stopStreaming()});return}}handleFrame(e){var s;const t=Qf(e,"base64",!0);this.sendDataFrame(t,this.apiPath),(s=this._onFrame)==null||s.call(this,t)}stopStreaming(){var e,t;this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(t=(e=this._renderer)==null?void 0:e.pause)==null||t.call(e)}isOneShotDone(){var e,t;return mn(this._renderer)&&((t=(e=this._renderer).isOneShot)==null?void 0:t.call(e))===!0&&this._renderer.isOneShotDone}startStreaming(){var e,t,s,o;{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 r=mn(this._renderer);this._renderer.renderFrame(this.width,this.height);const n=(o=(s=this._renderer).readPixels)==null?void 0:o.call(s,this.width,this.height);if(n&&this._onFrame&&this.handleFrame(n),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming()});return}const i=()=>{var c;(c=this._renderer)==null||c.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var l,d;const c=(d=(l=this._renderer)==null?void 0:l.readPixels)==null?void 0:d.call(l,this.width,this.height);c&&this._onFrame&&(this.handleFrame(c),this.checkStreaming())},1e3/this.fps),!r&&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.stopStreaming(),t.send({status:"OK"})}),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/start`,async(e,t)=>{this.startStreaming(),t.send({status:"OK"})})}};Mc([Ae({modelType:Gs.type})],As.prototype,"router",2);As=Mc([O(_c)],As);const Mr=new ae({class:As,type:_c});class tp{constructor(t){a(this,"video");a(this,"canvas");a(this,"ctx");a(this,"lastUpdate",0);a(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 Ec{constructor(){a(this,"canvas");a(this,"ctx");a(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 Ic(e){class t extends e{constructor(){super(...arguments);a(this,"doneCallback",null);a(this,"oneShotDone",!1)}isOneShot(){return!0}onDone(r){this.doneCallback=r}signalDoneIfNeeded(){var r;this.oneShotDone||((r=this.doneCallback)==null||r.call(this),this.oneShotDone=!0)}resetOneShot(){this.doneCallback=null,this.oneShotDone=!1}get isOneShotDone(){return this.oneShotDone}}return t}const sp=Ic(Ec);class op extends sp{constructor(s){super();a(this,"img");a(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,o){!this.loaded||this.isOneShotDone||(this.canvas.width=s,this.canvas.height=o,this.ctx.drawImage(this.img,0,0,s,o),this.signalDoneIfNeeded())}}const rp=Ic(Ec);class yn extends rp{constructor(s=0,o=0,r=0){super();a(this,"color");this.color=`rgb(${s},${o},${r})`}setColor(s,o,r){this.color=`rgb(${s},${o},${r})`,this.resetOneShot()}reset(){this.resetOneShot()}renderFrame(s,o){this.isOneShotDone||(this.canvas.width=s,this.canvas.height=o,this.ctx.fillStyle=this.color,this.ctx.fillRect(0,0,s,o),this.signalDoneIfNeeded())}}const bn=({mode:e,data:t})=>{switch(e){case"color":{const{r:s,g:o,b:r}=t;return t?new yn(s,o,r):new yn(0,0,0)}case"image":return t?new op(t.src):null;case"video":return t?new tp(t.src):null;default:throw new Error(`Unknown mode: ${e}`)}};var np=Object.defineProperty,ip=Object.getOwnPropertyDescriptor,_r=(e,t,s,o)=>{for(var r=o>1?void 0:o?ip(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&np(t,s,r),r};const Tc="canvas-dispatcher-model";function ap(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 Nt=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_content",new Map);a(this,"_patterns",new Map);a(this,"_endpointRenderers");a(this,"router");a(this,"pattern");a(this,"data");this.id=e,this.logger=s.logger,this._endpointRenderers=new de}addNamedEndpoint(e,t){this._endpointRenderers.getModel(e)&&this.logger.warn(`Endpoint "${e}" already exists. Overwriting.`);const s=Mr.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 load(e){var s;const t=e==null?void 0:e.get(We.loader);t&&((s=t.patterns)==null||s.forEach(o=>{if(!o.id||!o.type||!o.data){this.logger.warn(`Invalid pattern data: ${JSON.stringify(o)}`);return}this.addPattern(o.id,o)})),this.router.use("POST","/api/ui/canvas/patterns",async(o,r)=>{var c,l;const n=o.body,i=Array.isArray(n)?n:[n];if(i.some(d=>!d.id||!d.type||!d.data)){(c=r.status)==null||c.call(r,400).send({error:"Invalid pattern data"});return}for(const d of i)this._patterns.has(d.id)&&this.logger.warn(`Pattern "${d.id}" already exists. Overwriting.`),this.addPattern(d.id,d);(l=r.status)==null||l.call(r,200).send({status:"OK"})}),this.router.use("POST","/api/ui/canvas/pattern/:endpoint/:pattern",async(o,r)=>{var u,h,p;const n=o.params.pattern,i=o.params.endpoint,c=this._endpointRenderers.getModel(i);if(!c){(u=r.status)==null||u.call(r,404).send({error:`Endpoint "${i}" not found`});return}if(!this._patterns.has(n)){(h=r.status)==null||h.call(r,404).send({error:`Pattern "${n}" not found`});return}const l=this._patterns.get(n),d=l.type;this.data=l.data,c.renderer=bn({mode:d,data:this.data}),c.startStreaming(),(p=r.status)==null||p.call(r,200).send({status:"OK"})}),this.router.use("POST","/api/ui/canvas/color/:endpoint/:color",async(o,r)=>{var p,w,b;const n=o.params.color,i=ap(n);if(!i){(p=r.status)==null||p.call(r,400).send({error:"Invalid color format"});return}const c=o.params.endpoint,l=this._endpointRenderers.getModel(c);if(!l){(w=r.status)==null||w.call(r,404).send({error:`Endpoint "${c}" not found`});return}const{r:d,b:u,g:h}=i;l.renderer=bn({mode:"color",data:{r:d,g:h,b:u}}),l.startStreaming(),(b=r.status)==null||b.call(r,200).send({status:"OK"})}),this.router.use("POST","/api/ui/canvas/endpoint",async(o,r)=>{var i,c;const n=o.body;if(!n.apiPath||!n.id){(i=r.status)==null||i.call(r,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(n.id,n),(c=r.status)==null||c.call(r,200).send({status:"OK"})})}};_r([ie],Nt.prototype,"_endpointRenderers",2);_r([Ae({modelType:Gs.type})],Nt.prototype,"router",2);Nt=_r([O(Tc)],Nt);const We=new pe({class:Nt,type:Tc}),{URL:Er}=q(),{getOne:$c}=Y.build({basePath:`${Er}/api/device`}),Cs=f.createLogger({name:"device-service",group:"Services"}),Oc=async()=>{Cs.debug("sending GET for device serial number");try{const e=await $c({urlOverride:`${Er}/api/kos/device/serialNumber`});return[void 0,e==null?void 0:e.data.serialNumber]}catch(e){if(e instanceof ce)return Cs.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Dc=async()=>{Cs.debug("sending GET for device details");try{const e=await $c({urlOverride:`${Er}/api/kos/device`});return e?[void 0,e.data]:["unknownError",void 0]}catch(e){if(e instanceof ce)return Cs.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},cp=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:Dc,getSerialNumber:Oc},Symbol.toStringTag,{value:"Module"}));var lp=Object.defineProperty,dp=Object.getOwnPropertyDescriptor,Sc=(e,t,s,o)=>{for(var r=o>1?void 0:o?dp(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&lp(t,s,r),r};const Ac="device-model",up="/kos/criticalData/changed",hp="/kos/criticalData/available";let Rs=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_serialNumber");a(this,"_name");a(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 Dc();if(e){this.logger.error(`Error fetching device serial number: ${e}`);return}if(t){const{name:s,nodeId:o}=t;this.updateModel({name:s,nodeId:o,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[e,t]=await Oc();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()}};Sc([R({topic:[up,hp],websocket:!0})],Rs.prototype,"handleCriticalDataChanged",1);Rs=Sc([O(Ac)],Rs);const Ls=new pe({class:Rs,type:Ac});var gp=Object.defineProperty,fp=Object.getOwnPropertyDescriptor,pp=(e,t,s,o)=>{for(var r=o>1?void 0:o?fp(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&gp(t,s,r),r};const Cc="network-interface-model";let Oo=class{constructor(e,t,s){a(this,"id");a(this,"name");a(this,"type");a(this,"nmdevicestate");a(this,"hwaddress");a(this,"mtu");a(this,"configured");a(this,"wifi");a(this,"ethernet");a(this,"ip4settings");a(this,"category");a(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}`)}};Oo=pp([O(Cc)],Oo);const Ir=new ae({class:Oo,type:Cc}),{URL:mp}=q(),{getAll:yp}=Y.build({basePath:`${mp}/api/kos/network/interfaces`}),vn=f.createLogger({name:"network-interface-service",group:"Services"}),Rc=async()=>{vn.debug("sending GET for copy-logs");try{const e=await yp({});return[void 0,e==null?void 0:e.data]}catch(e){if(e instanceof ce)return vn.error(`Error fetching log file size: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},bp=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:Rc},Symbol.toStringTag,{value:"Module"}));var vp=Object.defineProperty,wp=Object.getOwnPropertyDescriptor,Lc=(e,t,s,o)=>{for(var r=o>1?void 0:o?wp(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&vp(t,s,r),r};const Pc="network-interface-container-model";let Ps=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new de({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 Rc();if(e){this.logger.error(`Error loading network interfaces: ${e}`);return}t&&t.forEach(s=>{const o=Ir.instance(s.name).forceUpdate.options(s).build();this.addModel(o)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};Lc([ie],Ps.prototype,"_models",2);Ps=Lc([O(Pc)],Ps);const Ut=new pe({class:Ps,type:Pc});Ut.addRelatedModel(Ir);const{URL:Mp}=q(),{getAll:_p}=Y.build({basePath:`${Mp}/api/kos/storage/devices`}),wn=f.createLogger({name:"storage-device-service",group:"Services"}),kc=async()=>{wn.debug("sending GET for storage-device");const e=await _p({});return!(e!=null&&e.data)||e.status!==200?(wn.error("Failed to retrieve storage-device data",e),[]):e.data},Ep=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:kc},Symbol.toStringTag,{value:"Module"}));var Ip=Object.defineProperty,Tp=Object.getOwnPropertyDescriptor,$p=(e,t,s,o)=>{for(var r=o>1?void 0:o?Tp(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Ip(t,s,r),r};const xc="storage-device-model";let Do=class{constructor(e,t,s){a(this,"id");a(this,"mountDir");a(this,"removed");a(this,"vendor");a(this,"runTimeMs");a(this,"model");a(this,"nodeId");a(this,"local");a(this,"label");a(this,"syspath");a(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}`)}};Do=$p([Us(),O(xc)],Do);const ks=new ae({class:Do,type:xc});var Op=Object.defineProperty,Dp=Object.getOwnPropertyDescriptor,Tr=(e,t,s,o)=>{for(var r=o>1?void 0:o?Dp(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Op(t,s,r),r};const Fc="storage-device-container-model",Sp="/kos/storage";let jt=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new de({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(o=>o.id===s.id)).forEach(s=>{this.removeModel(s.id)}),e.forEach(s=>{const o=this.getModel(s.id);if(o){const r={...s,kosParentId:this.id};o.updateModel(r)}else{const r={...s,kosParentId:this.id},n=ks.instance(s.id).options(r).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await kc()).forEach(t=>{const s={...t,kosParentId:this.id},o=ks.instance(t.id).options(s).build();this.addModel(o)})}};Tr([ie],jt.prototype,"_models",2);Tr([R({topic:Sp,websocket:!0})],jt.prototype,"handleStorageAvailability",1);jt=Tr([O(Fc)],jt);const Ze=new pe({class:jt,type:Fc});Ze.addRelatedModel(ks);const{URL:$r}=q(),{getAll:Ap,postModel:Cp}=Y.build({basePath:`${$r}/api/kos/update/available`}),Mn=f.createLogger({name:"usb-update-service",group:"Services"}),Nc=async()=>{Mn.debug("sending GET for usb-update");const e=await Ap({urlOverride:`${$r}/api/kos/update/available`});return!(e!=null&&e.data)||(e==null?void 0:e.status)!==200?(Mn.error("Failed to retrieve usb-update data",e),[]):e.data},Uc=async(e,t,s)=>{const o=await Cp({model:{manifestId:e,deviceId:t},tracker:s,urlOverride:`${$r}/api/kos/update/install`});if(!(o!=null&&o.data))throw new Error("No response from server");return o.data},Rp=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:Nc,installUpdate:Uc},Symbol.toStringTag,{value:"Module"}));var Lp=Object.defineProperty,Pp=Object.getOwnPropertyDescriptor,jc=(e,t,s,o)=>{for(var r=o>1?void 0:o?Pp(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Lp(t,s,r),r};const Bc="usb-update-model";let xs=class{constructor(e,t,s){a(this,"id");a(this,"active");a(this,"blocked");a(this,"createTime");a(this,"deviceId");a(this,"manifestId");a(this,"notes");a(this,"futureHandler");a(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 cr(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}`),Uc(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}`)}};jc([Cr()],xs.prototype,"install",1);xs=jc([O(Bc)],xs);const Or=new ae({class:xs,type:Bc});var kp=Object.defineProperty,xp=Object.getOwnPropertyDescriptor,qs=(e,t,s,o)=>{for(var r=o>1?void 0:o?xp(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&kp(t,s,r),r};const Kc="usb-update-container-model";let Je=class{constructor(e,t,s){a(this,"id");a(this,"disposer");a(this,"storageService");a(this,"_activeUpdate");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new de({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 Nc();z(()=>{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 o=`${s.deviceId}-${s.manifestId}`,r=Or.instance(o).forceUpdate.options({...s,createTime:new Date(s.createTime)}).build();this.addModel(r)}),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}`)}};qs([Ae({modelType:Ze.type})],Je.prototype,"storageService",2);qs([ie],Je.prototype,"_models",2);qs([li({dependencies:e=>[e.isUsbInserted]})],Je.prototype,"usbInsertedEffect",1);Je=qs([O(Kc)],Je);const Bt=new pe({class:Je,type:Kc});Bt.addRelatedModel(Or);const Fp=()=>({...{[st.type]:{class:Ia},[be.type]:{class:Aa,singleton:!0},...V.registration,...Re.registration,...ze.registration,...Ds.registration,...ge.registration,[vr.type]:{class:exports.WsEventModel,singleton:!0},...Ft.registration,...yr.registration,...vs.registration}}),Dr=Fp(),Np={models:Dr,preloadModels:[]},Up=!0,Gc=e=>()=>{const t=Dr;return Ki(So)(xt).model(ze).model(Ze).model(Bt).model(Ls).model(Is).model(At).model(Ts).model(fr).model(Ut).model(We).model(Mr).model(Gs,Up).model(qt),Object.keys(t).forEach(s=>{const o=t[s];Bi(So)(s,o)}),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e)}},ne={};ne.core={models:Gc(ne)};ne.preload=$.model.preloadModel(ne);ne.model=$.model.register(ne);ne.companion=$.companion.register(ne);ne.legacy=$.model.registerLegacyModel(ne);const So=ne;class jp{registerTroubleRankMapper(t){return C.propertyMapper.registerPropertyMapper(re.TroubleRank,t),this}registerTroubleRoleMapper(t){return C.propertyMapper.registerPropertyMapper(re.TroubleRole,t),this}registerTroubleColorMapper(t){return C.propertyMapper.registerPropertyMapper(re.TroubleColor,t),this}registerModelLoader(t,s){C.loader.registerLoader(t,s)}registerCanvasPatternLoader(t){C.loader.registerLoader(We.loader,t)}}const Bp=async(e,t)=>{const s=fr.instance(e).options({}).build(),o=t?`${t}-`:"";return await J(s),{getState:r=>s.data[`${o}${r}`],updateState:async(r,n)=>{await s.updateState(`${o}${r}`,n)},clean:async()=>{for(const r of s.data.keys)await s.updateState(`${o}${r}`,void 0)},unsubscribe:()=>{Oe(s)}}},Vc="kos:service:region",Hc="regionId",Kp=`${Vc}-${Hc}`,Yc=async e=>{const t=Re.factory(Kp)({path:Vc,attribute:Hc});await J(t),t.updateProperty(e)},Sr="/kos-timer-event",Ar="defaultTimerEnd",mt=f.createLogger({name:"timer-manager"}),Gp=e=>e.updateProperty!==void 0;class zc{constructor(t,s,o){a(this,"name");a(this,"timeout");a(this,"timer");a(this,"state","inactive");a(this,"decrementValue",1);a(this,"remainingTime");a(this,"timeoutActions",new Map);this.name=t;const r=typeof s=="number"?s:s.value||60;this.timeout=r,this.state="inactive",this.remainingTime=r,Gp(s)&&F(()=>{f.info(`Updating config value timer ${t} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:Ar}),o&&o.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){mt.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&&(mt.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 o=t.name,r=this.timeoutActions.get(s).find(n=>n.name===o);r?r.action=t.action:this.timeoutActions.get(s).push(t)}removeTimeoutAction(t){for(const[s,o]of this.timeoutActions.entries()){const r=o.filter(n=>n.name!==t);r.length===0?this.timeoutActions.delete(s):this.timeoutActions.set(s,r)}}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 o;mt.debug(`Executing timer action ${s.name} at ${t}`),(o=s.action)==null||o.call(s,s.name,t),this.notifyTimeoutAction(s),s.singleUse&&(mt.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))})}notifyTimeoutAction(t){N(Sr,{name:this.name,action:t.name,remainingTime:this.remainingTime})}}const yt=new Map,Ne=(e,t)=>{const s=yt.get(e);if(!s){mt.error(`Timer ${e} not found`);return}t(s)},qc={createRelativeTimer(e,t,s){const o=new Date,r=Math.round((t.getTime()-o.getTime())/1e3);return this.createTimer(e,r,s)},createTimer(e,t=60,s){if(yt.has(e))return yt.get(e);const o=new zc(e,t,s);return yt.set(e,o),o},getTimer(e){return yt.get(e)},clearTimer(e){Ne(e,t=>t.pause())},restartTimer(e){Ne(e,t=>t.restart())},resetTimer(e){Ne(e,t=>t.reset())},addTimeoutAction(e,t){Ne(e,s=>s.addTimeoutAction(t))},removeTimeoutAction(e,t){Ne(e,s=>s.removeTimeoutAction(t))},startTimer(e){Ne(e,t=>t.start())}},Wc="kos:service:region:settings",Zc="timeZone",Vp=`${Wc}-${Zc}`,Ao=async e=>{const t=Re.factory(Vp)({path:Wc,attribute:Zc});await J(t),t.updateProperty(e)},Hp=e=>!e||!e.data;function Cr(e={}){const{alias:t,namespace:s}=e;return(o,r,n)=>{o[wt]=o[wt]||{};const i=n.value,c=async function(...l){const d=Xe();f.debug(`Calling future service ${r} with tracker ${d}`);const u=De.initiateFuture({tracker:d,id:tr});s&&(u.namespace=s),f.debug(`waiting for future ${u.id} to be ready`),await J(u),f.debug(`future ${u.id} is ready`),z(()=>{f.debug(`Adding future ${u.id} to futureHandler`),this.futureHandler.addFuture(u,t)});try{const h=await i.apply(this,[...l,d]);f.debug(`received future response for ${d}`,h);const p=Hp(h)?h:h==null?void 0:h.data;return p?(p.progress=1,f.debug("mapping future response to future model"),u.endState?f.debug(`future ${u.id} has already completed. Not updating the model`):dr(p,u)):this.futureHandler.removeFuture(t),p}catch(h){throw f.error(h),h}};o[wt][r]={handler:c}}}const Yp=({path:e})=>(t,s)=>{t[P]=t[P]||{},t[P][s]={modelType:Ft.type,id:`${Ft.type}-${e}`,options:{path:e},lifecycle:x.INIT}};function zp(e){const{path:t,attribute:s}=e;return(o,r)=>{o[P]=o[P]||{},o[P][r]={modelType:yr.type,id:`${t}-${s}`,options:{path:t,attribute:s},lifecycle:x.INIT}}}const Be=f.createLogger({name:"services",group:"Services"}),qp=async(e,t)=>Jc(e,t,`${exports.BASE_URL}/api/server/login`),Jc=async(e,t,s=`${exports.BASE_URL}/api/login`)=>{const o=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:e,password:t})});if(!o.ok){const n=await o.json();throw Error(`${n==null?void 0:n.error}`)}return await o.json()},Wp=async e=>Qc(e,`${exports.BASE_URL}/api/server/startPasswordReset`,""),Qc=async(e,t=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const o=await exports.kosFetch(`${t}?email=${e}`,{method:"POST",destinationAddress:s});if(!o.ok)throw Error(`There was a problem reseting config; returned status ${o.status}`);return await o.json()},Zp=async(e,t)=>Xc(e,t,`${exports.BASE_URL}/api/server/resetPassword`),Xc=async(e,t,s=`${exports.BASE_URL}/api/resetPassword`)=>{Be.debug(`resetting password with token ${e} and password ${t.replace(/./g,"*")}`);const o=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t})});if(Be.debug(`password reset returned status ${o.status}`),!o.ok){Be.error(`password reset failed with message ${o.statusText}`);const n=await o.json();throw Error(`${n==null?void 0:n.error}:There was a problem resetting the password.`)}return await o.json()},Jp=async(e,t,s)=>el(e,t,s,`${exports.BASE_URL}/api/server/acceptInvite`),el=async(e,t,s,o=`${exports.BASE_URL}/api/server/acceptInvite`)=>{Be.debug(`accepting invite with token ${e} and password ${t.replace(/./g,"*")}`);const r=await exports.kosFetch(`${o}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t,name:s})});if(Be.debug(`invitation accept returned status ${r.status}`),!r.ok){Be.error(`invite failed with message ${r.statusText}`);const i=await r.json();throw Error(`${i==null?void 0:i.error}:There was a problem accepting the invite.`)}return await r.json()},Qp=Ie.keyframes`
|
|
77
|
+
["${t}"]`;if(o?(w=this.fosSocket)==null?void 0:w.connectionEstablished:(b=this.socket)==null?void 0:b.connectionEstablished){const I=o?this.fosSocket:this.socket;(_=I==null?void 0:I.socket)==null||_.send(u)}else{Ee.debug("no connection adding to offline messages");const I=o?this.fosSocket:this.socket;I==null||I.addOfflineMessage(u)}}subscribeTopic({topic:t,callback:s,fos:o,bridge:r,destinationAddress:n}){const{unsubscribe:i,count:c}=U(t,s);return Ee.debug(`Topic ${t} currently has ${c} subscribers`),this._sendSubscriptionMessage(t,"subscribe",o,r,n),()=>{const{count:l}=i();Ee.debug(`Topic ${t} currently has ${l} subscribers`),l===0&&this._sendSubscriptionMessage(t,"unsubscribe",o,r,n)}}async whenReady(){const t=this;return this.webSocketSupported?(await v.when(()=>{var s,o;return!!((s=t.socket)!=null&&s.connectionEstablished)&&(!t.useFosTransport||!!((o=t.fosSocket)!=null&&o.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 o=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:t,token:s,fos:o})}return this._instance}}a(Vt,"_instance");class wu{constructor(t,s,o,r,n){a(this,"disposers",[]);a(this,"activatableDisposers",[]);this.model=t,this.modelData=s,this.modelId=o,this.offlineQueue=r,this.log=n}registerAll(t){var r;const s=((r=this.modelData)==null?void 0:r[G])||{},o=Object.keys(s);this.log.debug(`Found ${o.length} subscriptions in ${this.modelId} (lifecycle: ${t??"any"})`),o.forEach(n=>{const i=s[n],c=i.lifecycle;if(t&&t!==c)return;const l=this.resolvePropKey(n);this.log.debug(`Resolved topic: ${n} → ${l}`);const d=this.createHandler(l,i);this.subscribe(i,l,d,c===x.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 of t)try{s()}catch(o){this.log.error("Error during subscription disposal",o)}this.disposers=[],this.activatableDisposers=[]}subscribe(t,s,o,r){const n=t.destinationAddress?this.resolvePropKey(t.destinationAddress):null;if(t.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=Vt.getInstance().subscribeTopic({topic:s,callback:o,fos:t.fos,bridge:t.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=U(s,o);r?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(t,s){return async o=>{var r;try{const n=(r=o==null?void 0:o.headers)==null?void 0:r["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),c=i?n===i:!0;if(this.model.isReady()){const l=vo(o,s.skipParse),d=s.transform(l);if(c&&s.condition(d,this.modelData,o))return s.handler.call(this.modelData,d,o,this.modelData)}else{this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${t}`);const l=()=>{const d=vo(o,s.skipParse),u=s.transform(d);if(c&&s.condition(u,this.modelData,o))return s.handler.call(this.modelData,u,o,this.modelData)};this.offlineQueue.enqueue(l)}}catch(n){this.log.error(`Error handling subscription for ${t}`,n)}}}resolvePropKey(t){const s=/.*({PROP_(.+)})/;let o=t.includes("{MODEL_ID}")?t.replace("{MODEL_ID}",this.modelId):t;const r=o.match(s);return r&&r[2]in this.modelData&&(o=o.replace(r[1],this.modelData[r[2]])),o}}function nt(e,t){const s=`[Model:${t}]`;return{debug:(...o)=>e.debug(s,...o),info:(...o)=>e.info(s,...o),warn:(...o)=>e.warn(s,...o),error:(...o)=>e.error(s,...o)}}function Mu(e){return!!(e!=null&&e[$e])&&Object.keys(e[$e]).length>0}function _u(e){return!!(e!=null&&e[G])&&Object.keys(e[G]).length>0}class Eu{static createAll(t){const{modelId:s,modelTypeName:o,modelData:r}=t,n=iu.create({modelId:s,modelTypeName:o}),i=new nu(t,nt(n,"fsm")),c=new au(nt(n,"offline-queue")),l=new Jd(t),d=new Zd(t),u={fsm:i,offlineQueue:c,companionManager:l,childResolver:d};if(Mu(r)&&(u.effectManager=new Qd(o,s,r,nt(n,"effect"))),_u(r)){const h=nt(n,"subscription");u.subscriptionManager=new wu(t,r,s,c,h),u.onlineLifecycleManager=new cu(t,nt(n,"online"))}return u}}const S=T.getLogger("kos-model"),Iu="kos.extension.model.loader";class xi{constructor({modelTypeName:t,id:s,modelData:o}){a(this,"_id");a(this,"_status");a(this,"_activeStatus");a(this,"_onlineStatus");a(this,"modelData");a(this,"modelTypeName");a(this,"initialized");a(this,"loaded");a(this,"offlineQueue");a(this,"subscriptionManager");a(this,"effectManager");a(this,"onlineLifecycleManager");a(this,"companionManager");a(this,"childResolver");a(this,"fsm");this._id=typeof s<"u"?`${s}`:t,this.modelTypeName=t,this.initialized=!1,this.loaded=!1,this.modelData=o,this._status=y.CREATED,this._activeStatus=y.INACTIVE,this._onlineStatus=y.OFFLINE;const r=Eu.createAll(this);this.fsm=r.fsm,this.offlineQueue=r.offlineQueue,this.companionManager=r.companionManager,this.childResolver=r.childResolver,r.effectManager&&(this.effectManager=r.effectManager),r.subscriptionManager&&(this.subscriptionManager=r.subscriptionManager),r.onlineLifecycleManager&&(this.onlineLifecycleManager=r.onlineLifecycleManager),v.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),qd(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===y.ACTIVE}isOnline(){return this._onlineStatus===y.ONLINE}isReady(){return this._status===y.READY}async deactivate(){var t,s,o;S.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const r=k.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.deactivate)==null?void 0:s.call(t,r)),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(o=this.subscriptionManager)==null||o.deactivate()}catch(r){throw S.debug(`Model ${this.modelId} failed to deactivated`),r}}async activate(){var t,s,o;S.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await ct(this,x.ACTIVATE);try{const r=k.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.activate)==null?void 0:s.call(t,r)),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(x.ACTIVATE),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(r){throw S.debug(`Model ${this.modelId} failed to activate`),r}}async whenInitialized(){await zr([{condition:()=>this.status===y.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{S.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await zr([{condition:()=>this.status===y.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===y.READY,onMatch:()=>{S.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var t,s,o;if(this.fsm.current===y.READY){S.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{S.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await ct(this,x.READY),await Mi(this,qo.READY,x.READY);const r=k.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.ready)==null?void 0:s.call(t,r)),this.offlineQueue.flush(),(o=this.subscriptionManager)==null||o.registerAll(x.READY),S.debug(`Model ${this.modelId} is ready`);const n={modelId:this.modelId,modelType:this.modelTypeName};F(ci(this.modelTypeName,this.modelId),n),F(li(this.modelTypeName),n)}catch(r){throw S.error(r),Error(r)}}async load(){var o,r,n,i;const{modelTypeName:t,modelId:s}=this;if(this.fsm.current===y.LOADED||this.fsm.current===y.LOADING){S.debug(`Model ${t} with id ${s} already loaded or loading`);return}S.debug(`Loading model ${t} with id ${s}`),await ct(this,x.LOAD);try{const c=k.getContext(s),l=`${Iu}.${t}`,d=await A.loader.executeLoader(l,{});d&&(S.info(`Setting loaded context for ${s}, type: ${t}`),c==null||c.set(l,d)),await((r=(o=this.modelData)==null?void 0:o.load)==null?void 0:r.call(o,c)),this.loaded=!0,S.debug(`Model ${t} with id ${s} successfully loaded`),(n=this.subscriptionManager)==null||n.registerAll(x.LOAD),(i=this.effectManager)==null||i.setup()}catch(c){throw S.error(`Model ${s} failed to load`,c),c}}async unload(){var t,s,o,r,n;S.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const i=this.getChildren().map(l=>{var d;return(d=l.unload)==null?void 0:d.call(l)}).filter(l=>!!l);await Promise.allSettled(i);const c=k.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.unload)==null?void 0:s.call(t,c)),this.loaded=!1,(o=this.onlineLifecycleManager)==null||o.dispose(),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(r=this.effectManager)==null||r.disposeAll(),(n=this.subscriptionManager)==null||n.disposeAll()}catch(i){throw S.debug(`Model ${this.modelId} failed to unload`),i}}async init(){var r,n,i;const{modelId:t,modelTypeName:s}=this,o=k.getContext(t);S.debug(`Initializing model ${s} with id ${t}`),await ct(this,x.INIT);try{await((n=(r=this.modelData)==null?void 0:r.init)==null?void 0:n.call(r,o)),this.initialized=!0,S.debug(`Model ${s} with id ${t} initialized`),(i=this.onlineLifecycleManager)==null||i.register(),this.registerSubscribers(x.INIT)}catch(c){throw S.error(`Model ${t} failed to initialize`,c),c}}async registerSubscribers(t){var s;S.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(t)}async online(){var s,o;S.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const t=k.getContext(this.modelId);await((o=(s=this.modelData)==null?void 0:s.online)==null?void 0:o.call(s,t))}async offline(){var s,o,r;S.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const t=k.getContext(this.modelId);await((r=(o=this.modelData)==null?void 0:o.offline)==null?void 0:r.call(o,t))}accept(t){t.visit(this)}getChildren(){return this.childResolver.resolve()}addCompanionModel(t){this.companionManager.add(t)}clearCompanionModels(){this.companionManager.clear()}}const Fi=e=>typeof e=="function",Jr=f.createLogger({name:"kos-model-instantiator"});class Tu{constructor(t,s){this.registry=t,this.cache=s}createModelInstance(t,s,o={}){const r=this.registry.models[t];if(!r)throw new Error(`No model registered for type ${t}`);const n=r.singleton?t:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){Jr.debug(`Creating model instance: ${t} [${n}]`);const c=r.create?r.create({modelTypeId:t,id:n,options:o}):new r.class(n,o),l=new xi({modelTypeName:t,id:n,modelData:c});this.cache.addModel(l),this._createCompanionModels(l,o)}const i=this.cache.getModelById(n);if(!i)throw Jr.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 o=t.modelTypeName,r=((n=this.registry.companionModels)==null?void 0:n[o])||[];for(const{type:i}of r){const c=Fi(i)?i(t.modelData,s):i;if(!c)continue;const l=`${c}-${t.modelId}`,d=this.createModelInstance(c,l,{data:s,companionParent:t.modelData,kosParentId:t.modelId});d!=null&&d.model&&t.addCompanionModel(d.model)}}}let $u=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 o,r;(o=this.registry).companionModels??(o.companionModels={}),(r=this.registry.companionModels)[t]??(r[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 o;const s=(o=this.getModelTypeRegistry(t))==null?void 0:o.builder;if(!s)throw new Error(`No builder found for model type ${t}`);return s}getModelFactory(t){return et(t)}};const Ni=10,Qr=f.createLogger({name:"kos-model-manager"});class Ui{constructor(){a(this,"cache");a(this,"instantiator");a(this,"dependencies");a(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Sd,globalThis.kos.modelManager=this,globalThis.kos.resolveKosModel=t=>{const s=this.getModelById(t);if(s)return s.modelData||{}},globalThis.kos.kosModelJson=t=>{var o,r;const s=this.getModelById(t);if(s)return((r=(o=s.modelData).toJSON)==null?void 0:r.call(o))||{}},globalThis.kos.kosModelDebug=t=>{var o;const s=this.getModelById(t);if(s)return((o=s.modelData)==null?void 0:o.debugState)||{}},globalThis.kos.kmd=globalThis.kos.kosModelDebug,globalThis.kos.kmj=globalThis.kos.kosModelJson}static create(t,s){const o=this.getInstance(s);return o._registry=new $u(t),o.cache=new Cd(t.preloadModels),o.instantiator=new Tu(t,o.cache),o}static getInstance(t){var s,o;return(!((s=globalThis.kos)!=null&&s.modelManager)||t)&&(Qr.debug("Creating new instance of KosModelManager"),new this),(o=globalThis.kos)==null?void 0:o.modelManager}get registry(){return this._registry.registry}get preloadedModels(){return this.cache.preload(t=>(Qr.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(o=>o.modelTypeName===t).filter(o=>s?s(o.modelData):!0).map(o=>o.modelData)}getModelSubscriptions(t){return this._registry.getModelSubscriptions(t)}getDataModelBuilder(t){return this._registry.getDataModelBuilder(t)}getModelFactory(t){return et(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(D.RESET,y.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),ei.addToDeletionQueue(t.id,setTimeout(()=>this.destroyModel(s),Ni)))}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,o={}){return this.instantiator.createModelInstance(t,s,o)}registerCompanionModel(t,s){this._registry.registerCompanionModel(t,s)}registerModel(t){this._registry.registerModel(t)}}const Ou=async({context:e,extension:t})=>{const s=await A.loader.executeLoader(t,{});return e==null||e.set(t,s),s},Du=async({extension:e,contextData:t,data:s})=>await A.dataMapper.executeMapper(e,s,t),Su=async({extension:e,contextData:t,data:s})=>await A.propertyMapper.executeMapper(e,s,t),Cu=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:Du,executeLoaderExtension:Ou,executePropertyMapperExtension:Su},Symbol.toStringTag,{value:"Module"})),Au="Extensions";class Ru{constructor(){a(this,"extensions");this.extensions={}}register(t,s,o){this.extensions[t]={},this.extensions[t][s]={component:o}}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}}var cs=(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))(cs||{}),Ue=(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))(Ue||{});const Lu=e=>{const t=m.createMachine("offline",{online:m.state(m.transition("go_offline","offline",m.action(()=>{e.offline(),v.runInAction(()=>{e.isOnline=!1})}))),offline:m.state(m.transition("go_online","online",m.action(()=>{e.online(),v.runInAction(()=>{e.isOnline=!0})})))}),s=m.interpret(t,n=>T.debug(n.machine.current)),o=m.createMachine({creating:m.state(m.transition("create","created")),created:m.state(m.immediate("initializing")),initializing:m.invoke(()=>e.init(),m.transition("done","initialized")),initialized:m.state(m.immediate("loading")),loading:m.invoke(()=>e.load(),m.transition("done","loaded")),loaded:m.state(m.immediate("readying"),m.transition("unload","unloading")),readying:m.invoke(()=>e.ready(),m.transition("done","ready",m.action(()=>{v.runInAction(()=>{e.status="ready"})}))),reloading:m.invoke(()=>e.reload(),m.transition("done","loading")),ready:m.state(m.transition("reload","reloading"),m.transition("unload","unloaded",m.action(e.unload.bind(e))),m.transition("go_online","ready",m.action(()=>{s.send("go_online")})),m.transition("go_offline","ready",m.action(()=>{s.send("go_offline")}))),unloaded:m.state()});return{service:m.interpret(o,n=>T.debug(n.machine.current)),online:s}},J=async e=>{if(e.id){const t=E.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},Oe=async e=>{await E.getInstance().whenReady(),await E.getInstance().modelManager.initiateDestroyModel(e)},Pu=async e=>{if(await E.getInstance().whenReady(),!e.id)throw new Error("Model ID is required");const t=E.getInstance().modelManager.getModelById(e.id);t&&await t.fsm.transitionTo(D.UNLOAD,y.UNLOADED)},ji=async e=>{await E.getInstance().whenReady(),await E.getInstance().modelManager.reloadModel(e),f.debug(`reload model initiated for model ${e.id}, model ready: ${fs(e)} - ${Date.now()} `),await J(e),f.debug(`reload model complete for model ${e.id}, model ready: ${fs(e)} - ${Date.now()} `)},ku=async e=>{if(await E.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=E.getInstance().modelManager.getModelById(e);return t==null?void 0:t.modelTypeName},Bi=async e=>{if(await E.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=E.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},Ae=e=>{if(!e)throw new Error("Model ID is required");const t=E.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},Ki=(e,t)=>{if(!e)throw new Error("Model type is required");return E.getInstance().modelManager.getModelsByType(e).filter(r=>Object.keys(t).every(n=>r[n]===t[n]))},xu=(e,t)=>Ki(e,t)[0],Fu=(e,t)=>{if(!e.id)throw new Error("Model ID is required");const s=E.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error("Model not found");const o=s.companionModels.get(t);return o==null?void 0:o.modelData},Nu=e=>{if(!e.id)throw new Error("Model ID is required");const t=E.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return Array.from(t.companionModels.all()).map(o=>o.modelData)},Uu=e=>{if(!e)throw new Error("Model ID is required");const t=E.getInstance().modelManager.getModelById(e);if(!t)throw new Error("Model not found");return t.companionModels.data},Mo=(e,t)=>{const s=E.getInstance().modelManager.getModelById(e);if(!s){f.info(`Model not found for id ${e}`);return}return Array.from(s.companionModels.all()).find(r=>t(r.modelData))},te=e=>t=>Object.getPrototypeOf(t).modelTypeId===e,fs=e=>{const t=E.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return t.isReady()},ju=f.createLogger({name:"kos-model-factory"}),$t={byModelType:e=>E.getInstance().modelManager.getModelFactory(e),getModelInstance:(e,t,s)=>{const o=$t.byModelType(t);if(!o)throw ju.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 o.build(e,s)}},H={Factory:{create:e=>t=>(s,o)=>(o&&k.setParentContext(t,o),$t.getModelInstance(t,e,s))},Singleton:{create:e=>(t,s)=>(s&&k.setParentContext(e,s),$t.getModelInstance(e,e,t))},Model:{instance:e=>t=>$t.getModelInstance(t,e)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const Xr=window.KosRegistry.coreModels,no=window.KosRegistry.preloadModels,io=window.KosRegistry.companionModels,Jt=window.KosRegistry.models,$={model:{registerLegacyModel:e=>(t,s)=>(Xr.set(t,s),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}),preloadModel:e=>t=>(no.includes(t)||no.push(t),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}),register:e=>(t,s)=>{const o=ao(t)?t.registration():t;return Jt.set(o.type,o),ao(t)&&t.relatedModels.forEach(r=>Jt.set(r.type,r.registration())),E.getInstance().isReady&&(E.getInstance().modelManager.registry.models[o.type]||(console.info(`Model with type ${o.type} doesn't exist. Adding new registration`),E.getInstance().modelManager.registry.models[o.type]=o.registration[o.type],ao(t)&&t.relatedModels.forEach(r=>E.getInstance().modelManager.registry.models[r.type]=r.registration().registration))),s&&$.model.preloadModel(e)(o.type),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}},get:e=>Jt.get(e),getAll:()=>Array.from(Jt.entries()),getPreloadModels:()=>no,getLegacyModels:()=>Array.from(Xr.entries()).reduce((e,[t,s])=>(e[t]=s,e),{})},companion:{register:e=>(t,s)=>{const o=io.get(t)||[];return o.push(s),io.set(t,o),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}},getAll:()=>Array.from(io.entries())}},Gi=$.model.registerLegacyModel,Vi=$.model.register,Bu=$.companion.register,Ku=$.model.preloadModel,Hi=e=>typeof e.updateModel=="function",ao=e=>e.registration!==void 0&&typeof e.registration=="function";class Yi{constructor(t){a(this,"singleton");a(this,"type");a(this,"loader");a(this,"class");a(this,"guard");a(this,"factory");a(this,"relatedModels",[]);this.singleton=t.singleton,this.guard=te(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(){$.model.register({})(this.registration()),this.registerRelatedModels()}}class ae extends Yi{constructor(t){super({...t,singleton:!1,factory:H.Factory.create(t.type)})}instance(t){const s=this.factory(t);return{get:()=>{const o=Ae(t);if(!o)throw new Error("Model not found with id "+t);if(this.guard(o))return o;throw new Error("Model is not of type "+this.type)},forceUpdate:{options:o=>({build:()=>{const r=s(o);if(this.guard(r)){if(Hi(r))r.updateModel(o);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return r}else throw new Error("Model is not of type "+this.type)}})},options:o=>({build:()=>{const r=s(o);if(this.guard(r))return r;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 pe extends Yi{constructor(t){super({...t,singleton:!0,factory:H.Singleton.create(t.type)})}instance(){const t=this.factory;return{get:()=>{const o=Ae(this.type);if(!o)throw new Error("Model not found with id "+this.type);if(this.guard(o))return o;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)},forceUpdate:{options:o=>({build:()=>{const r=t(o);if(this.guard(r)){if(Hi(r))r.updateModel(o);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return r}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)}})},options:o=>({build:()=>{const r=t(o);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const j=f.createLogger({name:"kos-core"}),Gu=()=>{const e=ee(),t=e==null?void 0:e.alias,s=process.env.KOS_CONNECTION_ALIAS;return t||s||void 0},Vu=()=>{const e=window.location.protocol,t=ee(),s=t==null?void 0:t.host;let o;try{o=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return o||(e==="https:"?"wss://":"ws://")},Hu=()=>{const e=window.location.hostname,t=process.env.KOS_HOST,s=ee(),o=s==null?void 0:s.host;let r;try{r=new URL(o).hostname}catch{}return r??t??e},Yu=()=>{const e=window.location.port,t=process.env.KOS_PORT,s=ee(),o=s==null?void 0:s.host;let r;try{r=new URL(o).port}catch{}return r??t??e},zu=(e,t)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{t?f.error(`Model ${t.modelId} - ${t.modelTypeName} preloading - timed out after ${e}ms`):f.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)}}},en=e=>typeof e.reload=="function",qu=e=>typeof e.unload=="function";var zi=(e=>(e.LOGGED_IN="logged_in",e.LOGGED_OUT="logged_out",e))(zi||{});class E{constructor(t){a(this,"fsmService");a(this,"status");a(this,"initialized");a(this,"loaded");a(this,"_transport");a(this,"modelManager");a(this,"authState");a(this,"isOnline");a(this,"_reloading");a(this,"_unloading");a(this,"connectionAlias");this.initialized=!1,this.connectionAlias=t,this.loaded=!1,this.isOnline=!1,this.status=cs.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,v.makeAutoObservable(this),U("token",c=>{c&&(this.transport.token=c.body)}),U(Tt.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(Ue.GO_ONLINE)}),U(Tt.DISCONNECTED,async()=>{this.fsmService.service.send(Ue.GO_OFFLINE)}),U("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),U("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),U(Tt.RELOAD,()=>{this.fsmService.service.send(Ue.RELOAD)}),U("/studio/project/reload",()=>{this.fsmService.service.send(Ue.RELOAD)});const s=Vt.getInstance(),o=Hu(),r=Yu(),n=Vu();s.host=o,s.port=Number.parseInt(r),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=Gu()??t;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=Lu(this),this.fsmService.service.send(Ue.CREATE)}get onlineStatus(){return this.isOnline&&!this._reloading&&!this._unloading}get reloading(){return this._reloading}get unloading(){return this._unloading}async reload(){var r,n,i,c;const t=Date.now();if(this._reloading){j.info("reload already in progress");return}this._reloading=!0,j.warn("reloading KOS Core"),j.warn("reloading preloaded models");const s=this.modelManager;for(const l of s.preloadedModels)en(l.modelData)&&(j.info(`reloading model ${l.modelId}`),(r=l.unload)==null||r.call(l),await l.modelData.reload(),(n=l.registerSubscribers)==null||n.call(l),j.info(`reloading model ${l.modelId} complete`));for(const l of s.models)!s.preloadedModels.includes(l)&&en(l.modelData)&&((i=l.unload)==null||i.call(l),await l.modelData.reload(),(c=l.registerSubscribers)==null||c.call(l));const o=Date.now()-t;setTimeout(()=>{v.runInAction(()=>{j.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-o)}async online(){j.debug("KOS Core going online"),await this._transport.whenReady(),j.debug("KOS Transport Ready. Calling online() for models"),F("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){j.debug("KOS Core going offline"),F("/kosCore/offline","/kosCore/offline")}async unload(){var r;j.debug("Unloading KOS Core");const t=Date.now();this._unloading=!0,j.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)qu(n.modelData)&&((r=n.unload)==null||r.call(n));const o=Date.now()-t;setTimeout(()=>{v.runInAction(()=>{this._unloading=!1})},1e3-o)}async whenReady(){await v.when(()=>this.status===cs.READY)}async ready(){j.debug("Readying KOS Core"),await this._transport.whenReady();const t=this.modelManager.preloadedModels.map(r=>({modelId:r.modelId,model:r,promise:r.whenReady()})),o=(await Promise.allSettled(t.map(r=>{const{promise:n,cancel:i}=zu(5e3,r.model);Promise.race([r.promise.then(()=>{i()}),n])}))).filter(r=>r.status==="rejected");if(o.length)throw j.error(`There were ${o.length} failed models on model preloading`),Error(`There were ${o.length} failed models on model preloading`);j.debug("leaving kos-core ready() ")}get isReady(){return this.status===cs.READY}set transport(t){this._transport=t}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){j.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,j.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){j.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,j.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(t,s,o){var i,c,l;const r=this.getInstance({reset:s,connectionAlias:o});(i=t.extensions)!=null&&i.dataMapper&&Object.keys(t.extensions.dataMapper).forEach(d=>{var h,p;const u=(p=(h=t.extensions)==null?void 0:h.dataMapper)==null?void 0:p[d];u&&(Array.isArray(u)?u.forEach(w=>{A.dataMapper.registerDataMapper(d,w)}):A.dataMapper.registerDataMapper(d,u))}),(c=t.extensions)!=null&&c.propertyMapper&&Object.keys(t.extensions.propertyMapper).forEach(d=>{var h,p;const u=(p=(h=t.extensions)==null?void 0:h.propertyMapper)==null?void 0:p[d];u&&A.propertyMapper.registerPropertyMapper(d,u)}),(l=t.extensions)!=null&&l.contextLoader&&Object.keys(t.extensions.contextLoader).forEach(d=>{var h,p;const u=(p=(h=t.extensions)==null?void 0:h.contextLoader)==null?void 0:p[d];u&&A.loader.registerLoader(d,u)}),$.model.getAll().forEach(([,d])=>{t.models={...t.models,...d.registration}}),t.models={...t.models,...$.model.getLegacyModels()},$.companion.getAll().forEach(([d,u])=>{t.companionModels={...t.companionModels},t.companionModels[d]=t.companionModels[d]||[];for(const h of u)t.companionModels[d].push({type:h})}),$.model.getPreloadModels().forEach(d=>{t.preloadModels.includes(d)||t.preloadModels.push(d)});const n=Ui.create(t,s);return r.modelManager=n,r}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}}a(E,"_instance");const tn=f.createLogger({name:"kos-fetch"}),Wu=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,Zu=()=>new Promise(e=>{setTimeout(()=>{e(!0)},0)}),Ju=e=>e!=null&&e.studio?Ii:e!=null&&e.fos?Ti:$i,Qu=async(e,t)=>{const s=E.getInstance().transport;await s.whenReady();const o=Xe(),r=new URL(e),n=`${r.pathname}${r.search}`;tn.debug(`path: ${n}`);const i=(t==null?void 0:t.timeout)||Wu,c=Ju(t),l=ve(c({path:n,requestId:o,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}),t==null?void 0:t.body);return new Promise(d=>{const u=new AbortController,h=setTimeout(()=>{tn.error(`Timeout occurred - url: ${e}`),u.abort(),d({headers:yo({}),status:404,ok:!1,json:async()=>null,body:bo(""),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),{unsubscribe:p}=U(o,b=>{var I,C,se;clearTimeout(h);const _={headers:yo((b==null?void 0:b.headers)||{}),status:((I=b==null?void 0:b.headers)==null?void 0:I.status)&&parseInt((C=b==null?void 0:b.headers)==null?void 0:C.status)||200,ok:((se=b==null?void 0:b.headers)==null?void 0:se.status)==="200",json:async()=>{var we;try{return(we=b==null?void 0:b.body)!=null&&we.length?JSON.parse(b.body):null}catch{throw Error("Not a JSON response")}},text:async()=>(b==null?void 0:b.body)||"",body:bo((b==null?void 0:b.body)||""),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.")}};p(),Zu().then(()=>d(_))}),w=t!=null&&t.fos?s.fosSocket:s.socket;if(!w)throw Error(`No web socket transport available: ${t}`);w==null||w.send(l)})};exports.BASE_URL="kos:";exports.kosFetch=Qu;if(process.env.KOS_MOCK_FETCH==="true"){const e=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${e}`}const Xu=f.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class eh{constructor(){a(this,"visitedModels",new Set);this.visitedModels=new Set}start(t){var o;if(t.id===void 0)throw new Error("rootModel must have an id");const s=E.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error(`Could not find rootModel with id: ${t.id}`);this.visitedModels.clear(),(o=s.accept)==null||o.call(s,this)}visit(t){var o;if(this.visitedModels.has(t.modelId)){Xu.info(`model ${t.modelId} already visited`);return}const s=!!this.visitModel(t.modelData,this);this.visitedModels.add(t.modelId),!s&&((o=t.getChildren)==null||o.call(t).forEach(r=>{var n;(n=r.accept)==null||n.call(r,this)}))}}const qi=()=>({isMock:!1,URL:exports.BASE_URL}),th=f.createLogger({name:"kos-service-request"}),sh="errUnknown";async function Qt(e,t,s,o,r){const n=o!=null&&o.path?Object.keys(o.path).reduce((h,p)=>String(h).replace(`{${p}}`,o==null?void 0:o.path[p]),String(e)):String(e),i=o!=null&&o.query?Object.keys(o.query).map(h=>`${h}=${o.query[h]}`).join("&"):"",c=`${qi().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;th.debug(`fullUrl: ${c}`);const l={method:String(t).toUpperCase(),body:null,...s};r&&(l.body=JSON.stringify(r));const d=await exports.kosFetch(c,l);return d.status<200||d.status>=400?[`${d.statusText||sh}`,null]:[null,(await d.json()).data]}function Jo(){return{get:(e,t,s)=>Qt(e,"get",s,t),post:(e,t,s,o)=>Qt(e,"post",o,t,s),put:(e,t,s,o)=>Qt(e,"put",o,t,s),delete:(e,t,s)=>Qt(e,"delete",s,t)}}class Wi{constructor(){a(this,"middlewares",[])}use(t){this.middlewares.push(t)}async execute(t){let s=0;const o=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](t,o)};await this.middlewares[s](t,o)}}const oh=async(e,t)=>{const s=new Wi;t.forEach(r=>s.use(r));const o={data:e,result:{}};return await s.execute(o),o.result},et=e=>({type:e,build:(t,s)=>E.getInstance().modelManager.createModelInstance(e,t,s).data,buildAsync:async(t,s)=>{const o=E.getInstance().modelManager.createModelInstance(e,t,s);return await o.model.whenInitialized(),o.data}}),rh=e=>{E.getInstance().modelManager.registerModel(e)},nh=(e,t)=>{E.getInstance().modelManager.registerCompanionModel(e,t)},Zi=Symbol("KosObservableData");class Ji{constructor(){a(this,"map");a(this,"atomMap",new Map);a(this,"proxyHandler",{get:(t,s)=>{var o;return t[s]!==void 0?t[s]:this.atomMap.has(s)&&(o=this.atomMap.get(s))!=null&&o.reportObserved()?this.getValue(s):this.getValue(s)},set:(t,s,o)=>{var r;return this.setValue(s,o),this.atomMap.has(s)||this.atomMap.set(s,v.createAtom(s.toString())),(r=this.atomMap.get(s))==null||r.reportChanged(),!0},ownKeys:()=>Array.from(this.map.keys())});this.map=v.observable.map(new Map)}setValue(t,s){this.map.set(t,s)}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 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)}}Ji.prototype[Zi]=!0;function ih(e,t){return new Proxy(e,{construct:(s,o)=>{const r=new e(...o);return r.setValues(t),r.proxy}})}const ye=e=>{const t=ih(Ji,e);return new t(e)},sn="/kos/ui/internal/heartbeat/",ah=({relationshipId:e,destinationAddress:t,onAbort:s,waitTime:o,beatTime:r})=>{const n=E.getInstance().transport,i=new AbortController;let c=performance.now();const l=n.subscribeTopic({topic:`${sn}${e}`,callback:()=>{c=performance.now()}}),d=o??3e3,u=window.setInterval(()=>{let _=performance.now()-c;_=_/1e3,_>d/1e3&&i.abort()},d),h=r??2e3,p=window.setInterval(()=>{Li({msg:{},options:{topic:`${sn}${e}`,destinationAddress:t}})},h),w=()=>{window.clearInterval(p),window.clearInterval(u),l()},b=()=>{w(),s&&s(),i.signal.removeEventListener("abort",b)};return i.signal.addEventListener("abort",b),{cleanUpHeartbeat:w}},Qi=(...e)=>t=>e.reduce((s,o)=>o(s),t),ch={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function lh(e,t){let s=1;const o={...ch,...t},{maxAttempts:r,baseDelayMs:n,backoffFactor:i}=o;let c=n;for(;s<=r;)try{return await e()}catch(l){if(f.error(`Attempt ${s} failed: ${l}`),s<r)c=n*Math.pow(i,s),await new Promise(d=>setTimeout(d,c)),s++;else throw l}throw new Error("All attempts failed")}const dh=f.createLogger({name:"kos-service-request"}),q=e=>({isMock:!1,URL:exports.BASE_URL}),uh=(e,t,s)=>async({id:o,tracker:r,urlOverride:n,ordered:i,studio:c,fos:l,bridge:d,destinationAddress:u})=>{const h={method:"DELETE"};e&&(h.destinationAddress=e),r&&(h.tracker=r),tt(h,{ordered:i,studio:c,fos:l,bridge:d,destinationAddress:u});const p=await s(n||`${t}/${o}`,h);if(!p.ok)throw Error(`There was a problem deleting the model; returned status ${p.status}`);return await p.json()},tt=(e,{ordered:t,studio:s,fos:o,destinationAddress:r,bridge:n,timeout:i})=>(i&&(e.timeout=i),t&&(e.ordered=t),s&&(e.studio=s),o&&(e.fos=o),n&&(e.bridge=n),(r||r==="")&&(e.destinationAddress=r),e),hh=(e,t,s)=>async({urlOverride:o,ordered:r,studio:n,fos:i,bridge:c,timeout:l,destinationAddress:d})=>{const u={method:"GET"};e&&(u.destinationAddress=e),tt(u,{timeout:l,ordered:r,studio:n,fos:i,bridge:c,destinationAddress:d});const p=await s(o||t,u);if(!p.ok){let b;try{b=await p.json()}catch{}throw new ce(`There was a problem retrieving the model; returned status ${p.status}`,b)}return await p.json()},gh=(e,t,s)=>async({urlOverride:o,ordered:r,studio:n,fos:i,bridge:c,tracker:l,timeout:d,destinationAddress:u})=>{const h={method:"GET"};e&&(h.destinationAddress=e),l&&(h.tracker=l),tt(h,{timeout:d,ordered:r,studio:n,fos:i,bridge:c,destinationAddress:u});const p=o||t;dh.debug(`resolvedUrl: ${p}`);const w=await s(p,h);if(!w.ok){let _;try{_=await w.json()}catch{}throw new ce(`There was a problem retrieving the model; returned status ${w.status}`,_)}return await w.json()},fh=(e,t,s)=>async({urlOverride:o,id:r,ordered:n,studio:i,fos:c,bridge:l,timeout:d,destinationAddress:u})=>{const h={method:"GET"};e&&(h.destinationAddress=e),tt(h,{timeout:d,ordered:n,studio:i,fos:c,bridge:l,destinationAddress:u});const p=o||`${t}/${r}`,w=await s(p,h);if(!w.ok){let _;try{_=await w.json()}catch{}throw new ce(`There was a problem retrieving the model; returned status ${w.status}`,_)}return await w.json()};class ce extends Error{constructor(s,o){super(s);a(this,"payload");this.name="FetchException",this.payload=o}}const on=(e,t,s)=>async({model:o,urlOverride:r,ordered:n,tracker:i,studio:c,fos:l,bridge:d,timeout:u,destinationAddress:h})=>{const p={method:"POST",body:typeof o=="string"?o:JSON.stringify(o)};e&&(p.destinationAddress=e),i&&(p.tracker=i),tt(p,{timeout:u,ordered:n,studio:c,fos:l,bridge:d,destinationAddress:h});const w=await s(r||t,p);if(!w.ok){let _;try{_=await w.json()}catch{}throw new ce(`There was a problem sending the POST data; returned status ${w.status}`,_)}return await w.json()},rn=(e="POST",t,s,o)=>async({model:r,id:n,urlOverride:i,ordered:c,studio:l,fos:d,bridge:u,timeout:h,destinationAddress:p})=>{const w={method:e};r&&(w.body=JSON.stringify(r)),t&&(w.destinationAddress=t),tt(w,{timeout:h,ordered:c,studio:l,fos:d,bridge:u,destinationAddress:p});const b=await o(i||`${s}/${n}`,w);if(!b.ok){let I;try{I=await b.json()}catch{}throw new ce(`There was a problem modifying the model; returned status ${b.status}`,I)}return await b.json()},Y={build:({destinationAddress:e="",basePath:t,getAllPath:s,getOnePath:o,deleteModelPath:r,addModelPath:n,modifyModelPath:i,mock:c=!1})=>{const l=c?fetch:exports.kosFetch;return{getAll:hh(e,s||t,l),getModelById:fh(e,o||t,l),getOne:gh(e,o||t,l),addModel:on(e,n||t,l),deleteModel:uh(e,r||t,l),modifyModel:rn("POST",e,i||t,l),putModel:rn("PUT",e,i||t,l),postModel:on(e,n||t,l)}}},ph=Xe(),Xi=()=>`kos-${ph}`,mh=e=>!!e&&!e.includes("VM_SERVICE")&&e.startsWith(Xi()),Qo=async(e,t=6e4)=>new Promise((s,o)=>{const{unsubscribe:r}=U(e,i=>{T.debug(`recieved response for refId ${e}: ${i}`),r(),clearTimeout(n);try{const c=i!=null&&i.body?JSON.parse(i.body):{};s(c)}catch{const c=(i==null?void 0:i.body)||{};s(c)}}),n=setTimeout(()=>{r(),o(Error(`Request with ID ${e} timed out. Cancelling.`))},t)}),yh=async(e,t,s)=>{const o=Qo(s),r=await Promise.allSettled([e(t),o]);if(r[0].status==="fulfilled"){if(r[1].status==="rejected")throw Error(r[1].reason);if(r[0].value){if(r[1].value.error)throw Error(r[1].value.error);return r[0].value.data=r[1].value,r[0].value}}else throw Error(r[0].reason)},bh=async({topic:e,msg:t,requestId:s})=>{const o=s??Xe(),r=Qo(o);F(e,t,{sync:o});const n=await r;if(n.error)throw Error(n.error);return n},ue=new Map;class ea{constructor(t){a(this,"_context");a(this,"_parent");a(this,"_id");this._id=t,this._context=new v.ObservableMap({}),this._parent="",v.makeAutoObservable(this)}setParent(t){z(()=>{this._parent=t})}get id(){return this._id}get context(){return this._context}get parentModel(){var t;if(this._parent)return(t=Ae(this._parent))==null?void 0:t.model}get(t){var s;if(this._context.has(t))return this._context.get(t);if(this._parent)return(s=ue.get(this._parent))==null?void 0:s.get(t)}set(t,s){this._context.set(t,s)}remove(t){this._context.delete(t)}clear(){this._context.clear()}}const k={createContext:(e,t)=>{const s=ue.get(e)??new ea(e);if(t){if(!ue.has(t))throw new Error(`Parent context ${t} does not exist`);s.setParent(t)}else e!=="root"&&s.setParent("root");return ue.set(e,s),s},getContext:e=>ue.get(e),deleteContext:e=>{ue.delete(e)},setParentContext:(e,t)=>{var s;if(!ue.has(t))throw new Error(`Parent context ${t} does not exist`);(s=ue.get(e))==null||s.setParent(t)},rootContext:()=>ue.get("root")};k.createContext("root");const vh=e=>k.getContext(e.id);function wh(e,t){return e.length!==t.length?!1:e.every(s=>t.includes(s))}class Xo{constructor({container:t,key:s}){a(this,"_container");a(this,"_map");a(this,"_key");a(this,"data");this._container=t,this._map=v.observable.map(new Map),this._key=s,this.data=ye(),this.generateIndex(),v.autorun(()=>{this._container.revision&&this.generateIndex()}),v.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(t,s,o=this._map,r=this.data){const n=o.get(t)||new Set;n.add(s),o.set(t,n),r[t]=Array.from(n)}resolveIndex(t,s){this.data.keys.filter(r=>!Object.keys(s).includes(r)).forEach(r=>{delete this.data[r],this._map.delete(r)}),Object.keys(s).forEach(r=>{const n=s[r],i=this.data[r]||[];if(wh(n,i))f.debug(`KosContainerIndex - Index ${r} is the same`);else{this.data[r]=n;const c=t.get(r)||new Set;this._map.set(r,c)}})}generateIndex(){v.runInAction(async()=>{const t=new Map,s={};for(const o of this._container.data){const r=typeof this._key=="function"?await this._key(o):o[this._key];Array.isArray(r)?r.forEach(n=>{this.addItemToIndex(n,o,t,s)}):typeof r=="string"||typeof r=="number"?this.addItemToIndex(String(r),o,t,s):typeof r=="boolean"&&this.addItemToIndex(String(r),o,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 Mh(e,t,s=[]){const o=Object.getOwnPropertyDescriptors(e);return Object.keys(o).filter(i=>v.isComputedProp(e,i)).filter(i=>s.includes(i)).map(i=>v.reaction(()=>e[i],(c,l)=>{t({name:i,newValue:c,oldValue:l})}))}const it=f.createLogger({name:"kos-container-model"});class de{constructor(t){a(this,"_data");a(this,"_sortKey");a(this,"_revision");a(this,"_index");a(this,"_optionsMap");a(this,"_disposerMap",new Map);a(this,"_parentId");a(this,"idx");this._data=v.observable.map(new Map),this._sortKey=t==null?void 0:t.sortKey,this._revision=1;const s=t!=null&&t.extensionId?A.indexExtension.loadIndexExtensions(t.extensionId):{},o=(t==null?void 0:t.indexMap)||{};this._optionsMap={...o,...s};const r=t!=null&&t.indexMap?Object.keys(t.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=v.observable.map(r),this.idx=ye(),this._parentId=t==null?void 0:t.parentId,v.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],o=new Xo({container:this,key:s});this._index.set(t,o),this.idx[t]=o.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 o;return t[s]=(o=this.index.get(s))==null?void 0:o.keys,t},{})}sortFn(t,s){const o=this._sortKey;return o?String(t[o]).localeCompare(String(s[o]),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(){v.runInAction(()=>{this._revision=this._revision+1})}addAll(t){v.runInAction(()=>{t.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(t){v.runInAction(()=>{t.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(t,s){this._data.set(t.id||"",t),t.id&&this._parentId&&k.setParentContext(t.id,this._parentId),s||this.increment();const o=this._disposerMap.get(t.id);o&&(o(),this._disposerMap.delete(t.id));const r=Object.entries(this._optionsMap||{}),n=Object.values(this._optionsMap||{}),i=new Map(r.map(([u,h])=>[h,u])),c=u=>{var p,w;n.includes(u.name)&&((p=this.index.get(i.get(u.name)))==null||p.refresh());const h=r.filter(([,b])=>typeof b=="function");for(const[b]of h)(w=this.index.get(b))==null||w.refresh()},l=Mh(t,c,n.filter(u=>typeof u=="string")),d=v.observe(t,c);this._disposerMap.set(t.id||"",()=>[d,...l].forEach(u=>u()))}removeModel(t,s){this._data.delete(t),s||this.increment();const o=this._disposerMap.get(t);o&&(o(),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??[]:(it.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(t,s){if(this.index.has(t)){const o=this.index.get(t);return o.index.has(s)?o.getByKey(s):(it.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return it.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(t=>{const s=t.id;Oe(t).then(()=>{it.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(o=>it.error(o))}),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 co=f.createLogger({name:"kos-data-container"});class ta{constructor(t){a(this,"_data");a(this,"_sortKey");a(this,"_revision");a(this,"_index");a(this,"_optionsMap");a(this,"_disposerMap",new Map);a(this,"idx");this._data=v.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((o,r)=>(o[r]=void 0,o),{}):{};this._index=v.observable.map(s),this.idx=ye(),v.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],o=new Xo({container:this,key:s});this._index.set(t,o),this.idx[t]=o.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 o;return t[s]=(o=this.index.get(s))==null?void 0:o.keys,t},{})}get revision(){return this._revision}addAll(t){v.runInAction(()=>{t.forEach(s=>this.addModel(s))})}removeAll(t){v.runInAction(()=>{t.forEach(s=>this.removeModel(s))})}sortFn(t,s){const o=this._sortKey;return o?String(t[o]).localeCompare(String(s[o]),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(){v.runInAction(()=>{this._revision=this._revision+1})}addModel(t,s){const o=v.isObservable(t)?t:v.observable.object(t),r=this._disposerMap.get(t.id);r&&(r(),this._disposerMap.delete(t.id)),this._data.set(o.id||"",o),s||this.increment();const n=v.observe(o,i=>{Object.values(this._optionsMap||{}).includes(i.name)&&this.increment()});this._disposerMap.set(o.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=v.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??[]:(co.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(t,s){if(this.index.has(t)){const o=this.index.get(t);return o.index.has(s)?o.getByKey(s):(co.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return co.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 _h{constructor({type:t,model:s,childRegistration:o}){a(this,"type");a(this,"childRegistration");a(this,"model");this.type=t,this.model=s,this.childRegistration=o}get factory(){return H.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 Eh{constructor({type:t,model:s,childRegistration:o}){a(this,"type");a(this,"model");a(this,"childRegistration");this.type=t,this.model=s,this.childRegistration=o}get factory(){return H.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 sa{constructor(){a(this,"_token");v.makeAutoObservable(this),U("token",t=>{this.token=t==null?void 0:t.body})}get token(){return this._token}set token(t){this._token=t}}class oa{constructor(){a(this,"routes",[]);a(this,"openApiRoutes",[])}use(t,s,...o){this.routes.push({method:t,path:s,middlewares:o});const r=this.extractOpenApiParams(s);this.openApiRoutes.push({method:t,path:s,parameters:r})}async handle(t,s){var c;const{path:o,query:r,params:n}=this.extractPathParams(t.path),i={...t,params:n,query:r};for(const l of this.routes){const d=this.matchRoute(l.path,o);if(l.method===t.method&&d){i.params=d;let u=0;const h=async()=>{if(u<l.middlewares.length){const p=l.middlewares[u++];await p(i,s,h)}};await h();return}}(c=s.status)==null||c.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,o]=t.split("?"),r=this.parseQueryParams(o);for(const n of this.routes){const i=this.matchRoute(n.path,s);if(i)return{path:s,query:r,params:i}}return{path:s,query:r,params:{}}}matchRoute(t,s){const o=t.split("/").filter(Boolean),r=s.split("/").filter(Boolean);if(o.length!==r.length)return null;const n={};for(let i=0;i<o.length;i++)if(o[i].startsWith(":"))n[o[i].slice(1)]=decodeURIComponent(r[i]);else if(o[i]!==r[i])return null;return n}parseQueryParams(t){return t?t.split("&").reduce((s,o)=>{const[r,n]=o.split("=").map(decodeURIComponent);return s[r]=n??"",s},{}):{}}}const ra=f.createLogger({name:"intent-service"}),Ih=e=>{Bo(`/kos/intent/${e.type}`)?F(`/kos/intent/${e.type}`,e.options,{"kos.intent.type":e.type}):ra.info(`No subscribers for intent ${e.type}. Intent not sent.`)},Th=async e=>new Promise(t=>{const{type:s,options:o}=e;if(Bo(`/kos/intent/${e.type}`)){const r=Xe(),{unsubscribe:n}=U(r,c=>{clearTimeout(i),n(),c&&(c.headers=c.headers||{},c.headers["kos.intent.type"]=s,c.headers.responseId=r),t([null,{body:c==null?void 0:c.body,payload:c}])}),i=setTimeout(()=>{n(),t([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);F(`/kos/intent/${s}`,o,{"kos.intent.type":s,sync:r})}else ra.info(`No subscribers for intent ${e.type}. Intent not sent.`),t([null,{body:void 0,payload:void 0}])}),_o=v.when,er=v.computed,z=v.runInAction,N=v.autorun,na=v.reaction,tr=v.observable,sr="Not Assigned",$h="kos.trouble.added",Oh="kos.trouble.removed";var re=(e=>(e.TroubleRank="kos.trouble.rank.mapper",e.TroubleColor="kos.trouble.color.mapper",e.TroubleRole="kos.trouble.role.mapper",e))(re||{}),Ot=(e=>(e.TIME_CHANGE="/kos/internal/time/time",e.DAY_CHANGE="/kos/internal/time/day",e.TIMEZONE_CHANGE="/kos/internal/time/timezone",e))(Ot||{});const ia=f.createLogger({name:"config-bean-service",group:"Services"}),or=exports.BASE_URL,aa=e=>(e==null?void 0:e.decimals)!==void 0,{postModel:Dh,getOne:Sh}=Y.build({destinationAddress:"",basePath:`${or}/kos/config/`}),ca=async(e,t,s="/api/kos/config")=>(ia.debug(`sending modify request for ConfigBean: ${e}`),Dh({model:t,urlOverride:`${or}${s}/${e}`})),la=async(e,t="/api/kos/config")=>(ia.debug(`sending get request for ConfigBean: ${e}`),await Sh({urlOverride:`${or}${t}/details/${e}/15`})),rr=e=>e.toLowerCase()==="true"||e.toLowerCase()==="false",js=e=>{try{const t=Number(e);return!isNaN(t)}catch{return!1}};function da(e=[]){return e.reverse().reduce((t,s)=>{const{overrides:o}=s;return o&&(t={...t,...o}),t},{})}function ua(e,t="",s={}){for(const o in e)if(Object.prototype.hasOwnProperty.call(e,o)){const r=t?`${t}.${o}`:o;typeof e[o]=="object"&&e[o]!==null&&!Array.isArray(e[o])?ua(e[o],r,s):s[r]=e[o]}return s}const ha=(e,t)=>{const s=e.details[0].bean||da(e.details[0].scopes),o=ua(s);v.runInAction(()=>{const r={...o};t.props.setValues(r)})},ga=(e,t)=>{v.runInAction(()=>{e.changes.forEach(s=>{const o=s.attr;let r=s.currentValue,n=s.previousValue;typeof r=="string"&&rr(r)&&(r=r.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof r=="string"&&js(r)&&(r=Number(r),n=Number(n)),t.props[o]=r,t.prevProps[o]=n})})},fa=e=>Object.fromEntries(e.props.entries),Ch=e=>t=>s=>e.build(t,s);var Ah=Object.defineProperty,Rh=Object.getOwnPropertyDescriptor,pa=(e,t,s,o)=>{for(var r=o>1?void 0:o?Rh(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Ah(t,s,r),r};function Lh(e,t){for(const s of e)if(new RegExp(`^${s}$`).test(t))return s}const nr="config-bean-model",Xt=f.getLogger(nr),Ph=Se("path");let ps=class{constructor(e,t){a(this,"_modifyConfigBean");a(this,"_getConfigBean");a(this,"_schema");a(this,"id");a(this,"path");a(this,"props");a(this,"prevProps");a(this,"serviceBasePath");Object.assign(this,t),this.id=e,this.path=t.path,this.serviceBasePath=t.serviceBasePath;const{modifyConfigBean:s=ca,getConfigBean:o=la}=t;this._modifyConfigBean=s,this._getConfigBean=o,this.props=ye(),this.prevProps=ye()}get values(){return this.props.values}async ready(){Xt.debug(`readying config bean ${this.path}`),Xt.debug(`complete readying config bean ${this.path}`)}async load(){Xt.debug(`loading config bean ${this.path}`);const e=await this._getConfigBean(this.path,this.serviceBasePath);if(e!=null&&e.data){const t=e.data;ha(t,this),Xt.debug(this.values);const s=e==null?void 0:e.data.details[0].schema;z(()=>{s&&(this._schema=s)})}}get schemaKeys(){var e;return Object.keys(((e=this._schema)==null?void 0:e.schema)||{})}getSchemaForProperty(e){var s,o;if(this.schemaKeys.includes(e))return(s=this._schema)==null?void 0:s.schema[e];const t=Lh(this.schemaKeys,e);if(t)return(o=this._schema)==null?void 0:o.schema[t]}async updateProperty(e,t){this.props[e]=t,await this.updateConfigBean()}async updateConfigBean(){const e=fa(this);await this._modifyConfigBean(this.path,e,this.serviceBasePath)}handleConfigBeanUpdated(e){ga(e,this)}};pa([R({topic:`/kos/config/${Ph}`,websocket:!0})],ps.prototype,"handleConfigBeanUpdated",1);ps=pa([O(nr)],ps);const Ct=new ae({class:ps,type:nr}),Bs=({path:e,lazy:t,serviceBasePath:s})=>(o,r)=>{o[P]=o[P]||{},o[P][r]={modelType:Ct.type,id:`${Ct.type}-${e}`,options:{path:e,serviceBasePath:s},lifecycle:x.INIT,lazy:t}},{URL:ma}=q(),{getOne:kh,getAll:xh}=Y.build({basePath:`${ma}/api/kos/regions/info`}),ya=async()=>await kh({}),ba=async()=>await xh({urlOverride:`${ma}/api/kos/regions`}),Fh=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:ya,getRegions:ba},Symbol.toStringTag,{value:"Module"}));var Z=(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))(Z||{});const va={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 Nh(e,t){const s=t.id,o=t.units.reduce((r,n)=>{const i=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return r[n.name]=i,n.alias&&(r[n.alias]=i),r},{...va});return{...e,...o}}function Uh(e,t){const s=t.id,o=t.units.reduce((r,n)=>{const i=r[n.measure]||{},c=i[s]||{};i[s]=c;const l=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return c[n.name]=l,Object.hasOwn(n,"default")&&Object.defineProperty(c,"default",{value:l,writable:!0,enumerable:!0,configurable:!0}),r[n.measure]=i,n.alias&&(r[n.alias]=i),r},{time:{[s]:{...va}}});return Object.keys(o).forEach(r=>{e[r]={...e[r],...o[r]}}),e}function jh(e,t){const s=t.id,o=t.units.reduce((r,n)=>{const i=r[n.measure]||{};return Object.hasOwn(n,"default")&&(i[s]=n.name),r[n.measure]=i,r},{time:{[s]:"millisecond"}});return Object.keys(o).forEach(r=>{e[r]={...e[r],...o[r]}}),e}var Bh=Object.defineProperty,Kh=Object.getOwnPropertyDescriptor,ir=(e,t,s,o)=>{for(var r=o>1?void 0:o?Kh(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Bh(t,s,r),r};const ls="region-info-model",at=f.createLogger({name:"region-info-model"});let At=class{constructor(e){a(this,"id");a(this,"unitSystemMap");a(this,"measureMap");a(this,"defaultMeasureMap");a(this,"regionMap");a(this,"timeFormats");a(this,"dateFormats");a(this,"unitSystems");a(this,"regionSource");a(this,"region");a(this,"regions",[]);a(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[Z.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[Z.family]}getDefaultUnitDecimalPlaces(e,t,s){if(!e||!t)throw Error("Measure and unit system are required");const o=s==="drt"?"second":s,r=this.measureMap[e];if(!r)throw Error(`No unit systems found for measure: ${e}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const n=r[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(r).join(", ")}`);const i=n[o||"default"];if(!i)throw Error(`No unit "${o||"default"}" found for measure: ${e} and unit system: ${t}. Unit should come from list of units: ${Object.keys(n).join(", ")}`);return i[Z.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 o=s[t.toLowerCase()];if(!o)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 o}convertByUnit(e,t,s){if(t[Z.family]!==s[Z.family])throw new Error(`Cannot convert between units of different families: ${t[Z.family]} and ${s[Z.family]}`);const o=t[Z.offset],r=t[Z.scale],n=s[Z.scale],i=s[Z.offset],c=s[Z.decimals];return((e-o)/(r/n)+i).toFixed(c)}convertByUnitName(e,t,s){const o=this.unitSystemMap[t],r=this.unitSystemMap[s];if(!o||!r)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,o,r)}convert(e,t,s){var c,l;if(t.unit&&s.unit)return this.convertByUnitName(e,t.unit,s.unit);const o=t.unit||"",r=s.unit||"";let n=this.unitSystemMap[o],i=this.unitSystemMap[r];if(!i&&s.measure&&s.system){const d=this.measureMap[s.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(c=d[s.system])==null?void 0:c.default,i||at.info("Could not find default unit for measure",s.measure)}if(!n&&t.measure&&t.system){const d=this.measureMap[t.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(l=d[t.system])==null?void 0:l.default,n||at.info("Could not find default unit for measure",t.measure)}return!n||!i?(at.warn("Could not find unit to convert to or from. Return value as is"),String(e)):this.convertByUnit(e,n,i)}async init(){at.debug("initializing region info")}async load(){at.debug("loading region info");const e=await ba();e&&(this.regions=e.data.map(s=>s.id),this.timeZoneMap=e.data.reduce((s,o)=>({...s,[o.id]:o.timeZones}),this.timeZoneMap),this.regionMap=e.data.reduce((s,o)=>({...s,[o.id]:o}),{}));const t=await ya();t&&(this.unitSystems=t.data.unitSystems.reduce((s,o)=>{const r={id:o.id,name:o.id};return s[o.id]=r,s},this.unitSystems),this.unitSystemMap=t.data.unitSystems.reduce(Nh,{}),this.measureMap=t.data.unitSystems.reduce(Uh,{}),this.defaultMeasureMap=t.data.unitSystems.reduce(jh,{}),this.timeFormats=t.data.timeFormats.reduce((s,o)=>({...s,[o.id]:o}),{}),this.dateFormats=t.data.dateFormats.reduce((s,o)=>({...s,[o.id]:o}),{}))}async ready(){var e,t;await((t=(e=this.regionSource).ready)==null?void 0:t.call(e))}};ir([Bs({path:"kos:service:region:settings"})],At.prototype,"regionSource",2);ir([Bs({path:"kos:service:region"})],At.prototype,"region",2);At=ir([O(ls)],At);const V={registration:{[ls]:{class:At,singleton:!0}},type:ls,factory:H.Singleton.create(ls)},ms=({source:e,defaultSystem:t="si",defaultMeasure:s})=>{let o={system:t,measure:s};return typeof e=="string"?o={...o,unit:e}:o={...o,...e},o},ar=(e,t,s)=>{const{model:o}=Ae(V.type);if(!o)throw new Error("RegionInfo model not found");if(!fs(o))throw new Error("RegionInfo model not ready");const r={system:o.defaultUnitSystem},n=ms({source:t}),i=ms({source:s||r,defaultMeasure:o.getUnitMeasure(n.unit||"")});return o.convert(e,n,i)};function nn(e,t,s){const o=t.toLowerCase().replace(/_/g,"-").replace(/s$/,""),r=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,c=(s==null?void 0:s.minDecimals)??0;return new Intl.NumberFormat(r,{style:"unit",unit:o,unitDisplay:n,minimumFractionDigits:c,maximumFractionDigits:i}).format(e)}catch{return t}}const Gh=(e,t,s,o)=>{const r=ar(e,t,s),n=ms({source:t}),{model:i}=Ae(V.type);if(!i)throw new Error("RegionInfo model not found");const c=i.getUnitMeasure(n.unit||""),l={system:i.defaultUnitSystem},d=ms({source:s||l,defaultMeasure:i.getUnitMeasure(n.unit||"")}),u=i.getDefaultUnitForMeasure(c,d.system),h=i.getDefaultUnitDecimalPlaces(c,d.system),p={...o,minDecimals:(o==null?void 0:o.minDecimals)??h,maxDecimals:(o==null?void 0:o.maxDecimals)??h};return{value:r,unit:u||n.unit||"",display:nn(r,u||n.unit||"",{...p,mode:"long"}),shortDisplay:nn(r,u||n.unit||"",{...p,mode:"short"})}};function an({start:e,end:t,count:s,decimals:o=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 r=(t-e)/(s-1),n=[];for(let i=0;i<s;i++){const c=Math.round(e+i*r);n.push(c.toFixed(o))}return n}function cn({start:e,end:t,interval:s,decimals:o=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 r=[];let n=e;for(;n<=t;)r.push(n.toFixed(o)),n+=s;return r[r.length-1]!==t.toString()&&r.push(t.toString()),r}const ke=(e,t)=>s=>!e||!t?s:js(s)?ar(Number(s),e,t):s,Vh=(e,t,s,o)=>{if((e==null?void 0:e.type)==="enum"||!(e!=null&&e.options))return[];if(e.options.type==="rangeCount")return an(e.options).map(ke(s,o));if(e.options.type==="rangeInterval")return cn(e.options).map(ke(s,o));if(e.options.type==="list"){const{list:r}=e.options;return r.map(ke(s,o))}else{if(e.options.type==="unitSystemRangeCount"&&t)return an(e.options.unitSystems[t]).map(ke(s,o));if(e.options.type==="unitSystemRangeInterval"&&t)return cn(e.options.unitSystems[t]).map(ke(s,o));if(e.options.type==="unitSystemList"&&t){const{list:r}=e.options.unitSystems[t];return r.map(ke(s,o))}}return[]},Hh=(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 Yh=Object.defineProperty,zh=Object.getOwnPropertyDescriptor,cr=(e,t,s,o)=>{for(var r=o>1?void 0:o?zh(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Yh(t,s,r),r};function qh(e){return(e==null?void 0:e.type)==="enum"}function Wh(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 Zh(e,t){const s=new Date;s.setHours(0,0,0,0);const o=new Date(s.getTime()+e*1e3);return me.format(o,t)}const ds="config-bean-prop-model",xe=f.createLogger({name:"config-bean-prop-model"}),Jh=Se("path"),Qh=Se("serviceBasePath");let Rt=class{constructor(e,t){a(this,"id");a(this,"path");a(this,"attribute");a(this,"converter");a(this,"formatter");a(this,"optionsExpander");a(this,"serviceBasePath");a(this,"regionInfo");a(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 aa(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?Wh(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,o=this.bean.getSchemaForProperty(this.attribute),r=qh(o)?o.values:Vh(o,s,t==null?void 0:t.from,t==null?void 0:t.to),n=r.length>0?r.map(c=>({label:c,value:c})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,r):this.optionsExpander:n}convertUnit(e,t,s){const o=(e==null?void 0:e.measure)||s,r=(e==null?void 0:e.system)||t,n=e==null?void 0:e.unit;return{measure:o,system:r,unit:n}}getConverterUnits(){const e=this.regionInfo.defaultUnitSystem,t=this.getConverter();if(!t)throw Error("No converter defined");const s=t.measure,o=this.convertUnit(t.from,"si",s),r=this.convertUnit(t.to,e,s);return{backend:o,display:r}}set value(e){this.updateProperty(e)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var r,n;const e=this.value,t=this.regionInfo.defaultUnitSystem,s=this.getConverter(),o=(s==null?void 0:s.measure)||((r=s==null?void 0:s.to)==null?void 0:r.measure);if(!isNaN(e)&&s&&o){const i=this.getDefaultUnitDecimalPlaces(o,t,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const l=this.getFormatterOptions(s);if(l){let d=String(e);return d=l.formatToParts(Number(e))[0].value,Number(d)}}catch(l){xe.info(`error formatting value ${e}`,l)}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:o,display:r}=this.getConverterUnits();return this.regionInfo.convert(Number(t),o,r)}return t||""}async activate(){xe.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 Zh(e,s)}if(!isNaN(e))try{const t=this.getConverter(),s=this.getFormatterOptions(t);if(s){let o=String(e);return o=s.format(Number(e)),o}}catch(t){xe.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 o=t.formatToParts(Number(this.value)).find(r=>r.type==="unit");return(o==null?void 0:o.value)??this.getDefaultUnit(e)}}return this.getDefaultUnit(e)}get displayOptions(){var r;const e=this.bean.getSchemaForProperty(this.attribute),t=this.regionInfo.defaultUnitSystem,s=this.getConverter(),o=((r=s==null?void 0:s.to)==null?void 0:r.system)??t;return Hh(e,o)}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 o,r;const t=this.regionInfo.defaultUnitSystem,s=e==null?void 0:e.measure;return s?((o=e==null?void 0:e.to)==null?void 0:o.unit)||this.getDefaultUnitForMeasure(s,((r=e==null?void 0:e.to)==null?void 0:r.system)||t):this.getConverterFromFormat().unit}getFormatterOptions(e){var n,i,c;const t=this.regionInfo.defaultUnitSystem,s=e==null?void 0:e.measure,o=new Intl.NumberFormat().resolvedOptions().locale;let r=null;if(s||this.formatter){const l=s?{style:"unit",unit:this.getDefaultUnit(e)}:null,d=this.formatter||l;if(d){let u=typeof d=="function"?d(((n=e==null?void 0:e.to)==null?void 0:n.system)||t):d;s&&(u={unit:this.getDefaultUnit(e),...u},u.style==="unit"&&(u.maximumFractionDigits=u.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=e==null?void 0:e.to)==null?void 0:i.system)||t,(c=e==null?void 0:e.to)==null?void 0:c.unit)));try{r=new Intl.NumberFormat(o,{...u})}catch(h){xe.error(`error creating formatter ${u}. Returning the raw value`,h)}}else xe.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return r}getConverter(){var o,r,n,i,c,l,d,u,h,p,w;const{unit:e,measure:t}=this.getConverterFromFormat(),s=e==="drt"?"second":e;if(this.converter){const b=(o=this.converter)==null?void 0:o.measure,_=(n=(r=this.converter)==null?void 0:r.to)==null?void 0:n.measure,I=(c=(i=this.converter)==null?void 0:i.from)==null?void 0:c.measure,C=b||_||I||t,se=((d=(l=this.converter)==null?void 0:l.to)==null?void 0:d.unit)||this.regionInfo.getDefaultUnitForMeasure(C,((h=(u=this.converter)==null?void 0:u.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),we=((w=(p=this.converter)==null?void 0:p.to)==null?void 0:w.system)??this.regionInfo.getUnitSystem(se),rt=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:rt,...this.converter.from},to:{...this.converter.to,unit:se,system:we},measure:C}}if(s&&t){const b=this.regionInfo.getDefaultUnitForMeasure(t,this.regionInfo.defaultUnitSystem),_=this.regionInfo.getUnitSystem(s),I=this.regionInfo.getUnitSystem(b);return{measure:t,to:{unit:_===I?s:b}}}}async updateProperty(e){xe.debug(`updating property ${this.attribute} with value ${e}`);let t=e;if(this.getConverter()&&!isNaN(t)){const{backend:r,display:n}=this.getConverterUnits();t=this.regionInfo.convert(Number(t),n,r)}const o=Array.isArray(t)?JSON.stringify(t):String(t);await this.bean.updateProperty(this.attribute,o)}};cr([Ce({modelType:V.type})],Rt.prototype,"regionInfo",2);cr([Bs({path:Jh,serviceBasePath:Qh})],Rt.prototype,"bean",2);Rt=cr([O(ds)],Rt);const Re={registration:{[ds]:{class:Rt,singleton:!1}},type:ds,factory:H.Factory.create(ds)};function Xh(e){const{path:t,attribute:s,converter:o,formatter:r,lazy:n,optionsExpander:i,serviceBasePath:c}=e,l=o;return l&&(typeof l!="function"&&typeof l.from=="string"&&(l.from={unit:l.from}),typeof l!="function"&&typeof l.to=="string"&&(l.to={unit:l.to})),(d,u)=>{d[P]=d[P]||{},d[P][u]={modelType:Re.type,id:`${t}-${s}`,options:{path:t,attribute:s,serviceBasePath:c,converter:l,formatter:r,optionsExpander:i},lifecycle:x.INIT,lazy:n}}}class eg{constructor(t,s){a(this,"futures");a(this,"defaultContext");a(this,"context");a(this,"disposers",new Map);a(this,"container");this.futures=tr.map(new Map),this.context="",this.defaultContext=s||"",this.container=t,v.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 o=N(()=>{var r,n;(t.endState||t.progress)&&((n=(r=this.container)==null?void 0:r.onFutureUpdate)==null||n.call(r,t))});this.disposers.set(s||t.id,o)}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 lr{constructor(t){a(this,"disposer");a(this,"_future");a(this,"container");a(this,"onFutureUpdate");this._future=void 0,this.container=t,v.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=N(()=>{var o,r;(t.endState||t.progress)&&((r=(o=this.container)==null?void 0:o.onFutureUpdate)==null||r.call(o,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 f.error(t),t}}}const wa="future-model",st=et(wa),Ks=f.createLogger({name:"future-service",group:"Services"}),{isMock:tg,URL:Ht}=q();var Ve=(e=>(e.Success="SUCCESS",e.Fail="FAIL",e.Aborted="ABORT",e.Canceled="CANCEL",e))(Ve||{});const{getAll:sg,modifyModel:og,addModel:rg,deleteModel:ng,postModel:ig}=Y.build({destinationAddress:"",basePath:`${Ht}/api/future`,mock:tg}),ag=async()=>await sg({}),Ma=async(e,t="/api/kos/future")=>(Ks.info(`sending delete request for Future: ${e}`),await ng({id:e,urlOverride:`${Ht}${t}/${e}`})),_a=async(e,t="/api/kos/future")=>(Ks.info("sending add request for Future"),await rg({model:e,urlOverride:`${Ht}${t}`})),cg=async(e,t,s="/api/kos/future")=>(Ks.info(`sending modify request for Future: ${e}`),og({model:t,id:e,urlOverride:`${Ht}${s}/${e}`})),Ea=async(e,t="/api/kos/future")=>(Ks.info(`sending cancel request for Future: ${e}`),ig({urlOverride:`${Ht}${t}/${e}/cancel`,ordered:!0,model:{}})),dr=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}),ur=(e,t)=>{f.debug(`future dto ${e.id} end state ${e.endState}`),f.debug(`future model ${t.id} end state ${t.endState}`),t.endState?f.debug(`future model ${t.id} is already complete`):(f.debug(`updating future model ${t.id}`),v.runInAction(()=>{const s=dr(e);z(()=>{Object.keys(s).forEach(o=>{o==="id"?(t.futureId=s.id,s.tracker||(t.id=s.id)):o==="tracker"?t.id=s.tracker:t[o]=s[o]})})}))},Ia=e=>t=>s=>e.build(String(t),s),hr=e=>t=>Qi(dr,Ia(e)(t.tracker||t.id))(t);var lg=Object.defineProperty,dg=Object.getOwnPropertyDescriptor,Ta=(e,t,s,o)=>{for(var r=o>1?void 0:o?dg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&lg(t,s,r),r};const lo=f.getLogger(st.type);let ys=class{constructor(e,t,s){a(this,"logger");a(this,"_cancelFuture");a(this,"futureId");Object.assign(this,t),this.logger=s.logger,this.id=e,this.futureId=t.id,this.namespace=t.namespace||"kos",this._cancelFuture=Ea,_o(()=>this.status===Ve.Success||this.status===Ve.Fail,()=>{lo.info(`Future ${this.id} has completed with status ${this.status}`),Oe(this)})}async load(){lo.debug(`loading Future ${this.id}`)}unload(){lo.info(`unloading Future ${this.id}`)}async cancelFuture(){const e=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await _o(()=>this.futureId!==sr),await this._cancelFuture(this.futureId,e)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var c,l;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",o=0;for(const[d,u]of Object.entries(t))if(Math.abs(e)>=u){s=d,o=Math.round(e/u);break}const n=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(o,s);return n.length===3?`${((c=n[1])==null?void 0:c.value)??0} ${((l=n[2])==null?void 0:l.value)??""}`:"0 seconds"}handleFutureUpdated(e){this.logger.debug(`Future ${this.id} updated. future: ${e.id} endState: ${e.endState} progress: ${e.progress} remainingTimeMs: ${e.remainingTimeMs}`),ur(e,this)}};Ta([R({topic:`kos.future/${hs}`})],ys.prototype,"handleFutureUpdated",1);ys=Ta([O(st.type)],ys);const $a=ys,Oa=Jo();var ug=Object.defineProperty,hg=Object.getOwnPropertyDescriptor,Da=(e,t,s,o)=>{for(var r=o>1?void 0:o?hg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&ug(t,s,r),r};const Sa="browser-router-model",gg="kos.http.request",fg="kos.http.response";let bs=class{constructor(e,t,s){a(this,"_id");a(this,"logger");a(this,"router");this._id=e,this.logger=s.logger,this.router=new oa}get id(){return this._id}async handleRequest(e,t){const s=t.headers["src-addr"],o=t.headers["dst-addr"],r=t.headers.url,n=t.headers.method,i=t.headers["request-id"],c={id:i,method:n,path:r,body:e};let l=200;const d={send:u=>{this.logger.debug(`sending response to ${o}`),this.logger.debug(u),Pi({msg:u,options:{responseId:i,destinationAddress:s,type:fg,sourceAddress:o,status:l}})},status:function(u){return l=u,this}};if(c.path==="/openapi.json"){d.send(this.router.generateOpenApiSpec());return}await this.router.handle(c,d)}use(e,t,...s){this.router.use(e,t,...s)}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};Da([R({topic:gg})],bs.prototype,"handleRequest",1);bs=Da([O(Sa)],bs);const Gs=new pe({class:bs,type:Sa}),Ca="future-container-model",be=et(Ca),Aa=e=>hr(st)(e),pg=e=>{const t=Aa(e);return be.build(be.type,{}).addFutureModel(t),t},mg=e=>be.build(be.type,{}).getFuture(String(e)),De={buildFutureModel:Aa,initiateFuture:pg,getFuture:mg};var yg=Object.defineProperty,bg=Object.getOwnPropertyDescriptor,gr=(e,t,s,o)=>{for(var r=o>1?void 0:o?bg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&yg(t,s,r),r};const es=f.getLogger(be.type);let Lt=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_deleteFuture");a(this,"_addFuture");a(this,"_futures");a(this,"createModel");a(this,"deleteModel");const{deleteFuture:o=Ma,addFuture:r=_a}=t;this.logger=s.logger,this._deleteFuture=o,this._addFuture=r,this.id=e,this._futures=new de,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){es.error("error deleting a Future"),es.error(t)}}async createFuture(e){try{const t=await this._addFuture(e),s=t==null?void 0:t.data;if(s){const o=hr(st)(s);return this.addFutureModel(o),o}}catch(t){throw es.error("error creating a Future"),es.error(t),t}}handleFutureUpdated(e,t){const s=De.buildFutureModel(e);this.addFutureModel(s);const o=`kos.future/${e.tracker||e.id}`;this.logger.debug(`publishing future update to ${o}`),F(o,t.body,t.headers)}};gr([ie],Lt.prototype,"_futures",2);gr([R({topic:"kos.future"})],Lt.prototype,"handleFutureUpdated",1);Lt=gr([O(be.type)],Lt);const Ra=Lt,{URL:Yt}=q(),{getOne:vg,postModel:wg,deleteModel:La}=Y.build({basePath:`${Yt}/api/keyVal`}),Eo=f.createLogger({name:"key-value-service",group:"Services"}),Pa=async(e,t)=>{await La({urlOverride:`${Yt}/api/keyVal/${e}/${t}`,id:t})},ka=async(e,t,s)=>{const o=await wg({urlOverride:`${Yt}/api/keyVal/${e}/${t}`,model:s.toString()});if((o==null?void 0:o.status)!==200)throw Eo.error("Failed to update studio-state data",o),new Error(`Failed to update studio-state data for namespace ${e}`);return o.data},xa=async(e="studio")=>{Eo.debug("sending GET for studio-state");const t=await vg({urlOverride:`${Yt}/api/keyVal/${e}`});if((t==null?void 0:t.status)!==200)throw Eo.error("Failed to retrieve studio-state data",t),new Error(`Failed to retrieve studio-state data for namespace ${e}`);return t.data},Mg=async e=>{await La({urlOverride:`${Yt}/api/keyVal/${e}}`,id:""})},_g=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Pa,deleteKeyValueNamespace:Mg,getKeyValue:xa,updateKeyValue:ka},Symbol.toStringTag,{value:"Module"}));var Eg=Object.defineProperty,Ig=Object.getOwnPropertyDescriptor,fr=(e,t,s,o)=>{for(var r=o>1?void 0:o?Ig(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Eg(t,s,r),r};const Fa="key-value-model";let Pt=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"namespace");a(this,"data");this.id=e,this.logger=s.logger,this.data=ye(),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 ka(this.namespace,e,t),this.data[e]=t):(await Pa(this.namespace,e),this.data[e]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const e=await xa(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)}};fr([R({topic:"/keyVal/set"})],Pt.prototype,"handleStateUpdate",1);fr([R({topic:"/keyVal/remove"})],Pt.prototype,"handleStateDelete",1);Pt=fr([O(Fa)],Pt);const pr=new ae({class:Pt,type:Fa}),{URL:zt}=q(),{postModel:mr,getOne:Tg}=Y.build({basePath:`${zt}/api/kos-time`});f.createLogger({name:"kos-time-service",group:"Services"});const Na=async e=>{const t=await mr({model:e,urlOverride:`${zt}/api/kos/time/time`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},Ua=async e=>{const t=await mr({model:e,urlOverride:`${zt}/api/kos/time/date`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},ja=async e=>{const t=await mr({model:{},urlOverride:`${zt}/api/kos/time/timezone?tz=${e}`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data},Ba=async()=>{const e=await Tg({urlOverride:`${zt}/api/kos/time/timezone`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data.timeZone},$g=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:Ba,setDate:Ua,setTime:Na,setTimezone:ja},Symbol.toStringTag,{value:"Module"}));var Og=Object.defineProperty,Dg=Object.getOwnPropertyDescriptor,Vs=(e,t,s,o)=>{for(var r=o>1?void 0:o?Dg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Og(t,s,r),r};const lt="kos-time-model",Sg="/kos/time/time",Cg="/kos/time/day",Ag="/kos/time/timezone";let He=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"timezone");this.id=e,this.logger=s.logger,this.timezone=""}async updateSystemTime(e){await Na(e)}async updateSystemDate(e){await Ua(e)}async updateSystemTimezone(e){await ja(e)}handleTimeChange(){F(Ot.TIME_CHANGE,{})}handleDayChange(){F(Ot.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),F(Ot.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const e=await Ba();this.setTimezone(e)}setTimezone(e){this.timezone=e}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};Vs([R({topic:Sg,websocket:!0})],He.prototype,"handleTimeChange",1);Vs([R({topic:Cg,websocket:!0})],He.prototype,"handleDayChange",1);Vs([R({topic:Ag,websocket:!0})],He.prototype,"handleTimeZoneChange",1);He=Vs([O(lt)],He);const vs={registration:{[lt]:{class:He,singleton:!0}},type:lt,predicate:te(lt),factory:H.Singleton.create(lt)};var Rg=Object.defineProperty,Lg=Object.getOwnPropertyDescriptor,Ka=(e,t,s,o)=>{for(var r=o>1?void 0:o?Lg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Rg(t,s,r),r};const Ga="log-block-container-model";let ws=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new de({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}`)}};Ka([ie],ws.prototype,"_models",2);ws=Ka([O(Ga)],ws);const Le=Jo(),Pg=f.createLogger({name:"log-stream-container-service",group:"Services"}),Va=()=>{var o;const e=ee(),s=(e==null?void 0:e.connId)||((o=window==null?void 0:window.kosBridge)==null?void 0:o.call(window,"connId"));return f.error(`getKosConnectionId: ${s}`),s},ot=Va(),kg="/api/kos/logs/node/{nodeId}/streams",Ha=async()=>(Pg.debug("sending GET for log-stream-container"),await Le.get(kg,{path:{nodeId:"primary"}},{destinationAddress:ot})),Ya=async(e,t="primary")=>{await Le.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:t,stream:e}},void 0,{destinationAddress:ot})},za=async e=>{await Le.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:e}},void 0,{destinationAddress:ot})},xg=async()=>{await Le.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:ot})},qa=async e=>await Le.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:e}},{destinationAddress:ot}),Wa=async(e,t)=>await Le.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:e,blockId:t}},{destinationAddress:ot}),Fg=Object.freeze(Object.defineProperty({__proto__:null,createOverride:xg,getKosConnectionId:Va,getLogStreamBlock:Wa,getLogStreamBlocks:qa,getLogStreams:Ha,subscribeToLogStream:Ya,unsubscribeFromLogStream:za},Symbol.toStringTag,{value:"Module"}));var Ng=Object.defineProperty,Ug=Object.getOwnPropertyDescriptor,jg=(e,t,s,o)=>{for(var r=o>1?void 0:o?Ug(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Ng(t,s,r),r};const Za="log-block-model";let Io=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"nodeId");a(this,"stream");a(this,"blockNum");a(this,"startLineNum");a(this,"endLineNum");a(this,"startTime");a(this,"endTime");a(this,"lineCount");a(this,"lines");a(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 Wa(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}`)}};Io=jg([O(Za)],Io);const kt=new ae({class:Io,type:Za}),Hs=new ae({class:ws,type:Ga});Hs.addRelatedModel(kt);var Bg=Object.defineProperty,Kg=Object.getOwnPropertyDescriptor,Ja=(e,t,s,o)=>{for(var r=o>1?void 0:o?Kg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Bg(t,s,r),r};const Qa="log-stream-model";let Ms=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"nodeId");a(this,"_blocks");a(this,"name");a(this,"currentBlockId");a(this,"isResetting");a(this,"generatorInstance");a(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=Hs.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 o;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=kt.instance(`${e.stream}-block-${e.blockNum}`).options(s).build(),this._blocks.addModel(t)),t&&t.updateModel(s),(!this.currentBlock||e.blockNum>=((o=this.currentBlock)==null?void 0:o.blockNum))&&(this.currentBlockId=`${e.stream}-block-${e.blockNum}`)}addBlock(e){var s;const t=kt.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 Ya(this.name)}async unsubscribe(){await za(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 qa(this.name);if(e){this.logger.error(`Error loading log stream: ${e}`);return}if(t)for(const o of t)this.addBlock(o);const s=this._blocks.data[this._blocks.data.length-1];if(s&&await s.syncLines(),this._blocks.data.length>1){const o=this._blocks.data[this._blocks.data.length-2];o&&await o.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,o=this.currentBlockId;const r=na(()=>{const n=this.currentBlock;return n?{blockId:this.currentBlockId,lineCount:n.lines.length}:null},n=>{const i=this.currentBlock;if(i)if(o!==(n==null?void 0:n.blockId))o=n==null?void 0:n.blockId,s=0,e.push(...i.lines);else{const c=i.lines.slice(s);e.push(...c),s+=c.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{r()}}};Ja([ie],Ms.prototype,"_blocks",2);Ms=Ja([O(Qa)],Ms);const Dt=new ae({class:Ms,type:Qa});var Gg=Object.defineProperty,Vg=Object.getOwnPropertyDescriptor,Pe=(e,t,s,o)=>{for(var r=o>1?void 0:o?Vg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Gg(t,s,r),r};const Xa="log-stream-container-model",Hg="/kos/logs/subscription/addBlock/*",Yg="/kos/logs/subscription/updateBlock/*",zg="/kos/logs/subscription/removeBlock/*",qg="/kos/logs/subscription/lines/*",ec="/kos/logs/streams/add/*";let he=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"selectedStream");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new de({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: ${ec}`);const t=e.stream,s=Dt.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,o=this.models.getModel(s);o&&o.addBlock(e)}handleRemoveBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,o=this.models.getModel(s);o&&o.removeBlock(e.blockNum)}handleUpdateBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,o=this.models.getModel(s);o&&o.updateBlock(e)}handleLogLine(e,t){var r;this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,o=this.models.getModel(s);o&&((r=o.currentBlock)==null||r.addLines(e.lines))}async init(){this.logger.debug(`initializing log-stream-container container ${this.id}`)}async subscribeToLogStream(e){const t=Dt.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 Ha();if(e){this.logger.error(`Error loading log-streams: ${e}`);return}t&&t.forEach(s=>{const o=Dt.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(o)})}};Pe([ie],he.prototype,"_models",2);Pe([R({topic:[ec],websocket:!0})],he.prototype,"handleStreamAdded",1);Pe([R({topic:[Hg],websocket:!0})],he.prototype,"handleAddBlock",1);Pe([R({topic:[zg],websocket:!0})],he.prototype,"handleRemoveBlock",1);Pe([R({topic:[Yg],websocket:!0})],he.prototype,"handleUpdateBlock",1);Pe([R({topic:[qg],websocket:!0})],he.prototype,"handleLogLine",1);he=Pe([O(Xa)],he);const qt=new pe({class:he,type:Xa});qt.addRelatedModel(Dt);qt.addRelatedModel(Hs);qt.addRelatedModel(kt);const Wg=e=>e.rank!==void 0,Zg=e=>e.visibleRole!==void 0,Jg=e=>e.color!==void 0,Qg=e=>{const t=e.info;return Wg(t)?t.rank:0},Xg=e=>{const t=e.info;return Jg(t)?t.color:"orange"},ef=e=>{const t=e.info;return Zg(t)?t.visibleRole:"TECHNICIAN"},{URL:yr}=q(),{getAll:tf,postModel:tc}=Y.build({basePath:`${yr}/api/kos/troubles`}),sc=async()=>await tf({}),oc=async(e,t)=>{try{const s=await tc({model:{},urlOverride:`${yr}/api/kos/troubles/resolve/${e}`,tracker:t});return s!=null&&s.data&&De.initiateFuture(s.data),s.data}catch{const o={id:t||"",endState:Ve.Fail,tracker:t,reason:"Failed to resolve trouble"};return De.initiateFuture(o),o}},sf=async(e,t)=>{try{const s=await tc({model:e,urlOverride:`${yr}/api/kos/troubles/resolve/`,tracker:t});return s!=null&&s.data&&De.initiateFuture(s.data),s.data}catch{const o={id:t||"",endState:Ve.Fail,tracker:t,reason:"Failed to resolve troubles"};return De.initiateFuture(o),o}},of=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:sf,getTroubles:sc,resolveTrouble:oc},Symbol.toStringTag,{value:"Module"})),_s="troubleDataMapper",ts=new Map;zo(_s,{register:(e,t)=>{var s;ts.has(e)||ts.set(e,[]),(s=ts.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=ts.get(e);if(!s)return{...t.data};const o=s.map(i=>i(t));return(await Promise.allSettled(o)).reduce((i,c)=>(c.status==="fulfilled"?i={...i,...c.value}:f.info(`Trouble mapper ${e} failed: ${c.reason}`),i),{...t.data})}});const Wt="troubleMapper",ss=new Map;zo(Wt,{register:(e,t)=>{var s;ss.has(e)||ss.set(e,[]),(s=ss.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=ss.get(e);if(!s)return[];const o=s.map(i=>i(t)),n=(await Promise.allSettled(o)).map(i=>i.status==="fulfilled"?i.value:(f.info(`Trouble mapper ${e} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});A[Wt].register("nozzle",async e=>[e.data.nozzlePath]);A[Wt].register("path",async e=>[e.data.path]);const rf=async e=>{const t=new Set,s=e.ifaces,o=s==null?void 0:s.map(n=>A[Wt].execute(n,e));return(await Promise.allSettled(o)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>t.add(i))}),Array.from(t)},rc=async e=>{const t=e.ifaces,s=t==null?void 0:t.map(i=>A[_s].execute(i,e)),o=A[_s].execute(e.type,e);s.push(o);const n=(await Promise.allSettled(s)).reduce((i,c)=>(c.status==="fulfilled"&&(i={...i,...c.value}),i),{});return{...e.data,...n}};class nf{constructor(){a(this,"type","ResolvableTrouble");a(this,"title","Resolvable Trouble");a(this,"subtitle","Trouble")}}class af{constructor(){a(this,"type","BlockPumpTrouble");a(this,"title","Block Pump Trouble");a(this,"subtitle","Trouble")}}class Fe{static getHandler(t){switch(t){case"ResolvableTrouble":return new nf;case"BlockPumpTrouble":return new af;default:return}}}var cf=Object.defineProperty,lf=Object.getOwnPropertyDescriptor,nc=(e,t,s,o)=>{for(var r=o>1?void 0:o?lf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&cf(t,s,r),r};const dt="trouble-model";function os(e){return typeof e.shouldDefer=="boolean"}let Es=class{constructor(e,{resolvable:t,tags:s,info:o,id:r,clientData:n,rank:i,ifaces:c,type:l,group:d,createTime:u,role:h,color:p,...w},b){a(this,"id");a(this,"logger");a(this,"_troubleId");a(this,"_resolvable");a(this,"type");a(this,"futureHandler");a(this,"ifaces");a(this,"clientData");a(this,"info");a(this,"role");a(this,"color");a(this,"tags");a(this,"data");a(this,"rank");a(this,"group");a(this,"createTime");a(this,"_mapped",{});this.id=e,this.logger=b.logger,this.type=l,this._troubleId=r,this._resolvable=!!t,this.ifaces=c,this.rank=i,this.role=h,this.color=p,this.tags=s,this.info=o,this.group=d,this.createTime=u,this.clientData=n,this.data={},Object.assign(this.data,w),this.futureHandler=new lr(this)}getTitleWithContext(e){var s,o;const t=e?(o=(s=Fe.getHandler(this.type))==null?void 0:s.context)==null?void 0:o[e]:Fe.getHandler(this.type);return(t==null?void 0:t.title)||"Trouble"}getSubtitleWithContext(e){var s,o;const t=e?(o=(s=Fe.getHandler(this.type))==null?void 0:s.context)==null?void 0:o[e]:Fe.getHandler(this.type);return(t==null?void 0:t.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var e;return((e=Fe.getHandler(this.type))==null?void 0:e.title)||"Trouble"}get subtitle(){var e;return((e=Fe.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 rc(this)}get deferredCompanion(){const e=Mo(this.id,t=>os(t));if(e&&os(e.modelData))return e.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const e=Mo(this.id,t=>os(t));return e&&os(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 oc(this._troubleId,e)}};nc([Lr()],Es.prototype,"resolve",1);Es=nc([O(dt)],Es);const xt={registration:{[dt]:{class:Es,singleton:!1}},type:dt,predicate:te(dt),factory:H.Factory.create(dt)};var df=Object.defineProperty,uf=Object.getOwnPropertyDescriptor,Ys=(e,t,s,o)=>{for(var r=o>1?void 0:o?uf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&df(t,s,r),r};const ln=f.createLogger({name:"trouble-container-model"});function dn(e){return A.propertyMapper.hasMapper(re.TroubleRank)?A.propertyMapper.executeMapper(re.TroubleRank,e):Qg(e)}function un(e){return(A.propertyMapper.hasMapper(re.TroubleColor)?A.propertyMapper.executeMapper(re.TroubleColor,e):Xg(e)).toLowerCase()}function hn(e){return(A.propertyMapper.hasMapper(re.TroubleRole)?A.propertyMapper.executeMapper(re.TroubleRole,e):ef(e)).toLowerCase()}const hf="trouble-container-model";class X{}a(X,"INDEX_TROUBLES_BY_IFACE","byIface"),a(X,"INDEX_TROUBLES_BY_TYPE","byType"),a(X,"INDEX_TROUBLES_BY_GROUP","byGroup"),a(X,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),a(X,"SORT_KEY_RANK","rank"),a(X,"TROUBLES_DEFERRED","true");let Ye=class{constructor(e){a(this,"id");a(this,"troubles");this.id=e,this.troubles=new de({indexMap:{[X.INDEX_TROUBLES_BY_IFACE]:rf,[X.INDEX_TROUBLES_BY_TYPE]:"type",[X.INDEX_TROUBLES_BY_GROUP]:"group",[X.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:X.SORT_KEY_RANK,parentId:e})}async load(){ln.debug("loading trouble container");const e=await sc();try{e==null||e.data.forEach(t=>{const s={...t,rank:dn(t),color:un(t),role:hn(t),id:String(t.id)},o=xt.factory(`trouble-${t.id}`)(s);this.troubles.addModel(o)})}catch(t){throw ln.error(t),t}}handleTroubleRemoved(e){const t=`trouble-${e}`,s=this.troubles.getModel(t);this.troubles.removeModel(t),s&&Oe(s)}handleTroubleAdded(e){const t={...e,rank:dn(e),color:un(e),role:hn(e),id:String(e.id)};if(t.role==="NONE")return;const s=xt.factory(`trouble-${e.id}`)(t);this.troubles.addModel(s)}};Ys([ie],Ye.prototype,"troubles",2);Ys([R({topic:"/kos/trouble/remove",websocket:!0,lifecycle:x.INIT})],Ye.prototype,"handleTroubleRemoved",1);Ys([R({topic:"/kos/trouble/add",websocket:!0})],Ye.prototype,"handleTroubleAdded",1);Ye=Ys([O(hf)],Ye);const rs="trouble-container-model",ze={registration:{[rs]:{class:Ye,singleton:!0}},type:rs,predicate:te(rs),factory:H.Singleton.create(rs)},{URL:ic}=q(),{getAll:gf}=Y.build({basePath:`${ic}/api/kos/ota`}),gn=f.createLogger({name:"ota-service",group:"Services"}),ff=async()=>{gn.debug("sending GET request to /api/kos/ota/artifacts");const e=await gf({urlOverride:`${ic}/api/kos/ota/artifacts`});return gn.debug("getArtifacts - response:",e),e==null?void 0:e.data};var pf=Object.defineProperty,mf=Object.getOwnPropertyDescriptor,zs=(e,t,s,o)=>{for(var r=o>1?void 0:o?mf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&pf(t,s,r),r};const ac="ota-model",yf=e=>{let t=null;for(const s in e){const o=e[s],r=o.lastUpdateTime;(!t||t.lastUpdateTime<r)&&(t=o)}return t},uo=e=>{const t=e.artifactInfo,s=yf(e.requests),o=(t==null?void 0:t.identifier)||(s==null?void 0:s.kabId);if(!o)return;let r;switch(e.status){case"INSTALLED":r="ready";break;case"INVALID":r="error";break;case"MISSING":r=((s==null?void 0:s.currentSize)||0)>0?"downloading":"idle";break;case"STAGED":r="pending"}const n=t===void 0;return{id:o,manifest:n,label:t==null?void 0:t.version,name:t==null?void 0:t.name,status:r,error:r==="error"?s==null?void 0:s.lastErrorReason:void 0,errorCount:r==="error"?s==null?void 0:s.errorCount:0,progress:r==="downloading"&&s&&!n?s.currentSize/(t==null?void 0:t.size)*100:void 0,size:t==null?void 0:t.size}};let qe=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"data",new ta);a(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 ff();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)}}};zs([Ce({modelType:ze.type})],qe.prototype,"troubleContainer",2);zs([R({topic:"/kos/ota/artifacts/all",websocket:!0})],qe.prototype,"handleAllArtifacts",1);zs([R({topic:"/kos/ota/artifacts/changed",websocket:!0})],qe.prototype,"handleChangedArtifacts",1);qe=zs([O(ac)],qe);const Is=new pe({class:qe,type:ac}),fn=f.createLogger({name:"software-info-service",group:"Services"}),cc=async()=>{fn.debug("sending GET for software-info");const[e,t]=await Oa.get("/api/kos/manifest/info");if(!t)throw fn.error("Failed to fetch software-info",e),new ce("Failed to fetch software-info");return t},bf=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:cc},Symbol.toStringTag,{value:"Module"}));var vf=Object.defineProperty,wf=Object.getOwnPropertyDescriptor,Mf=(e,t,s,o)=>{for(var r=o>1?void 0:o?wf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&vf(t,s,r),r};const ut="software-info-model";let To=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(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,o)=>(s[o[t]]=[...s[o[t]]||[],o],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const e=await cc(),t=(e==null?void 0:e.nodes)||{};z(()=>{const o=Object.keys(t).map(r=>t[r][0]).map(r=>({nodeName:r.node,group:this.groupBy(r.artifacts,"group")}));this.nodes=o})}catch(e){e instanceof ce&&this.logger.error("Failed to fetch software-info",e)}}};To=Mf([O(ut)],To);const Ts={registration:{[ut]:{class:To,singleton:!1}},type:ut,predicate:te(ut),factory:H.Factory.create(ut)},{URL:lc}=q(),{getOne:_f}=Y.build({basePath:`${lc}/api/kos/state`}),Ef=f.createLogger({name:"state-bean-service",group:"Services"}),dc=async({path:e})=>(Ef.debug("sending GET for state-bean"),await _f({urlOverride:`${lc}/api/kos/state/${e}`})),If=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:dc},Symbol.toStringTag,{value:"Module"}));var Tf=Object.defineProperty,$f=Object.getOwnPropertyDescriptor,uc=(e,t,s,o)=>{for(var r=o>1?void 0:o?$f(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Tf(t,s,r),r};const ht="state-bean-model",Of=Se("path");let $s=class{constructor(e,t,s){a(this,"id");a(this,"path");a(this,"props");a(this,"logger");this.id=e,this.logger=s.logger,this.props=tr.map(new Map),mo(t,this)}updateModel(e){mo(e,this)}handleConfigBeanUpdated(e){Object.entries(e).forEach(([t,s])=>{let o=s;typeof o=="string"&&rr(o)&&(o=o.toLowerCase()=="true"),typeof o=="string"&&js(o)&&(o=Number(o)),this.props.set(t,o)})}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 dc({path:this.path});e!=null&&e.data&&this.updateProps(e.data)}};uc([R({topic:`/kos/state/${Of}`,websocket:!0})],$s.prototype,"handleConfigBeanUpdated",1);$s=uc([O(ht)],$s);const Ft={registration:{[ht]:{class:$s,singleton:!1}},type:ht,predicate:te(ht),factory:H.Factory.create(ht)};var Df=Object.defineProperty,Sf=Object.getOwnPropertyDescriptor,hc=(e,t,s,o)=>{for(var r=o>1?void 0:o?Sf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Df(t,s,r),r};const gt="state-prop-model",pn=Se("path");let Os=class{constructor(e,t,s){a(this,"id");a(this,"path");a(this,"attribute");a(this,"logger");a(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())??""}};hc([Ce({modelType:Ft.type,id:`state-bean-${pn}`,options:{path:pn}})],Os.prototype,"stateBean",2);Os=hc([O(gt)],Os);const br={registration:{[gt]:{class:Os,singleton:!1}},type:gt,predicate:te(gt),factory:H.Factory.create(gt)},{URL:Cf}=q(),{getAll:Af}=Y.build({basePath:`${Cf}/api/state-prop`}),Rf=f.createLogger({name:"state-prop-service",group:"Services"}),Lf=async()=>(Rf.debug("sending GET for state-prop"),await Af({})),Pf=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:Lf},Symbol.toStringTag,{value:"Module"})),{URL:vr}=q(),{getOne:gc}=Y.build({basePath:`${vr}/api/translation`}),St=f.createLogger({name:"translation-service",group:"Services"}),kf=()=>{const e=window.location.origin,t=ee();return(t==null?void 0:t.host)||e},fc=async(e,t)=>{St.debug("sending GET for translation");const s=t??kf();try{const o=await fetch(`${s}${e}`);return o.status!==200?(St.warn(`Failed to fetch translations at ${e}: ${o.status}`),{}):await o.json()}catch(o){throw St.error("Error fetching translations",o),o}},xf=async()=>{St.debug("getting localization descriptor");const e=await gc({urlOverride:`${vr}/api/system/kos/localization`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get tool localization descriptor ${e==null?void 0:e.status}`);return e.data},pc=e=>async()=>{St.debug("getting kos localization descriptor");const t=await gc({urlOverride:`${vr}/api/kos/localization/contexts`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get tool localization descriptor ${t==null?void 0:t.status}`);return t.data[e]},mc="langResolver";var Ff=Object.defineProperty,Nf=Object.getOwnPropertyDescriptor,Uf=(e,t,s,o)=>{for(var r=o>1?void 0:o?Nf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Ff(t,s,r),r};const ft="translation-model";function jf(e){const t=typeof e=="string",s=t?!1:!!(e!=null&&e.data)&&typeof(e==null?void 0:e.data)!="string",o=t?e:e==null?void 0:e.defaultValue,r=t||e==null?void 0:e.context,n=t?void 0:s?e==null?void 0:e.data:e;return{isBasicOptions:t,defaultValue:o,context:r,data:n}}function yc(e,t=""){return Object.keys(e).reduce((s,o)=>{const r=t?`${t}.${o}`:o;if(typeof e[o]=="object"&&e[o]!==null){const n=yc(e[o],r);return{...s,...n}}else return{...s,[r]:e[o]}},{})}function bc(e,t){const s={...e};for(const o in t)Object.prototype.hasOwnProperty.call(t,o)&&(typeof t[o]=="object"&&t[o]!==null&&typeof e[o]=="object"&&e[o]!==null?s[o]=bc(e[o],t[o]):s[o]=t[o]);return s}const $o=(e,t)=>{const s=/__(.*?)__/g,o=e.replace(s,(r,n)=>Object.prototype.hasOwnProperty.call(t||{},n.trim())?t==null?void 0:t[n.trim()]:r);return o===e?o:s.test(o)?$o(o,t):o},ns=(e,t,s)=>{const o=/{{(.*?)}}/g,n=$o(e,t).replace(o,(c,l)=>Object.prototype.hasOwnProperty.call(s||{},l.trim())?s==null?void 0:s[l.trim()]:c);return $o(n,t)},mn=(e,t)=>{if(t.includes(":")){const[s,o]=t.split(":");return{namespace:s,key:o}}else return{namespace:e,key:t}};let Oo=class{constructor(e,t,s){a(this,"id");a(this,"namespace");a(this,"descriptor");a(this,"defaultLocale");a(this,"currentLocale");a(this,"bundleResolver");a(this,"data");a(this,"logger");a(this,"resolver");a(this,"disposer");a(this,"context");a(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(mc),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(o=>{if(this.bundleResolver){const r=k.getContext(this.id);return this.bundleResolver(this.namespace,o,r)}try{const r=this.resolver(this.namespace,o);return fc(r,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(t);z(()=>{const o=s.reduce((r,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${e[i]}`,n.value),n.value&&(r=bc(r,n.value))):this.logger.error(`failed to load translation ${this.id} for ${e[i]}`),r),{});this.data=yc(o)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(e){const{namespace:t,key:s}=mn(this.namespace,e);if(t!==this.namespace){const o=this.context.getModel(t);return o?o.exists(s):!1}return!!this.data[s]}resolveKey(e,t){if(!e)return this.logger.debug("key is empty"),"";const{defaultValue:s,context:o,data:r}=jf(t),{namespace:n,key:i}=mn(this.namespace,e),c=`${i}_${o}`;if(n!==this.namespace){const l=this.context.getModel(n);return l?l.resolveKey(i,t):i}if(o&&this.data[c]){const l=this.data[c];return Array.isArray(l)?l.map(d=>ns(d,this.data,r)):ns(this.data[c],this.data,r)}if(this.data[i]){const l=this.data[c];return Array.isArray(l)?l.map(d=>ns(d,this.data,r)):ns(this.data[i],this.data,r)}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=v.reaction(()=>this.currentLocale,(e,t)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${t} to ${e}`),this.loadTranslations()})}};Oo=Uf([Us(),O(ft)],Oo);const Ds={registration:{[ft]:{class:Oo,singleton:!1}},type:ft,predicate:te(ft),factory:H.Factory.create(ft)};var Bf=Object.defineProperty,Kf=Object.getOwnPropertyDescriptor,vc=(e,t,s,o)=>{for(var r=o>1?void 0:o?Kf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Bf(t,s,r),r};const pt="translation-container-model",Gf=(e,t="/")=>e.join(t).replace(new RegExp(t+"{1,}","g"),t);function Vf(e,t){const s=this.descriptor.namespaces[e];if(!s)throw new Error(`namespace ${e} not found in descriptor`);const o=s.basePath,r=s.locales[t].file;return Gf([o,r])}let Ss=class{constructor(e,t,s){a(this,"id");a(this,"lang");a(this,"rootUrl");a(this,"descriptor");a(this,"_defaultNamespace");a(this,"resolver");a(this,"logger");a(this,"descriptorUrl");a(this,"namespaces",[]);a(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||Vf.bind(this),s.kosContext.set(mc,this.resolver),this.logger=s.logger,this._models=new de({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(){this._models.clear(),await ji(this);for(const e of this.namespaces){const t=this.resolveNamespace(e);await J(t)}}resolveNamespace(e){var s;if((s=this.descriptor.namespaces)==null?void 0:s[e]){const o=Object.keys(this.descriptor.namespaces[e].locales)[0],r=this.descriptor.namespaces[e].locales[o].defaultLocale,n=Ds.factory(`translation-${e}`)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:r,descriptor:this.descriptor.namespaces[e].locales,resolver:this.resolver});return this.addModel(n),this.namespaces.includes(e)||z(()=>{this.namespaces.push(e)}),n}else{this.logger.warn(`namespace ${e} not found in descriptor`);const o=Ds.factory(`translation-${e}`)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(o),o}}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}`)}};vc([ie],Ss.prototype,"_models",2);Ss=vc([O(pt)],Ss);const ge={registration:{[pt]:{class:Ss,singleton:!0}},type:pt,predicate:te(pt),factory:H.Singleton.create(pt)},Hf={set(e,t){const s=k.getContext(ge.type);s&&s.set(e,t)},get(e){const t=k.getContext(ge.type);return t==null?void 0:t.get(e)}},wc={async init(e){const t=ge.factory(e);return await J(t),{translations:t}}},Yf=(e,t)=>{const s=t.type;return e[s]||(e[s]=[]),e[s].push(t),e},Mc="kos-ws-event",wr=et(Mc);var zf=Object.defineProperty,qf=Object.getOwnPropertyDescriptor,Mr=(e,t,s,o)=>{for(var r=o>1?void 0:o?qf(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&zf(t,s,r),r};const Wf=({headers:e,body:t})=>Object.entries(e).map(([o,r])=>`${o}:${r}`).join("\\n")+"\\n\\n"+t;exports.WsEventModel=class{constructor(t){a(this,"id");a(this,"events");a(this,"_topicMap");this.id=t,this.events=v.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){f.debug("kos event received");const{body:o,headers:r}=t.body,n=r["request-id"]||r["response-id"],i=r["request-id"]||r["response-id"]||r.topic||r.type;if(i){let c=i;if(n)c=`${c}-${s?"send":"receive"}`;else{const d=this._topicMap.get(i)||0;c=`${c}-${d+1}`,this._topicMap.set(i,d+1)}const l={msgId:c,content:o,headers:r,timestamp:Date.now(),raw:Wf({headers:r,body:o}),direction:s?"send":"receive",mocked:!!r.mocked};this.events.set(c,l),f.debug(`logged ${this.events.size} events`)}}};Mr([R({topic:[Gt.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);Mr([R({topic:[Gt.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=Mr([O(wr.type)],exports.WsEventModel);const yn=ee(),Zf=yn.debug==="true"||yn.debug===!0,Jf="/api/system/canvas",_c=async(e,t)=>{const s=t||Jf,o=`${exports.BASE_URL}${s}`;await exports.kosFetch(o,{method:"POST",headers:{hide:Zf?"true":"false"},body:e})},Qf=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:_c},Symbol.toStringTag,{value:"Module"})),Xf=(e,t,s)=>e>>5<<5|t>>5<<2|s>>6;function ep(e,t,s){if(t==="base64"){const o=s?e.filter((r,n)=>n%4!==3):Array.from(e);return btoa(String.fromCharCode(...o))}else{const o=[];for(let r=0;r<e.length;r+=4)o.push(Xf(e[r],e[r+1],e[r+2]));return String.fromCharCode(...o)}}var tp=Object.defineProperty,sp=Object.getOwnPropertyDescriptor,Ec=(e,t,s,o)=>{for(var r=o>1?void 0:o?sp(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&tp(t,s,r),r};const Ic="canvas-renderer-model";function bn(e){return typeof e.onDone=="function"}let Cs=class{constructor(e,t,s){a(this,"id");a(this,"router");a(this,"logger");a(this,"_renderer",null);a(this,"isStreaming",!1);a(this,"renderLoopId",null);a(this,"sendIntervalId",null);a(this,"timeoutId",null);a(this,"apiPath");a(this,"endpointName");a(this,"width",50);a(this,"height",30);a(this,"fps",10);a(this,"durationMs",null);a(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()}sendDataFrame(e,t){_c(e,t)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{this.stopStreaming()});return}}handleFrame(e){var s;const t=ep(e,"base64",!0);this.sendDataFrame(t,this.apiPath),(s=this._onFrame)==null||s.call(this,t)}stopStreaming(){var e,t;this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(t=(e=this._renderer)==null?void 0:e.pause)==null||t.call(e)}isOneShotDone(){var e,t;return bn(this._renderer)&&((t=(e=this._renderer).isOneShot)==null?void 0:t.call(e))===!0&&this._renderer.isOneShotDone}startStreaming(){var e,t,s,o;{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 r=bn(this._renderer);this._renderer.renderFrame(this.width,this.height);const n=(o=(s=this._renderer).readPixels)==null?void 0:o.call(s,this.width,this.height);if(n&&this._onFrame&&this.handleFrame(n),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming()});return}const i=()=>{var c;(c=this._renderer)==null||c.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var l,d;const c=(d=(l=this._renderer)==null?void 0:l.readPixels)==null?void 0:d.call(l,this.width,this.height);c&&this._onFrame&&(this.handleFrame(c),this.checkStreaming())},1e3/this.fps),!r&&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.stopStreaming(),t.send({status:"OK"})}),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/start`,async(e,t)=>{this.startStreaming(),t.send({status:"OK"})})}};Ec([Ce({modelType:Gs.type})],Cs.prototype,"router",2);Cs=Ec([O(Ic)],Cs);const _r=new ae({class:Cs,type:Ic});class op{constructor(t){a(this,"video");a(this,"canvas");a(this,"ctx");a(this,"lastUpdate",0);a(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 Tc{constructor(){a(this,"canvas");a(this,"ctx");a(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 $c(e){class t extends e{constructor(){super(...arguments);a(this,"doneCallback",null);a(this,"oneShotDone",!1)}isOneShot(){return!0}onDone(r){this.doneCallback=r}signalDoneIfNeeded(){var r;this.oneShotDone||((r=this.doneCallback)==null||r.call(this),this.oneShotDone=!0)}resetOneShot(){this.doneCallback=null,this.oneShotDone=!1}get isOneShotDone(){return this.oneShotDone}}return t}const rp=$c(Tc);class np extends rp{constructor(s){super();a(this,"img");a(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,o){!this.loaded||this.isOneShotDone||(this.canvas.width=s,this.canvas.height=o,this.ctx.drawImage(this.img,0,0,s,o),this.signalDoneIfNeeded())}}const ip=$c(Tc);class vn extends ip{constructor(s=0,o=0,r=0){super();a(this,"color");this.color=`rgb(${s},${o},${r})`}setColor(s,o,r){this.color=`rgb(${s},${o},${r})`,this.resetOneShot()}reset(){this.resetOneShot()}renderFrame(s,o){this.isOneShotDone||(this.canvas.width=s,this.canvas.height=o,this.ctx.fillStyle=this.color,this.ctx.fillRect(0,0,s,o),this.signalDoneIfNeeded())}}const wn=({mode:e,data:t})=>{switch(e){case"color":{const{r:s,g:o,b:r}=t;return t?new vn(s,o,r):new vn(0,0,0)}case"image":return t?new np(t.src):null;case"video":return t?new op(t.src):null;default:throw new Error(`Unknown mode: ${e}`)}};var ap=Object.defineProperty,cp=Object.getOwnPropertyDescriptor,Er=(e,t,s,o)=>{for(var r=o>1?void 0:o?cp(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&ap(t,s,r),r};const Oc="canvas-dispatcher-model";function lp(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 Nt=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_content",new Map);a(this,"_patterns",new Map);a(this,"_endpointRenderers");a(this,"router");a(this,"pattern");a(this,"data");this.id=e,this.logger=s.logger,this._endpointRenderers=new de}addNamedEndpoint(e,t){this._endpointRenderers.getModel(e)&&this.logger.warn(`Endpoint "${e}" already exists. Overwriting.`);const s=_r.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 load(e){var s;const t=e==null?void 0:e.get(We.loader);t&&((s=t.patterns)==null||s.forEach(o=>{if(!o.id||!o.type||!o.data){this.logger.warn(`Invalid pattern data: ${JSON.stringify(o)}`);return}this.addPattern(o.id,o)})),this.router.use("POST","/api/ui/canvas/patterns",async(o,r)=>{var c,l;const n=o.body,i=Array.isArray(n)?n:[n];if(i.some(d=>!d.id||!d.type||!d.data)){(c=r.status)==null||c.call(r,400).send({error:"Invalid pattern data"});return}for(const d of i)this._patterns.has(d.id)&&this.logger.warn(`Pattern "${d.id}" already exists. Overwriting.`),this.addPattern(d.id,d);(l=r.status)==null||l.call(r,200).send({status:"OK"})}),this.router.use("POST","/api/ui/canvas/pattern/:endpoint/:pattern",async(o,r)=>{var u,h,p;const n=o.params.pattern,i=o.params.endpoint,c=this._endpointRenderers.getModel(i);if(!c){(u=r.status)==null||u.call(r,404).send({error:`Endpoint "${i}" not found`});return}if(!this._patterns.has(n)){(h=r.status)==null||h.call(r,404).send({error:`Pattern "${n}" not found`});return}const l=this._patterns.get(n),d=l.type;this.data=l.data,c.renderer=wn({mode:d,data:this.data}),c.startStreaming(),(p=r.status)==null||p.call(r,200).send({status:"OK"})}),this.router.use("POST","/api/ui/canvas/color/:endpoint/:color",async(o,r)=>{var p,w,b;const n=o.params.color,i=lp(n);if(!i){(p=r.status)==null||p.call(r,400).send({error:"Invalid color format"});return}const c=o.params.endpoint,l=this._endpointRenderers.getModel(c);if(!l){(w=r.status)==null||w.call(r,404).send({error:`Endpoint "${c}" not found`});return}const{r:d,b:u,g:h}=i;l.renderer=wn({mode:"color",data:{r:d,g:h,b:u}}),l.startStreaming(),(b=r.status)==null||b.call(r,200).send({status:"OK"})}),this.router.use("POST","/api/ui/canvas/endpoint",async(o,r)=>{var i,c;const n=o.body;if(!n.apiPath||!n.id){(i=r.status)==null||i.call(r,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(n.id,n),(c=r.status)==null||c.call(r,200).send({status:"OK"})})}};Er([ie],Nt.prototype,"_endpointRenderers",2);Er([Ce({modelType:Gs.type})],Nt.prototype,"router",2);Nt=Er([O(Oc)],Nt);const We=new pe({class:Nt,type:Oc}),{URL:Ir}=q(),{getOne:Dc}=Y.build({basePath:`${Ir}/api/device`}),As=f.createLogger({name:"device-service",group:"Services"}),Sc=async()=>{As.debug("sending GET for device serial number");try{const e=await Dc({urlOverride:`${Ir}/api/kos/device/serialNumber`});return[void 0,e==null?void 0:e.data.serialNumber]}catch(e){if(e instanceof ce)return As.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Cc=async()=>{As.debug("sending GET for device details");try{const e=await Dc({urlOverride:`${Ir}/api/kos/device`});return e?[void 0,e.data]:["unknownError",void 0]}catch(e){if(e instanceof ce)return As.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},dp=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:Cc,getSerialNumber:Sc},Symbol.toStringTag,{value:"Module"}));var up=Object.defineProperty,hp=Object.getOwnPropertyDescriptor,Ac=(e,t,s,o)=>{for(var r=o>1?void 0:o?hp(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&up(t,s,r),r};const Rc="device-model",gp="/kos/criticalData/changed",fp="/kos/criticalData/available";let Rs=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_serialNumber");a(this,"_name");a(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 Cc();if(e){this.logger.error(`Error fetching device serial number: ${e}`);return}if(t){const{name:s,nodeId:o}=t;this.updateModel({name:s,nodeId:o,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[e,t]=await Sc();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()}};Ac([R({topic:[gp,fp],websocket:!0})],Rs.prototype,"handleCriticalDataChanged",1);Rs=Ac([O(Rc)],Rs);const Ls=new pe({class:Rs,type:Rc});var pp=Object.defineProperty,mp=Object.getOwnPropertyDescriptor,yp=(e,t,s,o)=>{for(var r=o>1?void 0:o?mp(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&pp(t,s,r),r};const Lc="network-interface-model";let Do=class{constructor(e,t,s){a(this,"id");a(this,"name");a(this,"type");a(this,"nmdevicestate");a(this,"hwaddress");a(this,"mtu");a(this,"configured");a(this,"wifi");a(this,"ethernet");a(this,"ip4settings");a(this,"category");a(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}`)}};Do=yp([O(Lc)],Do);const Tr=new ae({class:Do,type:Lc}),{URL:bp}=q(),{getAll:vp}=Y.build({basePath:`${bp}/api/kos/network/interfaces`}),Mn=f.createLogger({name:"network-interface-service",group:"Services"}),Pc=async()=>{Mn.debug("sending GET for copy-logs");try{const e=await vp({});return[void 0,e==null?void 0:e.data]}catch(e){if(e instanceof ce)return Mn.error(`Error fetching log file size: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},wp=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:Pc},Symbol.toStringTag,{value:"Module"}));var Mp=Object.defineProperty,_p=Object.getOwnPropertyDescriptor,kc=(e,t,s,o)=>{for(var r=o>1?void 0:o?_p(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Mp(t,s,r),r};const xc="network-interface-container-model";let Ps=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new de({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 Pc();if(e){this.logger.error(`Error loading network interfaces: ${e}`);return}t&&t.forEach(s=>{const o=Tr.instance(s.name).forceUpdate.options(s).build();this.addModel(o)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};kc([ie],Ps.prototype,"_models",2);Ps=kc([O(xc)],Ps);const Ut=new pe({class:Ps,type:xc});Ut.addRelatedModel(Tr);const{URL:Ep}=q(),{getAll:Ip}=Y.build({basePath:`${Ep}/api/kos/storage/devices`}),_n=f.createLogger({name:"storage-device-service",group:"Services"}),Fc=async()=>{_n.debug("sending GET for storage-device");const e=await Ip({});return!(e!=null&&e.data)||e.status!==200?(_n.error("Failed to retrieve storage-device data",e),[]):e.data},Tp=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:Fc},Symbol.toStringTag,{value:"Module"}));var $p=Object.defineProperty,Op=Object.getOwnPropertyDescriptor,Dp=(e,t,s,o)=>{for(var r=o>1?void 0:o?Op(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&$p(t,s,r),r};const Nc="storage-device-model";let So=class{constructor(e,t,s){a(this,"id");a(this,"mountDir");a(this,"removed");a(this,"vendor");a(this,"runTimeMs");a(this,"model");a(this,"nodeId");a(this,"local");a(this,"label");a(this,"syspath");a(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}`)}};So=Dp([Us(),O(Nc)],So);const ks=new ae({class:So,type:Nc});var Sp=Object.defineProperty,Cp=Object.getOwnPropertyDescriptor,$r=(e,t,s,o)=>{for(var r=o>1?void 0:o?Cp(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Sp(t,s,r),r};const Uc="storage-device-container-model",Ap="/kos/storage";let jt=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new de({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(o=>o.id===s.id)).forEach(s=>{this.removeModel(s.id)}),e.forEach(s=>{const o=this.getModel(s.id);if(o){const r={...s,kosParentId:this.id};o.updateModel(r)}else{const r={...s,kosParentId:this.id},n=ks.instance(s.id).options(r).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await Fc()).forEach(t=>{const s={...t,kosParentId:this.id},o=ks.instance(t.id).options(s).build();this.addModel(o)})}};$r([ie],jt.prototype,"_models",2);$r([R({topic:Ap,websocket:!0})],jt.prototype,"handleStorageAvailability",1);jt=$r([O(Uc)],jt);const Ze=new pe({class:jt,type:Uc});Ze.addRelatedModel(ks);const{URL:Or}=q(),{getAll:Rp,postModel:Lp}=Y.build({basePath:`${Or}/api/kos/update/available`}),En=f.createLogger({name:"usb-update-service",group:"Services"}),jc=async()=>{En.debug("sending GET for usb-update");const e=await Rp({urlOverride:`${Or}/api/kos/update/available`});return!(e!=null&&e.data)||(e==null?void 0:e.status)!==200?(En.error("Failed to retrieve usb-update data",e),[]):e.data},Bc=async(e,t,s)=>{const o=await Lp({model:{manifestId:e,deviceId:t},tracker:s,urlOverride:`${Or}/api/kos/update/install`});if(!(o!=null&&o.data))throw new Error("No response from server");return o.data},Pp=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:jc,installUpdate:Bc},Symbol.toStringTag,{value:"Module"}));var kp=Object.defineProperty,xp=Object.getOwnPropertyDescriptor,Kc=(e,t,s,o)=>{for(var r=o>1?void 0:o?xp(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&kp(t,s,r),r};const Gc="usb-update-model";let xs=class{constructor(e,t,s){a(this,"id");a(this,"active");a(this,"blocked");a(this,"createTime");a(this,"deviceId");a(this,"manifestId");a(this,"notes");a(this,"futureHandler");a(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 lr(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}`),Bc(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}`)}};Kc([Lr()],xs.prototype,"install",1);xs=Kc([O(Gc)],xs);const Dr=new ae({class:xs,type:Gc});var Fp=Object.defineProperty,Np=Object.getOwnPropertyDescriptor,qs=(e,t,s,o)=>{for(var r=o>1?void 0:o?Np(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Fp(t,s,r),r};const Vc="usb-update-container-model";let Je=class{constructor(e,t,s){a(this,"id");a(this,"disposer");a(this,"storageService");a(this,"_activeUpdate");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new de({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 jc();z(()=>{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 o=`${s.deviceId}-${s.manifestId}`,r=Dr.instance(o).forceUpdate.options({...s,createTime:new Date(s.createTime)}).build();this.addModel(r)}),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}`)}};qs([Ce({modelType:Ze.type})],Je.prototype,"storageService",2);qs([ie],Je.prototype,"_models",2);qs([ui({dependencies:e=>[e.isUsbInserted]})],Je.prototype,"usbInsertedEffect",1);Je=qs([O(Vc)],Je);const Bt=new pe({class:Je,type:Vc});Bt.addRelatedModel(Dr);const Up=()=>({...{[st.type]:{class:$a},[be.type]:{class:Ra,singleton:!0},...V.registration,...Re.registration,...ze.registration,...Ds.registration,...ge.registration,[wr.type]:{class:exports.WsEventModel,singleton:!0},...Ft.registration,...br.registration,...vs.registration}}),Sr=Up(),jp={models:Sr,preloadModels:[]},Bp=!0,Hc=e=>()=>{const t=Sr;return Vi(Co)(xt).model(ze).model(Ze).model(Bt).model(Ls).model(Is).model(Ct).model(Ts).model(pr).model(Ut).model(We).model(_r).model(Gs,Bp).model(qt),Object.keys(t).forEach(s=>{const o=t[s];Gi(Co)(s,o)}),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e)}},ne={};ne.core={models:Hc(ne)};ne.preload=$.model.preloadModel(ne);ne.model=$.model.register(ne);ne.companion=$.companion.register(ne);ne.legacy=$.model.registerLegacyModel(ne);const Co=ne;class Kp{registerTroubleRankMapper(t){return A.propertyMapper.registerPropertyMapper(re.TroubleRank,t),this}registerTroubleRoleMapper(t){return A.propertyMapper.registerPropertyMapper(re.TroubleRole,t),this}registerTroubleColorMapper(t){return A.propertyMapper.registerPropertyMapper(re.TroubleColor,t),this}registerModelLoader(t,s){A.loader.registerLoader(t,s)}registerCanvasPatternLoader(t){A.loader.registerLoader(We.loader,t)}}const Gp=async(e,t)=>{const s=pr.instance(e).options({}).build(),o=t?`${t}-`:"";return await J(s),{getState:r=>s.data[`${o}${r}`],updateState:async(r,n)=>{await s.updateState(`${o}${r}`,n)},clean:async()=>{for(const r of s.data.keys)await s.updateState(`${o}${r}`,void 0)},unsubscribe:()=>{Oe(s)}}},Yc="kos:service:region",zc="regionId",Vp=`${Yc}-${zc}`,qc=async e=>{const t=Re.factory(Vp)({path:Yc,attribute:zc});await J(t),t.updateProperty(e)},Cr="/kos-timer-event",Ar="/kos-timer-event/tick",Rr="defaultTimerEnd",mt=f.createLogger({name:"timer-manager"}),Hp=e=>e.updateProperty!==void 0;class Wc{constructor(t,s,o){a(this,"name");a(this,"timeout");a(this,"timer");a(this,"state","inactive");a(this,"decrementValue",1);a(this,"remainingTime");a(this,"timeoutActions",new Map);this.name=t;const r=typeof s=="number"?s:s.value||60;this.timeout=r,this.state="inactive",this.remainingTime=r,Hp(s)&&N(()=>{f.info(`Updating config value timer ${t} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:Rr}),o&&o.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){mt.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&&(mt.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 o=t.name,r=this.timeoutActions.get(s).find(n=>n.name===o);r?r.action=t.action:this.timeoutActions.get(s).push(t)}removeTimeoutAction(t){for(const[s,o]of this.timeoutActions.entries()){const r=o.filter(n=>n.name!==t);r.length===0?this.timeoutActions.delete(s):this.timeoutActions.set(s,r)}}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 o;mt.debug(`Executing timer action ${s.name} at ${t}`),(o=s.action)==null||o.call(s,s.name,t),this.notifyTimeoutAction(s),s.singleUse&&(mt.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){F(`${Ar}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(t){F(Cr,{name:this.name,action:t.name,remainingTime:this.remainingTime})}}const yt=new Map,Ne=(e,t)=>{const s=yt.get(e);if(!s){mt.error(`Timer ${e} not found`);return}t(s)},Zc={createRelativeTimer(e,t,s){const o=new Date,r=Math.round((t.getTime()-o.getTime())/1e3);return this.createTimer(e,r,s)},createTimer(e,t=60,s){if(yt.has(e))return yt.get(e);const o=new Wc(e,t,s);return yt.set(e,o),o},getTimer(e){return yt.get(e)},clearTimer(e){Ne(e,t=>t.pause())},restartTimer(e){Ne(e,t=>t.restart())},resetTimer(e){Ne(e,t=>t.reset())},addTimeoutAction(e,t){Ne(e,s=>s.addTimeoutAction(t))},removeTimeoutAction(e,t){Ne(e,s=>s.removeTimeoutAction(t))},startTimer(e){Ne(e,t=>t.start())}},Jc="kos:service:region:settings",Qc="timeZone",Yp=`${Jc}-${Qc}`,Ao=async e=>{const t=Re.factory(Yp)({path:Jc,attribute:Qc});await J(t),t.updateProperty(e)},zp=e=>!e||!e.data;function Lr(e={}){const{alias:t,namespace:s}=e;return(o,r,n)=>{o[wt]=o[wt]||{};const i=n.value,c=async function(...l){const d=Xe();f.debug(`Calling future service ${r} with tracker ${d}`);const u=De.initiateFuture({tracker:d,id:sr});s&&(u.namespace=s),f.debug(`waiting for future ${u.id} to be ready`),await J(u),f.debug(`future ${u.id} is ready`),z(()=>{f.debug(`Adding future ${u.id} to futureHandler`),this.futureHandler.addFuture(u,t)});try{const h=await i.apply(this,[...l,d]);f.debug(`received future response for ${d}`,h);const p=zp(h)?h:h==null?void 0:h.data;return p?(p.progress=1,f.debug("mapping future response to future model"),u.endState?f.debug(`future ${u.id} has already completed. Not updating the model`):ur(p,u)):this.futureHandler.removeFuture(t),p}catch(h){throw f.error(h),h}};o[wt][r]={handler:c}}}const qp=({path:e})=>(t,s)=>{t[P]=t[P]||{},t[P][s]={modelType:Ft.type,id:`${Ft.type}-${e}`,options:{path:e},lifecycle:x.INIT}};function Wp(e){const{path:t,attribute:s}=e;return(o,r)=>{o[P]=o[P]||{},o[P][r]={modelType:br.type,id:`${t}-${s}`,options:{path:t,attribute:s},lifecycle:x.INIT}}}const Be=f.createLogger({name:"services",group:"Services"}),Zp=async(e,t)=>Xc(e,t,`${exports.BASE_URL}/api/server/login`),Xc=async(e,t,s=`${exports.BASE_URL}/api/login`)=>{const o=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:e,password:t})});if(!o.ok){const n=await o.json();throw Error(`${n==null?void 0:n.error}`)}return await o.json()},Jp=async e=>el(e,`${exports.BASE_URL}/api/server/startPasswordReset`,""),el=async(e,t=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const o=await exports.kosFetch(`${t}?email=${e}`,{method:"POST",destinationAddress:s});if(!o.ok)throw Error(`There was a problem reseting config; returned status ${o.status}`);return await o.json()},Qp=async(e,t)=>tl(e,t,`${exports.BASE_URL}/api/server/resetPassword`),tl=async(e,t,s=`${exports.BASE_URL}/api/resetPassword`)=>{Be.debug(`resetting password with token ${e} and password ${t.replace(/./g,"*")}`);const o=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t})});if(Be.debug(`password reset returned status ${o.status}`),!o.ok){Be.error(`password reset failed with message ${o.statusText}`);const n=await o.json();throw Error(`${n==null?void 0:n.error}:There was a problem resetting the password.`)}return await o.json()},Xp=async(e,t,s)=>sl(e,t,s,`${exports.BASE_URL}/api/server/acceptInvite`),sl=async(e,t,s,o=`${exports.BASE_URL}/api/server/acceptInvite`)=>{Be.debug(`accepting invite with token ${e} and password ${t.replace(/./g,"*")}`);const r=await exports.kosFetch(`${o}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t,name:s})});if(Be.debug(`invitation accept returned status ${r.status}`),!r.ok){Be.error(`invite failed with message ${r.statusText}`);const i=await r.json();throw Error(`${i==null?void 0:i.error}:There was a problem accepting the invite.`)}return await r.json()},em=Ie.keyframes`
|
|
78
78
|
0% {
|
|
79
79
|
left: -90px;
|
|
80
80
|
color: #eee;
|
|
@@ -86,13 +86,13 @@ ${d}topics:${t}
|
|
|
86
86
|
left: 90px;
|
|
87
87
|
color: #eee;
|
|
88
88
|
}
|
|
89
|
-
`,
|
|
89
|
+
`,tm=Ie.css`
|
|
90
90
|
font-size: 100px;
|
|
91
91
|
margin-top: -80px;
|
|
92
92
|
position: relative;
|
|
93
|
-
animation: ${
|
|
93
|
+
animation: ${em} ease-in-out infinite alternate;
|
|
94
94
|
animation-duration: 1.2s;
|
|
95
|
-
`,
|
|
95
|
+
`,sm=({children:e})=>On.createPortal(e,document.body);function ol({message:e="Wait a moment while we load your app.",theme:t="light"}){return M.jsx(sm,{children:M.jsxs(om,{theme:t,children:[e,M.jsx("div",{css:tm,children:"."})]})})}const om=ko.div`
|
|
96
96
|
padding-inline: 20px;
|
|
97
97
|
width: 100%;
|
|
98
98
|
height: 100vh;
|
|
@@ -106,7 +106,7 @@ ${d}topics:${t}
|
|
|
106
106
|
left: 0;
|
|
107
107
|
color: ${({theme:e})=>e==="light"?"black":"white"};
|
|
108
108
|
z-index: 10000;
|
|
109
|
-
`;class
|
|
109
|
+
`;class rl extends g.Component{constructor(t){super(t),this.state={error:null,errorInfo:null}}componentDidCatch(t,s){this.setState({error:t,errorInfo:s})}render(){return this.state.errorInfo?this.props.fallback||M.jsxs("div",{children:[M.jsx("h2",{children:"Something went wrong."}),M.jsxs("details",{style:{whiteSpace:"pre-wrap"},children:[this.state.error&&this.state.error.toString(),M.jsx("br",{}),this.state.errorInfo.componentStack]})]}):this.props.children}}const rm={normal:"#B5F7F6",warn:"#F3D78A",error:"#FC8486"},nm=({value:e=0,title:t,status:s="normal",subtitle:o})=>{const r=Ie.css`
|
|
110
110
|
display: flex;
|
|
111
111
|
flex-direction: column;
|
|
112
112
|
`,n=Ie.css`
|
|
@@ -126,7 +126,7 @@ ${d}topics:${t}
|
|
|
126
126
|
`,c=Ie.css`
|
|
127
127
|
width: ${e}%;
|
|
128
128
|
height: 35px;
|
|
129
|
-
background-color: ${
|
|
129
|
+
background-color: ${rm[s]};
|
|
130
130
|
text-align: center;
|
|
131
131
|
line-height: 32px;
|
|
132
132
|
color: black;
|
|
@@ -144,7 +144,7 @@ ${d}topics:${t}
|
|
|
144
144
|
transform: translateX(100%) scaleX(0.5);
|
|
145
145
|
}
|
|
146
146
|
}
|
|
147
|
-
`;return M.jsxs("div",{css:r,children:[M.jsxs("div",{css:n,children:[M.jsx("div",{css:i,children:t}),M.jsx("div",{css:[c,e<0?l:""]})]}),M.jsx("div",{children:o})]})},
|
|
147
|
+
`;return M.jsxs("div",{css:r,children:[M.jsxs("div",{css:n,children:[M.jsx("div",{css:i,children:t}),M.jsx("div",{css:[c,e<0?l:""]})]}),M.jsx("div",{children:o})]})},im={setModel:()=>!1},Ws=g.createContext(im),am=()=>{const e=g.useContext(Ws);if(e==null)throw new Error("useModels must be used within a KosModelProvider");return e.model},nl=({children:e})=>{const[t,s]=g.useState(),o=g.useCallback(r=>(s(r),!0),[s]);return M.jsx(Ws.Provider,{value:{model:t,setModel:o},children:e})},il=f.createLogger({name:"kos-model-hierarchy-context"}),cm={models:[],addModel:()=>{il.debug("Default implementation being used. Do Nothing.")}},Zs=g.createContext(cm),lm=({children:e})=>{const[t,s]=g.useState([]),o=g.useCallback(r=>{t.includes(r)||(il.debug("adding to hierarchy context",r.id),s(n=>[...n,r]))},[t]);return M.jsx(Zs.Provider,{value:{models:t,addModel:o},children:e})},dm=()=>!0,al=e=>{const t=g.useContext(Zs);if(!t)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(e==null?void 0:e.filter)||dm;return g.useMemo(()=>t.models.filter(s),[t.models,s])},um=e=>al({filter:s=>{const o=Ae(s.id);return(o==null?void 0:o.type)===e}})[0],hm=f.createLogger({name:"kos-model-loader"}),gm=()=>M.jsx("div",{}),cl=({fallback:e,children:t,...s})=>M.jsx(nl,{children:M.jsx(rl,{fallback:e,children:M.jsx(g.Suspense,{children:M.jsx(ll,{...s,children:t})})})}),ll=e=>{const[t,s]=g.useState(),[o,r]=g.useState(!1),{setModel:n}=g.useContext(Ws),i=g.useContext(Zs);if(g.useEffect(()=>{e.model&&(s(e.model),n(e.model),r(!0),i&&i.addModel(e.model))},[i,e.model,n]),e.error)throw hm.error(e.error),new Error(e.error);const c=e.loading||M.jsx(gm,{});return M.jsx(M.Fragment,{children:t&&o?e.children:c})},us={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},dl=g.createContext(us),fm=({translations:e=us,children:t})=>{const s={header:{...us.header,...e.header},createModal:{...us.createModal,...e.createModal}};return M.jsx(dl.Provider,{value:s,children:t})};function pm(e,t){const s=E.create(e,!1,t),o=s.whenReady().then(()=>s);return Ko(o)}const ul=g.createContext(void 0),mm=(e={models:{},preloadModels:[]},t)=>{const s=pm(e,t),o=({children:r})=>{const n=s.read(),[i,c]=g.useState(n.isOnline);return g.useEffect(()=>{const l=N(()=>{c(n.isOnline)});return()=>{l()}},[n]),M.jsx(ul.Provider,{value:{kosCore:n,online:i},children:r})};return{KosCoreContextProvider:xo.observer(o)}},hl=()=>{const e=g.useContext(ul);if(e===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return e},ym=8,bm=(e=0)=>new Promise(t=>{setTimeout(()=>{t(!0)},2**e*10)}),Te=new Map;function vm(e,t){if(Te.has(e)){const s=Te.get(e);if(s.status==="finished"){const o=E.getInstance().modelManager.getModelById(e);return{kosModel:o,model:o==null?void 0:o.modelData}}else throw s.promise}else{const s=t().then(()=>{Te.set(e,{status:"finished",key:e})},r=>{throw Te.set(e,{status:"error",error:r}),r}),o={status:"pending",promise:s};throw Te.set(e,o),s}}function wm(e,t){return vm(e,t)}async function Mm(e,t){const{modelId:s,factory:o,modelType:r,options:n,activate:i}=t;let c=0;await e.whenReady();let l;if(n){const u=typeof r=="string"?e.modelManager.getModelFactory(r):o;if(!u)throw Error("No Factory Specified. Cannot create a new instance");l=u.build(s,n)}const d=e.modelManager.getModelById(s);if(!d){if(c>ym)throw Error(`KOS Model ${s} has not been found`);await bm(c),c=c+1}return await(d==null?void 0:d.whenReady()),d?(l=d.modelData,{kosModel:d,model:l}):{kosModel:void 0,model:void 0}}const B=e=>{const{modelId:t,modelType:s,activate:o,destroyOnUnmount:r}=e,n=hl(),[i,c]=g.useState(!1),[l,d]=g.useState(),{kosModel:u,model:h}=wm(t||s||"",()=>Mm(n.kosCore,e));return g.useEffect(()=>{async function p(){try{return await n.kosCore.whenReady(),o&&await(u==null?void 0:u.fsm.transitionTo(D.GO_ACTIVE,y.ACTIVE)),c(!0),u}catch(b){d(b.message)}}let w;return n.kosCore&&t&&p().then(b=>{w=N(()=>{const _=(b==null?void 0:b.status)===y.READY;c(_)})}).catch(b=>{console.error(b)}),()=>{if(o){if(h!=null&&h.id){const b=n.kosCore.modelManager.getModelById(h.id);b==null||b.fsm.transitionTo(D.GO_INACTIVE,y.INACTIVE).then(()=>{if(r){const _=h.id;Oe(h).then(()=>{Te.delete(_),w==null||w()})}})}}else r&&h&&Oe(h).then(()=>{Te.delete(t),w==null||w()})}},[o,r,n.kosCore,u,h,t]),{model:h,ready:i,error:l,status:{model:h,ready:i,error:l},KosModelLoader:cl}},Pr=()=>{const e=vs.type;return B({modelId:e,modelType:vs.type,options:{}})},kr=g.createContext(void 0),_m=({children:e})=>{const{model:t,ready:s}=Pr(),o=g.useMemo(()=>s&&t?{model:t}:{},[s,t]);return M.jsx(kr.Provider,{value:o,children:e})},Em=()=>{const e=g.useContext(kr);if(!e)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return e},xr=()=>{const e=Ts.type;return B({modelId:e,modelType:Ts.type,options:{}})};function Im(e){return()=>t=>{const{model:s,status:o,KosModelLoader:r}=xr();return M.jsx(r,{...o,children:M.jsx(e,{...t,softwareInfo:s})})}}const Fr=g.createContext(void 0),Tm=({children:e})=>{const{model:t,ready:s}=xr(),o=g.useMemo(()=>s&&t?{model:t}:{},[s,t]);return M.jsx(Fr.Provider,{value:o,children:e})},$m=()=>{const e=g.useContext(Fr);if(!e)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return e},gl=new sa,fl=g.createContext(gl);function Om({children:e}){return M.jsx(fl.Provider,{value:gl,children:e})}const Nr=g.createContext(void 0),Dm=()=>{const e=window.location.origin,t=ee();return(t==null?void 0:t.host)||e},Sm=({children:e,appContext:t,locale:s="en",resolver:o,rootUrl:r,descriptorResolver:n})=>{const[i,c]=g.useState(!1),[l,d]=g.useState(),[u,h]=g.useState(),p=r||Dm(),w=g.useMemo(()=>t??"app/system",[t]);g.useEffect(()=>{async function I(){const se=(Array.isArray(w)?w:[w]).map(Q=>(n||pc(Q))()),Js=(await Promise.allSettled(se)).map(Q=>{if(Q.status==="rejected"){f.warn("Failed to load localization descriptor",Q.reason);return}return Q.value}).filter(Q=>!!Q).reverse().reduce((Q,Me)=>{const Qs=Me.path;return Object.keys(Me.namespaces).forEach(Xs=>{const eo=Me.namespaces[Xs];eo.basePath=Qs}),{...Q,namespaces:{...Q.namespaces,...Me.namespaces}}},{});d(Js)}I()},[w,n]),g.useEffect(()=>{async function I(){if(l){const C=p,{translations:se}=await wc.init({lang:s,descriptor:l,defaultNamespace:"common",resolver:o,rootUrl:C});h(se),c(!0)}}I()},[s,l,o,p]);const b=g.useMemo(()=>i?{setLocale:I=>{u&&(u.currentLocale=I)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,u]),_=i?e:null;return M.jsx(Nr.Provider,{value:b,children:_})},Cm=()=>{const e=g.useContext(Nr);if(!e)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return e},Am=()=>{const e=We.type;return B({modelId:e,modelType:We.type,options:{}})};function Rm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Am();return M.jsx(r,{...o,children:M.jsx(e,{...t,canvasDispatcher:s})})}}const Lm=(e,t,s)=>{const o=atob(e),r=new Uint8ClampedArray(t*s*4);for(let n=0,i=0;n<o.length&&i<r.length;n+=3,i+=4)r[i]=o.charCodeAt(n),r[i+1]=o.charCodeAt(n+1),r[i+2]=o.charCodeAt(n+2),r[i+3]=255;return r},Pm=(e,t,s)=>{const o=new Uint8ClampedArray(t*s*4);for(let r=0;r<e.length;r++){const n=e.charCodeAt(r),i=(n>>5&7)*255/7,c=(n>>2&7)*255/7,l=(n&3)*255/3,d=r*4;o[d]=i,o[d+1]=c,o[d+2]=l,o[d+3]=255}return o};function km({ctx:e,format:t,dataString:s,width:o,height:r,pixelSize:n}){const i=t==="base64"?Lm(s,o,r):Pm(s,o,r),c=new ImageData(i,o,r),l=document.createElement("canvas");l.width=o,l.height=r;const d=l.getContext("2d");d==null||d.putImageData(c,0,0),e.imageSmoothingEnabled=!1,e.clearRect(0,0,o*n,r*n),e.drawImage(l,0,0,o*n,r*n)}const xm=f.createLogger({name:"canvas-streamer"});xm.debug("main-view component loaded");const ho=10,pl=xo.observer(({canvasDispatcher:e,height:t=30,width:s=50,defaultFps:o=10,showPreview:r=!1,name:n,apiPath:i="/api/system/canvas"})=>{const c=g.useRef(null),[l,d]=g.useState();g.useEffect(()=>{const h=e.addNamedEndpoint(n,{apiPath:i,fps:o,width:s,height:t,id:n});d(h)},[e]);const u=g.useCallback(h=>{if(c.current&&r){const p=c.current.getContext("2d");p&&km({ctx:p,format:"base64",dataString:h,height:t,width:s,pixelSize:ho})}},[s,t,r]);return g.useEffect(()=>{l&&(l.onFrame=u,l.width=s,l.height=t,l.fps=o)},[l,u,s,t,o]),r&&On.createPortal(M.jsx(Nm,{children:M.jsx(Um,{children:M.jsx("canvas",{ref:c,width:s*ho,height:t*ho,style:{border:"1px solid black"}})})}),document.body)}),Fm=Rm(pl),Nm=ko.div`
|
|
148
148
|
display: flex;
|
|
149
149
|
flex-direction: column;
|
|
150
150
|
gap: 8px;
|
|
@@ -152,9 +152,9 @@ ${d}topics:${t}
|
|
|
152
152
|
width: 100%;
|
|
153
153
|
justify-content: space-between;
|
|
154
154
|
align-items: center;
|
|
155
|
-
`,
|
|
155
|
+
`,Um=ko.div`
|
|
156
156
|
display: flex;
|
|
157
157
|
flex-direction: column;
|
|
158
158
|
align-items: center;
|
|
159
|
-
`,fl=()=>{const e=Ls.type;return B({modelId:e,modelType:Ls.type,options:{}})};function Nm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=fl();return M.jsx(r,{...o,children:M.jsx(e,{...t,device:s})})}}function Um(e,t,s){const o=new Promise(r=>{E.getInstance().whenReady().then(()=>{const{model:n}=E.getInstance().modelManager.createModelInstance(e,t??e,s);return n.whenReady().then(()=>{r(n.modelData)})})});return Bo(o)}function jm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Rr();return M.jsx(r,{...o,children:M.jsx(e,{...t,kosTime:s})})}}const pl=()=>{const e=Ut.type;return B({modelId:e,modelType:Ut.type,options:{}})};function Bm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=pl();return M.jsx(r,{...o,children:M.jsx(e,{...t,networkInterfaceContainer:s})})}}const ml=()=>{const e=Is.type;return B({modelId:e,modelType:Is.type,options:{}})};function Km(e){return t=>{const{model:s,status:o,KosModelLoader:r}=ml();return M.jsx(r,{...o,children:M.jsx(e,{...t,oTA:s})})}}function Gm(e,t){g.useEffect(()=>{function s(r){e.current&&!e.current.contains(r.target)&&t()}function o(r){r.key==="Escape"&&t()}return document.addEventListener("mousedown",s),document.addEventListener("keydown",o,!1),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",o,!1)}},[e,t])}function Vm(e){const t=g.useRef(null),s=e.onAlert;return Gm(t,s),M.jsx("div",{ref:t,style:{width:"100%"},children:e.children})}const Hm=e=>{var d;const{stateProp:t}=e,[s,o]=g.useState((d=e.stateProp)==null?void 0:d.value),[r,n]=g.useState(!1),[i,c]=g.useState(void 0);return g.useEffect(()=>{async function u(h){try{h&&(await J(h),n(!0))}catch(p){c(p.message)}}u(t)},[t]),g.useEffect(()=>{const u=F(()=>{t&&r&&o(t.value)});return()=>{u()}},[r,t]),[s,{ready:r,error:i}]},yl=()=>{const[e,t]=g.useState(!1),[s,o]=g.useState([]),r=Ze.type,n=B({modelId:r,modelType:Ze.type,options:{}});return g.useEffect(()=>{const i=F(()=>{var c,l;t(((c=n.model)==null?void 0:c.isStorageInserted)??!1),o(((l=n.model)==null?void 0:l.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:e,devices:s}};function Ym(e){return t=>{const{model:s,status:o,KosModelLoader:r}=yl();return M.jsx(r,{...o,children:M.jsx(e,{...t,storageDeviceContainer:s})})}}const zm=({timerName:e,onTimerExpired:t,timerEventActions:s,autoStart:o})=>{const r=qc.getTimer(e);return g.useEffect(()=>{const n=j(Sr,i=>{const{name:c,action:l,remainingTime:d}=i==null?void 0:i.body;c===e&&r&&(l===Ar?t({name:c,action:l,remainingTime:d,timer:r}):s!=null&&s[l]&&s[l]({name:c,action:l,remainingTime:d,timer:r}))});return o&&(r==null||r.start()),()=>{n.unsubscribe()}},[o,t,r,s,e]),{timer:r,start:r==null?void 0:r.start.bind(r),reset:r==null?void 0:r.reset.bind(r),pause:r==null?void 0:r.pause.bind(r)}},qm=e=>{const t=/[\\^$.*+?()[\]{}|]/g;return RegExp(t.source).test(e)?e.replace(t,"\\$&"):e},Wm=e=>e instanceof RegExp,Zm=e=>typeof e=="string",Jm=(e,t,s)=>{if(e===""||t==="")return e;let o=t;Wm(o)||(o=new RegExp("("+qm(o)+")","gi"));const r=e.split(o);for(let n=1,i=r.length;n<i;n+=2)r[n]=s(r[n],n);return r},bl=(e,t,s)=>{let o=e;return Array.isArray(o)||(o=[o]),o.flatMap(r=>Zm(r)?Jm(r,t,s):r)};function Qm(e,t){let s=e;return Object.entries(t).forEach(([o,r])=>{const n=new RegExp(`<${o}>(.*?)</${o}>|<${o}/>`,"g");s=bl(s,n,(i,c)=>r.type==="br"?M.jsx("br",{}):g.cloneElement(r,{key:`${o}-${c}`},i))}),s}const Xm=e=>{const{i18nKey:t,t:s,defaults:o,components:r,values:n={},context:i}=e,c=s(t,{defaultValue:o,data:n,context:i,returnObjects:!0}),l=Qm(c,r||{});return M.jsx("span",{className:e.className,children:l})},je=new Map;function ey(e,t){if(je.has(e)){const s=je.get(e);if(s.status==="finished")return s.result;throw s.promise}else{const s=t().then(r=>{je.set(e,{status:"finished",result:r})},r=>{throw je.set(e,{status:"error",error:r}),r}),o={status:"pending",promise:s};throw je.set(e,o),s}}function Co(e,t){return ey(e,t)}const ty=async()=>{const e=await Ui(ge.type);return await J(e.model),e.model},sy=async(e,t,s)=>{const o=e.resolveNamespace(t);await J(o);for(const r of s){const n=e.resolveNamespace(r);await J(n),je.set(r,{status:"finished",result:n})}return o},oy=(e,t)=>{const s=[e].flat(),[o,...r]=s,n=Co(ge.type,ty),i=s.join("__"),c=Co(i,()=>sy(n,o,r)),l=g.useMemo(()=>({exists:u=>{const h=t!=null&&t.keyPrefix?`${t.keyPrefix}.${u}`:u;return c?c.exists(h):!1}}),[t==null?void 0:t.keyPrefix,c]);return{t:g.useCallback((u,h)=>{const p=t!=null&&t.keyPrefix?`${t.keyPrefix}.${u}`:u;return c?c.resolveKey(p,h):(f.debug(`Translation model ${e} not ready for key: ${p}`),p)},[t==null?void 0:t.keyPrefix,e,c]),i18n:l}},vl=()=>{const e=ge.type;return B({modelId:e,modelType:ge.type,options:{}})};function ry(e){return t=>{const{model:s,status:o,KosModelLoader:r}=vl();return M.jsx(r,{...o,children:M.jsx(e,{...t,translationContainer:s})})}}const ny=e=>B({modelId:e,modelType:xt.type}),Fr=()=>B({modelId:ze.type,modelType:ze.type,options:{}}),iy=({troubleType:e,condition:t})=>{const{model:s}=Fr(),[o,r]=g.useState(!1),[n,i]=g.useState([]),c=g.useCallback(()=>{var l,d;return n.length>0&&((l=n[0])!=null&&l.resolvable)?(d=n[0])==null?void 0:d.resolve():Promise.resolve(void 0)},[n]);return g.useEffect(()=>F(()=>{const d=(e?s==null?void 0:s.troubles.getIndexByKey("byType",e):s==null?void 0:s.troubles.data)||[],u=t?d.filter(t):d;r(u.length>0),i(u)}),[t,s,e]),[o,c,n.length>0?n[0]:void 0,n]};function ay(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Fr();return M.jsx(r,{...o,children:M.jsx(e,{...t,troubleContainer:s})})}}const wl=()=>{const e=Bt.type,t=B({modelId:e,modelType:Bt.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,o]=g.useState(!1),[r,n]=g.useState(!1),[i,c]=g.useState([]);return g.useEffect(()=>{const l=F(()=>{var d,u,h;o(((d=t.model)==null?void 0:d.isUsbInserted)??!1),n(((u=t.model)==null?void 0:u.hasAvailableUpdates)??!1),c(((h=t.model)==null?void 0:h.data)??[])});return()=>{l()}},[t.model]),{...t,inserted:s,updateAvailable:r,updates:i}};function cy(e){return t=>{const{model:s,status:o,KosModelLoader:r}=wl();return M.jsx(r,{...o,children:M.jsx(e,{...t,usbUpdateContainer:s})})}}const ly=({path:e,propKey:t})=>{const{status:s}=B({modelType:At.type,modelId:e,options:{path:e}}),[o,r]=g.useState(!1),[n,i]=g.useState(),[c,l]=g.useState(""),[d,u]=g.useState(),h=p=>{n&&t&&n.updateProperty(t,p)};return g.useEffect(()=>{var p;s.model&&i(s.model),s.model&&t&&((p=s.model)!=null&&p.props.has(t)?l(s.model.props[t]):u(`property ${t} not found`)),s.ready&&r(s.ready)},[s.ready,s.model,t]),g.useEffect(()=>{t&&v.autorun(()=>{const p=n==null?void 0:n.props[t];l(p||"")})},[n,t]),{config:n,ready:o,value:c,error:d,updateValue:h}},dy=(e,t)=>{switch(t.type){case"UPDATE":return t.payload;default:return e}},Ml=({configProperty:e,optionsTransformer:t})=>{const[s,o]=g.useState(!1),[r,n]=g.useState(""),[i,c]=g.useReducer(dy,{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}),l=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&(e==null||e.updateProperty(u))},[e]);return g.useEffect(()=>{async function d(u){try{u&&(await J(u),o(!0))}catch(h){n(h.message)}}d(e)},[e]),g.useEffect(()=>{const d=F(()=>{if(e&&s){let u=[];t&&(u=t(e.options)),c({type:"UPDATE",payload:{value:String(e.value),displayValue:e.displayValue,significantValue:e.significantValue,unit:e.unit,options:e.options,mappedOptions:u,updateProperty:e.updateProperty,displayOptions:e==null?void 0:e.displayOptions}})}});return()=>{d()}},[e,t,s]),{...i,configSelectProps:{onChange:l,value:i.value,options:t?i.mappedOptions||[]:i.options||[]},ready:s,error:r}};function uy(e,t){const s=t??new Date().getFullYear(),o=[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:o[e]??0}function hy(e,t){return new Date(e,t,0).getDate()}function _l(e,t){const s=uy(t,e),o=[];for(let r=1;r<=s;r++)o.push(r);return o}function El(){return[...Array(12).keys()].map(t=>new Date(0,t).getMonth())}function Il(e=[2018,2028]){const t=[];for(let s=e[0];s<=e[1];s++)t.push(s);return t}function Tl(e,t=[2018,2028]){const s=Il(t);return e==="long"?s:s.map(o=>Number(o.toString().substring(2)))}function Nr(e="numeric",t="en-US"){const s=new Intl.DateTimeFormat(t,{month:e,timeZone:"UTC"}).format;return[...Array(12).keys()].map(o=>s(new Date(Date.UTC(0,o,1))))}function gy({locale:e="en-US",year:t,month:s,day:o,formatOptions:r={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:n}){const i=s-1,c=new Date(t,i,o),l=new Intl.DateTimeFormat(e,{month:r.month}).format(c),d=new Intl.DateTimeFormat(e,{year:r.year}).format(c),u=new Intl.DateTimeFormat(e,{day:r.day}).format(c);return n?n=="MMDDYY"?`${l} ${u} ${d}`:n==="DDMMYY"?`${u} ${l} ${d}`:n==="YYMMDD"?`${d} ${l} ${u}`:`${d} ${u} ${l}`:new Intl.DateTimeFormat(e,r).format(c)}function oe(e){return e.toString().length===2?new Date(Date.parse(`01 Jan 20${e}`)).getFullYear():e}function fy(e){return typeof e=="string"?new Date(Date.parse(`01 ${e.substring(0,3)} 2023`)).getMonth()+1:e}function $l(e,t,s){const o=oe(t),r=new Date(o,e,1).getDay(),n=new Date(o,e+1,0).getDate();return[...Array(42).keys()].map(c=>c<r||c>n+r-1?{label:"",value:0,disabled:!0}:s[c-r])}function bt(e,t,s){const o=t-1,r=new Date(e,o,s);return new Date(r).getMonth()===o&&new Date(r).getDate()===s}function vt(e,t){return new Date(e,t,0).getDate()}function Ol(e="en-US",t="short"){const s=new Intl.DateTimeFormat(e,{weekday:t}).format;return[...Array(7).keys()].map(o=>s(new Date(Date.UTC(2021,5,o))))}function Dl({locale:e="en-US",year:t=new Date().getFullYear(),month:s=new Date().getMonth(),yearRange:o=[2018,2028],daysOfWeekFilter:r=[],formatOptions:{yearFormat:n="long",monthFormat:i="long",dayFormat:c="short"}={}}){const l=Ur(n,o),d=Sl(n,o,e),u=Al(i,e),h=Cl(i,e),p=jr(t,s),w=Rl(t,s,e,r),b=kl(s,t,w),_=Ll(e,c);return{daysArray:p,monthsArray:u,yearsArray:l,yearsOptionsArray:d,monthsOptionsArray:h,daysOptionsArray:w,calendarDayArray:b,dayNamesArray:_}}function Ur(e="long",t=[2018,2028]){return g.useMemo(()=>Tl(e,t),[e,t])}function Sl(e="long",t=[2018,2028],s="en-US"){const o=Ur(e,t);return g.useMemo(()=>o.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,o])}function Al(e,t="en-US"){return g.useMemo(()=>Nr(e,t),[e,t])}function Cl(e,t="en-US"){const s=g.useMemo(()=>El(),[]),o=g.useMemo(()=>Nr(e,t),[e,t]);return g.useMemo(()=>[...Array(12).keys()].map(n=>({label:o[n],value:Number(s[n])})),[o,s])}function jr(e,t){const s=oe(e);return g.useMemo(()=>_l(s,t),[t,s])}const py=(e,t,s,o=[])=>{const r=new Date(e,t,s).getDay();return o.length>0&&o.includes(r)};function Rl(e,t,s="en-US",o=[]){const r=jr(e,t);return g.useMemo(()=>r.map(i=>({label:i.toLocaleString(s),value:i,disabled:py(e,t,i,o)})),[o,s,t,r,e])}function Ll(e="en-US",t="short"){return g.useMemo(()=>Ol(e,t),[e,t])}function Pl({year:e=new Date().getFullYear(),month:t=new Date().getMonth(),day:s=new Date().getDate(),formatString:o}){const r=t,n=new Date(e,r,s);return{formattedDate:me.format(n,o)}}function kl(e,t,s){return g.useMemo(()=>$l(e,t,s),[e,t,s])}var xl=(e=>(e.MMDDYY="MMDDYY",e.DDMMYY="DDMMYY",e.YYMMDD="YYMMDD",e.YYDDMM="YYDDMM",e))(xl||{});function my({locale:e="en-US",date:{year:t=new Date().getFullYear(),month:s=new Date().getMonth(),day:o=new Date().getDate()}={year:new Date().getFullYear(),month:new Date().getMonth(),day:new Date().getDate()},formatOptions:{yearFormat:r="long",monthFormat:n="long",dayFormat:i="short",formatString:c="yyyy/MM/dd"}={},filterOptions:{yearsRange:l=[2018,2028],daysOfWeekFilter:d=[]}={}}){const[u,h]=g.useState(t),[p,w]=g.useState(l),[b,_]=g.useState(s),[I,A]=g.useState(o);g.useEffect(()=>{h(t)},[t]),g.useEffect(()=>{_(s)},[s]),g.useEffect(()=>{A(o)},[o]);const{yearsArray:se,yearsOptionsArray:we,monthsArray:rt,monthsOptionsArray:Js,daysArray:Q,daysOptionsArray:Me,calendarDayArray:Qs,dayNamesArray:Xs}=Dl({locale:e,year:u,yearRange:p,month:b,formatOptions:{yearFormat:r,monthFormat:n,dayFormat:i},daysOfWeekFilter:d}),{formattedDate:eo}=Pl({year:u,month:b,day:I,formatString:c});return{dateActions:{setYear:h,setYearRange:w,setMonth:_,setDay:A,nextMonth:()=>{const K=b<11?oe(u):oe(u+1),W=b<11?b+1:0;if(!bt(K,W,I)){const _e=vt(K,W);A(_e)}W===0&&h(K),_(W)},previousMonth:()=>{const K=oe(b===0?u-1:u),W=b===0?11:b-1;if(!bt(K,W,I)){const _e=vt(K,W);A(_e)}W===11&&h(K),_(W)},nextYear:()=>{const K=u<p[1]?u+1:p[0],W=oe(K);if(bt(W,b,I))h(K);else{const _e=vt(oe(u+1),b);A(_e),h(K)}},previousYear:()=>{const K=u>p[0]?u-1:p[0],W=oe(K);if(bt(W,b,I))h(K);else{const _e=vt(oe(u-1),b);A(_e),h(K)}}},dateState:{year:u,yearRange:p,month:b,day:I,yearsArray:se,yearsOptionsArray:we,monthsArray:rt,monthsOptionsArray:Js,daysArray:Q,daysOptionsArray:Me,calendarDayNames:Xs,calendarDayArray:Qs,formattedDate:eo}}}function Fl({date:e=new Date,dateFormat:t,timeFormat:s,options:o={}}){const[r,n]=g.useState("Formatting Time..."),[i,c]=g.useState("Formatting Date..."),l=!!o.ignoreDateFormat,{model:d,ready:u}=B({modelId:V.type,modelType:V.type,options:{}}),h=typeof e=="string"?me.parseISO(e):e;return g.useEffect(()=>{l?c(""):t?c(me.format(h,t)):u&&c(me.format(h,d!=null&&d.selectedDateFormat?d==null?void 0:d.selectedDateFormat:""))},[l,e,t,h,d,u]),g.useEffect(()=>{s?n(me.format(h,s)):u&&n(me.format(h,d!=null&&d.selectedTimeFormat?d==null?void 0:d.selectedTimeFormat:""))},[e,s,h,d,u]),{formattedDate:i,formattedTime:r}}const Nl=({secondsFromMidnight:e=0})=>{const[t,s]=g.useState(0),[o,r]=g.useState(0),[n,i]=g.useState(0),[c,l]=g.useState(new Date),{formattedTime:d}=Fl({date:c,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const u=Number(e),h=Math.floor(u/3600),p=Math.floor(u%3600/60),w=u%60;s(h),r(p),i(w);const b=new Date;b.setHours(0,0,0,0);const _=new Date(b.getTime()+u*1e3);l(new Date(_))},[e]),{hours:t,minutes:o,seconds:n,formattedTime:d,timeActions:{setHours:s,setMinutes:r,setSeconds:i}}},yy=({configProperty:e})=>{const{value:t}=Ml({configProperty:e}),s=parseInt(t||"0",10),{hours:o,minutes:r,seconds:n,formattedTime:i,timeActions:c}=Nl({secondsFromMidnight:s}),l=g.useRef();return g.useEffect(()=>{const d=o*3600+r*60+n;return l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{e&&e.updateProperty(d.toString())},100),()=>{l.current&&clearTimeout(l.current)}},[e,o,r,n]),{hours:o,minutes:r,seconds:n,formattedTime:i,timeActions:c}};function by(e,t={}){const{intervalMs:s=5*60*1e3,immediate:o=!0}=t;g.useEffect(()=>{const r=()=>{try{e({__warmup:!0})}catch{}};o&&("requestIdleCallback"in window?requestIdleCallback(r):setTimeout(r,1));const n=s?setInterval(r,s):null;return()=>{n&&clearInterval(n)}},[e,s,o])}const vy=e=>M.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),wy=(e=vy)=>{const[t,s]=g.useState([]),[o,r]=g.useState(),{model:n,ready:i}=B({modelType:V.type,modelId:V.type,options:{}});g.useEffect(()=>{const l=F(()=>{s((n==null?void 0:n.dateFormatOptions.map(e))||[])});return()=>{l()}},[n,i,e]),g.useEffect(()=>{const l=F(()=>{n!=null&&n.dateFormatId&&(n!=null&&n.selectedDateFormat)&&r({id:n==null?void 0:n.dateFormatId,value:n==null?void 0:n.selectedDateFormat})});return()=>{l()}},[n==null?void 0:n.selectedDateFormat,n==null?void 0:n.dateFormatId]);const c=g.useCallback(l=>{var u;let d="";typeof l=="string"?d=l:(u=l==null?void 0:l.target)!=null&&u.value&&(d=l.target.value),d&&(n==null||n.setSelectedDateFormat(d))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(l=>l.id))??[],regionModel:n,selectedDateFormat:(o==null?void 0:o.value)||"",dateFormatId:(o==null?void 0:o.id)||"",updateDateFormat:c,props:{onChange:c,value:(o==null?void 0:o.id)||"",options:t}}},My=e=>M.jsx("option",{title:e,value:e,children:e},e),Ul="kos:service:region:settings",jl="timeZone",_y=`${Ul}-${jl}`,Ey=(e=My)=>{const[t,s]=g.useState([]),[o,r]=g.useState(""),{model:n,ready:i}=B({modelType:V.type,modelId:V.type,options:{}}),c=Re.factory(_y)({path:Ul,attribute:jl});g.useEffect(()=>{const d=F(()=>{s((n==null?void 0:n.timeZones.map(e))||[]),n!=null&&n.timeZones.length&&Ao(n==null?void 0:n.timeZones[0])});return()=>{d()}},[n,i,e]),g.useEffect(()=>{const d=F(()=>{r(c.value||"")});return()=>{d()}},[c.value]);const l=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&Ao(u)},[]);return{options:t,raw:(n==null?void 0:n.timeZones)??[],regionModel:n,selectedTimeZone:o,timeZones:(n==null?void 0:n.timeZones)??[],updateTimeZone:l,selectProps:{onChange:l,value:o,options:t}}},Bl="kos:service:region",Kl="regionId",Iy=`${Bl}-${Kl}`,Ty=e=>M.jsx("option",{title:e,value:e,children:e},e),Gl=(e=Ty)=>{const[t,s]=g.useState([]),[o,r]=g.useState("factory"),{model:n,ready:i}=B({modelType:V.type,modelId:V.type,options:{}}),c=Re.factory(Iy)({path:Bl,attribute:Kl});g.useEffect(()=>{const d=F(()=>{s((n==null?void 0:n.availableRegions.map(e))||[])});return()=>{d()}},[n,i,e]),g.useEffect(()=>{const d=F(()=>{r(c.value||"factory")});return()=>{d()}},[c.value]);const l=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&Yc(u)},[]);return{raw:(n==null?void 0:n.availableRegions)??[],regionModel:n,regionData:n==null?void 0:n.selectedRegion,selectedRegion:o,updateRegion:l,regionSelectProps:{onChange:l,value:o,options:t}}},$y=e=>M.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),Oy=(e=$y)=>{const[t,s]=g.useState([]),[o,r]=g.useState(),{model:n,ready:i}=B({modelType:V.type,modelId:V.type,options:{}});g.useEffect(()=>{const l=F(()=>{s((n==null?void 0:n.timeFormatOptions.map(e))||[])});return()=>{l()}},[n,i,e]),g.useEffect(()=>{const l=F(()=>{n!=null&&n.timeFormatId&&(n!=null&&n.selectedTimeFormat)&&r({id:n==null?void 0:n.timeFormatId,value:n==null?void 0:n.selectedTimeFormat})});return()=>{l()}},[n==null?void 0:n.selectedTimeFormat,n==null?void 0:n.timeFormatId]);const c=g.useCallback(l=>{var u;let d="";typeof l=="string"?d=l:(u=l==null?void 0:l.target)!=null&&u.value&&(d=l.target.value),d&&(n==null||n.setSelectedTimeFormat(d))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(l=>l.id))??[],regionModel:n,selectedTimeFormat:(o==null?void 0:o.value)??"",timeFormatId:(o==null?void 0:o.id)??"",updateTimeFormat:c,props:{onChange:c,value:(o==null?void 0:o.id)??"",options:t}}},Dy=(e,t)=>g.useMemo(()=>Xo(e),t),Sy={config:{attributes:!0,childList:!0,subtree:!0}};function Ay(e,t,s=Sy){const[o,r]=g.useState(null);g.useEffect(()=>{if(!t||typeof t!="function")throw new Error("A valid callback function is required");const n=new MutationObserver(t);r(n)},[t,s,r]),g.useEffect(()=>{if(!o)return()=>{};if(!e)throw new Error("A valid DOM element is required");const{config:n}=s;try{o.observe(e,n)}catch(i){f.error(i)}return()=>{o&&o.disconnect()}},[o,e,s])}const Vl={validateStart:function(e){return!0},validateStop:function(e){const t=e.event.currentTarget.getBoundingClientRect(),[s,o]=e.xy;return s<t.left||s>t.right||o<t.top||o>t.bottom}},go=f.createLogger({name:"usePressGesture",group:"kos-hooks"});function Cy({onPressed:e,onRelease:t,intersectionStrategy:s=Vl}){const o=g.useRef(!1),r=td.useGesture({onDragStart:l=>{go.info("onDragStart",l.type),s.validateStart(l)&&(e&&e(),o.current=!0)},onDrag:l=>{go.info("onDrag",l.type),o.current&&s.validateStop(l)&&(t&&t(),o.current=!1)},onDragEnd:l=>{go.info("onDragEnd",l.type),o.current&&t&&(t(),o.current=!1)}}),n=()=>{e&&e(),o.current=!0},i=()=>{o.current&&t&&(t(),o.current=!1)},c=()=>{o.current&&t&&(t(),o.current=!1)};return{dom:r,mesh:()=>({onPointerDown:n,onPointerUp:i,onPointerOut:c})}}const Hl=()=>{const[e,t]=g.useState(!1),s=E.getInstance();return g.useEffect(()=>{const o=F(()=>{s&&s.reloading!==e&&t(s.reloading)});return()=>{o()}},[s,e]),[e]};function Yl(e=!1,t="2-digit"){return g.useMemo(()=>{const s=e?12:24;return Array.from({length:s},(o,r)=>{const n=e&&r===0?12:r%s;return{id:r,label:t==="2-digit"?n.toString().padStart(2,"0"):n.toString()}})},[t,e])}function Ro(e,t="2-digit",s=0,o=0){return g.useMemo(()=>Array.from({length:e},(r,n)=>{const i=String(n+s);return{id:n+o,label:t==="2-digit"?i.padStart(2,"0"):i}}),[e,s,o,t])}function zl(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 ql({formatOptions:{hour12:e=!0,hour:t="2-digit",minute:s="2-digit",second:o="2-digit"}={hour12:!0,hour:"2-digit",minute:"2-digit",second:"2-digit"},locale:r="en-US"}){const n=Yl(e,t),i=Ro(60,s),c=Ro(60,o),l=zl(r);return{hourOptions:n,minuteOptions:i,secondOptions:c,amPmOptions:l}}function Wl(e,t){return me.format(e,t)}function Zl({formatOptions:e,initialDate:t=new Date,locale:s="en-US",format:o="HH:mm"}){const[r,n]=g.useState(t),i=g.useCallback(_=>{n(I=>{const A=new Date(I);return A.setHours(Number(_)),A})},[]),c=g.useCallback(_=>{n(I=>{const A=new Date(I);return A.setMinutes(Number(_)),A})},[]),l=g.useCallback(_=>{n(I=>{const A=new Date(I);return A.setSeconds(Number(_)),A})},[]),d=g.useCallback(_=>{const I=new Date(_);n(I)},[]),u=Wl(r,o),{hourOptions:h,minuteOptions:p,secondOptions:w,amPmOptions:b}=ql({formatOptions:e,locale:s});return{amPmOptions:b,formattedTime:u,hourOptions:h,minuteOptions:p,secondOptions:w,setHours:i,setMinutes:c,setSeconds:l,setTime:d,time:new Date(r)}}const Ry=e=>{const{regionModel:t}=Gl(),s=g.useMemo(()=>({hour12:t==null?void 0:t.is12HourTimeFormat}),[t==null?void 0:t.is12HourTimeFormat]);return Zl({...e,locale:t==null?void 0:t.regionId,format:t==null?void 0:t.selectedTimeFormat,formatOptions:s})};function Ly(e){return t=>{const[s]=Hl();return s?M.jsx(tl,{message:"Wait a moment while your project reloads..."}):M.jsx(e,{...t})}}const _n=f.createLogger({name:"studio-properties-service",group:"Services"}),Py="/api/kos/studio/properties",Jl=async e=>{if(_n.debug("sending GET for studio-properties"),!e)throw _n.error("connectionId is undefined"),new Error("connectionId is undefined");return await Le.get(Py,{},{destinationAddress:e,timeout:500})},ky=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:Jl},Symbol.toStringTag,{value:"Module"}));var xy=Object.defineProperty,Fy=Object.getOwnPropertyDescriptor,Ny=(e,t,s,o)=>{for(var r=o>1?void 0:o?Fy(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&xy(t,s,r),r};const Ql="studio-properties-model",Uy="/kos/studio/properties",En={"kos.studio.tool.legacy":1};let Lo=class{constructor(e,t,s){a(this,"id");a(this,"connectionId");a(this,"unsubscribe",null);a(this,"logger");a(this,"data");this.id=e,this.logger=s.logger,this.data=ye(),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=Vt.getInstance().subscribeTopic({topic:Uy,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[e,t]=await Jl(this.connectionId);if(e){this.logger.error(`Error loading studio-properties: ${e}`),this.data.setValues(En);return}if(t){const s=Object.keys(t).reduce((o,r)=>(o[r]=t[r]??r,o),{});this.data.setValues(s??En),f.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(e){return this.data[e]}createObservableProperty(e){return Xo(()=>this.get(e))}};Lo=Ny([O(Ql)],Lo);const jy=new ae({class:Lo,type:Ql});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>v.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>v.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>ko.observer});exports.AuthState=Hi;exports.BrowserKosRouter=ta;exports.BrowserRouter=Gs;exports.CanvasDispatcher=We;exports.CanvasDispatcherServices=Zf;exports.CanvasRenderer=Mr;exports.CanvasStreamer=km;exports.CanvasStreamerBase=gl;exports.ChildModels=Mt;exports.ConfigBean=At;exports.CoreExtensionManager=jp;exports.CoreModels=Dr;exports.CreateModelTranslationsContext=cl;exports.CreateModelTranslationsProvider=hm;exports.DateDisplayFormat=xl;exports.DateHelpers=gd;exports.DependencyLifecycle=x;exports.DependencyModels=P;exports.Device=Ls;exports.DeviceServices=cp;exports.DomIntersectionStrategy=Vl;exports.EVENT_KOS_MODEL_READY=Uo;exports.EVENT_TROUBLE_ADDED=Ih;exports.EVENT_TROUBLE_REMOVED=Th;exports.EXTENSION_TROUBLE_DATA_MAPPER=_s;exports.EXTENSION_TROUBLE_MAPPER=Wt;exports.ErrorBoundaryWithFallback=sl;exports.EventBus=nd;exports.ExtensionManager=C;exports.FUTURE_CONTAINER_MODEL_TYPE=Da;exports.FUTURE_MODEL_TYPE=ba;exports.FUTURE_NOT_ASSIGNED=tr;exports.FeatureFlagService=Gn;exports.FetchError=ce;exports.FutureContainerFactory=be;exports.FutureContainerModel=Aa;exports.FutureEndState=Ve;exports.FutureFactory=st;exports.FutureHandler=cr;exports.FutureManager=De;exports.FutureModel=Ia;exports.FutureService=wt;exports.HEADER_CACHE_CONTROL=Sn;exports.HEADER_CONTENT_TYPE=Dn;exports.HEADER_DESTINATION_ADDR=fe;exports.HEADER_FOS_REQUEST_ID=An;exports.HEADER_METHOD=Fs;exports.HEADER_ORDERED=Fo;exports.HEADER_REQUEST_ID=Kt;exports.HEADER_REQUEST_TYPE=le;exports.HEADER_RESPONSE_ID=Ns;exports.HEADER_SOURCE_ADDR=On;exports.HEADER_TOPIC=$n;exports.HEADER_URL=Qe;exports.HEADER_WORK_TRACKER=No;exports.KOS_MODEL_ID=hs;exports.KeyValue=fr;exports.KeyValueServices=wg;exports.Kos=H;exports.KosConfigPropertySpec=Re;exports.KosContainerIndex=Qo;exports.KosContextBean=Qi;exports.KosContextManager=k;exports.KosCore=E;exports.KosCoreModelPropertyMapper=re;exports.KosDataContainer=Xi;exports.KosDependencyTypes=Sd;exports.KosExtensionUtils=Du;exports.KosFeatureFlags=fd;exports.KosFetchMethods=Mi;exports.KosGlobalConfig=Ho;exports.KosLog=f;exports.KosMockEvents=Ln;exports.KosModel=Pi;exports.KosModelCollectionProvider=am;exports.KosModelContainer=de;exports.KosModelContext=Ws;exports.KosModelEvents=D;exports.KosModelFactory=$t;exports.KosModelLoader=il;exports.KosModelLoaderDisplay=al;exports.KosModelManager=Fi;exports.KosModelProvider=ol;exports.KosModelRegistrationFactory=ae;exports.KosModelRegistry=So;exports.KosModelState=y;exports.KosModelSymbol=ci;exports.KosModelVisitor=Qu;exports.KosObservableData=qi;exports.KosRegistration=wh;exports.KosSingletonRegistration=Mh;exports.KosTime=vs;exports.KosTimeContext=Lr;exports.KosTimeProvider=wm;exports.KosTimeServices=Ig;exports.KosTimer=zc;exports.KosToken=ea;exports.KosTranslationProvider=Om;exports.KosTranslations=bc;exports.KosWSTransportStatus=Li;exports.KosWsEvents=Gt;exports.LOGIN_HOST=Cn;exports.LOGIN_URL=sd;exports.LoadingMessage=tl;exports.LogBlock=kt;exports.LogBlockContainer=Hs;exports.LogConfig=Et;exports.LogStream=Dt;exports.LogStreamContainer=qt;exports.LogStreamServices=kg;exports.MODEL_DELETION_DELAY=xi;exports.MiddlewareChain=zi;exports.ModelEffects=$e;exports.MultipleFutureHandler=Qh;exports.NestedModelContext=Zs;exports.NetworkInterface=Ir;exports.NetworkInterfaceContainer=Ut;exports.NetworkInterfaceServices=bp;exports.ObservableData=ye;exports.Ota=Is;exports.OutsideAlerter=Vm;exports.PLUGIN_EXTENSION_NAME=Su;exports.PORT=Rn;exports.PROFILE_LOG_DEBUG=qn;exports.PROFILE_LOG_INFO=Wn;exports.PROFILE_RELAX_STORE_VALIDATION=md;exports.PROFILE_TOOLS_PREVIEW=zn;exports.ParentModel=_t;exports.PluginExtensionManager=Au;exports.ProgressBar=om;exports.ReferenceConfig=is;exports.RegionInfo=V;exports.RegionServices=kh;exports.RegistrationManager=$;exports.Registry=Np;exports.STATUS=xo;exports.ServiceFactory=Y;exports.SingletonKosModelRegistrationFactory=pe;exports.SoftwareInfo=Ts;exports.SoftwareInfoContext=kr;exports.SoftwareInfoProvider=Em;exports.SoftwareInfoServices=mf;exports.StateBean=Ft;exports.StateBeanServices=_f;exports.StateProp=yr;exports.StatePropServices=Rf;exports.StorageDevice=ks;exports.StorageDeviceContainer=Ze;exports.StorageDeviceServices=Ep;exports.StudioProperties=jy;exports.StudioPropertiesServices=ky;exports.SubscriptionHandlers=G;exports.TIMER_END=Ar;exports.TIMER_EVENT=Sr;exports.TimerManager=qc;exports.TokenContext=hl;exports.TokenProvider=Tm;exports.Topics=Ot;exports.Trans=Xm;exports.TransitionMap=as;exports.Transitions=zo;exports.Translation=Ds;exports.TranslationContainer=ge;exports.TranslationContainerContext=xr;exports.TranslationContext=Gf;exports.TransportFactory=vo;exports.Trouble=xt;exports.TroubleContainer=ze;exports.TroubleServices=tf;exports.Troubles=X;exports.UsbUpdate=Or;exports.UsbUpdateContainer=Bt;exports.UsbUpdateServices=Rp;exports.WS_EVENT_TYPE=vc;exports.WebSocketEvents=Tt;exports.WebSocketTransport=Vt;exports.WsEventFactory=vr;exports.acceptOrgInvitation=el;exports.addDaysToDate=xn;exports.addFuture=wa;exports.addMonthsToDate=kn;exports.api=Ta;exports.applyMixins=ad;exports.arraysEqual=cd;exports.buildConfigBeanModel=Dh;exports.buildFuture=ur;exports.buildFutureModel=_a;exports.cancelFuture=Ma;exports.convert=ir;exports.convertFileSizeRaw=id;exports.convertWithUnits=Bh;exports.createBaseMessage=Ii;exports.createBroadcastMessageResponse=Di;exports.createClient=Zo;exports.createFosBaseMessage=Ei;exports.createHeaders=mo;exports.createKosHtpMessageResponse=Si;exports.createKosMessage=$i;exports.createKosMessageResponse=Ai;exports.createMessageBody=ve;exports.createModelDependency=mi;exports.createOptionKey=Ad;exports.createPropKey=Se;exports.createReadableStream=yo;exports.createStudioMessage=_i;exports.createStudioMessageRequest=Ti;exports.createStudioMessageResponse=Oi;exports.debounce=Kn;exports.deleteFuture=va;exports.destroyKosModel=Oe;exports.evaluateScopes=ca;exports.executeChildrenModelLifecycle=vi;exports.executeDependentModelLifecycle=ct;exports.executeListLifecycle=bi;exports.fetchModel=Um;exports.findModel=Pu;exports.findModels=ji;exports.formatDate=Un;exports.formatDateSince=Pn;exports.formatDateTime=Bn;exports.formatTime=jn;exports.getAllKosCompanionModels=xu;exports.getCalendarMonthArray=$l;exports.getConfigBean=aa;exports.getDayStrings=Ol;exports.getDays=hy;exports.getDaysArray=_l;exports.getDaysInMonth=Vo;exports.getDependenciesByLifecycle=yi;exports.getFormattedDate=gy;exports.getFormattedMonth=fy;exports.getFormattedMonthsArray=Nr;exports.getFormattedYear=oe;exports.getFormattedYearsArray=Tl;exports.getFutures=ng;exports.getKosCompanionModel=ku;exports.getKosLocalizationDescriptor=gc;exports.getKosMessageLogging=ei;exports.getKosModel=Ui;exports.getKosModelSync=Ce;exports.getKosModelType=Lu;exports.getKosSessionKey=Ji;exports.getLastDayOfMonth=vt;exports.getLocalizationDescriptor=Pf;exports.getLogLevel=Xn;exports.getLogMessageToStudio=ti;exports.getMessageBody=bo;exports.getMonthsArray=El;exports.getObservableCompanions=Fu;exports.getQueryParams=ee;exports.getTranslations=hc;exports.getYearsArray=Il;exports.hasDecimals=na;exports.hasKosProfile=fo;exports.hslStringToHex=Hn;exports.hslToHex=Vn;exports.initKosProvider=fm;exports.isBoolean=or;exports.isKosCompanionTypeFactory=ki;exports.isKosDataModel=It;exports.isKosLoggingEnabled=vd;exports.isKosModel=te;exports.isKosModelContainer=qo;exports.isKosModelReady=fs;exports.isLeapYear=Go;exports.isLocalRefId=fh;exports.isNumber=js;exports.isPrintable=Hd;exports.isValidDate=bt;exports.kosAction=z;exports.kosAutoEffect=F;exports.kosChild=ie;exports.kosCompanion=Nd;exports.kosComputed=Xo;exports.kosConfigBean=Bs;exports.kosConfigProperty=Jh;exports.kosContext=Ud;exports.kosDependency=Ae;exports.kosEffect=oa;exports.kosFuture=Cr;exports.kosLogger=jd;exports.kosModel=O;exports.kosModelEffect=li;exports.kosObservable=er;exports.kosParentAware=Us;exports.kosReference=Bd;exports.kosStateBean=Yp;exports.kosStateProp=zp;exports.kosSubscribe=Kd;exports.kosTopicHandler=R;exports.kosWhen=Mo;exports.login=Jc;exports.mapConfigBeanModelToDto=ha;exports.mapDataToModel=po;exports.mapDtoToConfigBeanModel=da;exports.mapDtoToFutureModel=dr;exports.mapDtoToFutureOptions=lr;exports.mapUpdateDtoToConfigBeanModel=ua;exports.modelEventTopicFactory=ii;exports.modelFactory=et;exports.modelTypeEventTopicFactory=ai;exports.modifyConfigBean=ia;exports.modifyFuture=ig;exports.pairedClientHeartbeat=nh;exports.pipe=Zi;exports.preloadKosModel=ju;exports.processId=hd;exports.processMiddleware=th;exports.registerCompanionModel=Uu;exports.registerCoreModels=Gc;exports.registerExtensionPoint=Yo;exports.registerKosModel=Ki;exports.registerLegacyModel=Bi;exports.resetKosModel=Ni;exports.resetPassword=Xc;exports.resolveBaseUrl=Yi;exports.resolveChild=wi;exports.resolveContainerDeltas=ld;exports.resolveItemListDeltas=ud;exports.resolveKosCompanion=wo;exports.resolveKosContext=yh;exports.resolveKosProfiles=Jn;exports.resolveListDeltas=dd;exports.resolveServiceUrl=q;exports.resolveVariable=Yn;exports.retryWithExponentialBackoff=ah;exports.sendAsyncIntent=Eh;exports.sendBroadcastMessage=du;exports.sendIntent=_h;exports.sendKosHttpMessageResponse=Ri;exports.sendKosMessage=au;exports.sendKosMessageResponse=Ci;exports.sendRequest=ph;exports.sendStudioMessage=lu;exports.sendStudioMessageRequest=cu;exports.startPasswordReset=Qc;exports.stringComponentInsert=bl;exports.studioAcceptOrgInvitation=Jp;exports.studioLogin=qp;exports.studioResetPassword=Zp;exports.studioStartPasswordReset=Wp;exports.subscribeStore=Bp;exports.syncPublish=mh;exports.transitionToActive=hi;exports.transitionToInit=pi;exports.transitionToLoad=fi;exports.transitionToReady=gi;exports.transitionToUnload=Vd;exports.troubleByTypeReducer=Vf;exports.troubleDataFactory=sc;exports.unloadKosModel=Ru;exports.updateCompanionModelRegistration=oh;exports.updateModelRegistration=sh;exports.updateRegion=Yc;exports.updateTimeZone=Ao;exports.useAmPmValues=zl;exports.useCalendarDayArray=kl;exports.useConfigBean=ly;exports.useConfigProperty=Ml;exports.useContextModel=nm;exports.useContextModelHierarchy=nl;exports.useDateArrays=Dl;exports.useDateProps=my;exports.useDateRelativeConfig=yy;exports.useDateRelativeData=Nl;exports.useDayNames=Ll;exports.useDayOptions=Rl;exports.useDays=jr;exports.useDevice=fl;exports.useFormattedDate=Pl;exports.useFormattedTime=Wl;exports.useFunctionWarmup=by;exports.useHourValues=Yl;exports.useKosCore=dl;exports.useKosDateFormats=wy;exports.useKosModel=B;exports.useKosRegions=Gl;exports.useKosTime=Rr;exports.useKosTimeContext=Mm;exports.useKosTimeFormats=Oy;exports.useKosTimeZones=Ey;exports.useKosTranslation=oy;exports.useKosTranslationContext=Dm;exports.useLocalComputed=Dy;exports.useModelFromHierarchy=lm;exports.useMonths=Al;exports.useMonthsOptions=Cl;exports.useMutationObserver=Ay;exports.useNetworkInterfaceContainer=pl;exports.useOta=ml;exports.usePressGesture=Cy;exports.useProjectReload=Hl;exports.useRegionTimeProps=Ry;exports.useRegionalTimeDate=Fl;exports.useSoftwareInfo=Pr;exports.useSoftwareInfoContext=Im;exports.useStateProperty=Hm;exports.useStorageDeviceContainer=yl;exports.useSuspenseData=Co;exports.useTimeOptions=ql;exports.useTimeProps=Zl;exports.useTimeValues=Ro;exports.useTimer=zm;exports.useTranslationContainer=vl;exports.useTroubleContainerModel=Fr;exports.useTroubleModel=ny;exports.useTroublePresence=iy;exports.useUsbUpdateContainer=wl;exports.useYears=Ur;exports.useYearsOptions=Sl;exports.uuid=Xe;exports.variableToHex=pd;exports.waitForRequest=Jo;exports.whenReady=J;exports.withDevice=Nm;exports.withKosTime=jm;exports.withNetworkInterfaceContainer=Bm;exports.withOta=Km;exports.withProjectReloading=Ly;exports.withSoftwareInfo=_m;exports.withStorageDeviceContainer=Ym;exports.withTranslationContainer=ry;exports.withTroubleContainer=ay;exports.withUsbUpdateContainer=cy;exports.wrapPromise=Bo;
|
|
159
|
+
`,ml=()=>{const e=Ls.type;return B({modelId:e,modelType:Ls.type,options:{}})};function jm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=ml();return M.jsx(r,{...o,children:M.jsx(e,{...t,device:s})})}}function Bm(e,t,s){const o=new Promise(r=>{E.getInstance().whenReady().then(()=>{const{model:n}=E.getInstance().modelManager.createModelInstance(e,t??e,s);return n.whenReady().then(()=>{r(n.modelData)})})});return Ko(o)}function Km(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Pr();return M.jsx(r,{...o,children:M.jsx(e,{...t,kosTime:s})})}}const yl=()=>{const e=Ut.type;return B({modelId:e,modelType:Ut.type,options:{}})};function Gm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=yl();return M.jsx(r,{...o,children:M.jsx(e,{...t,networkInterfaceContainer:s})})}}const bl=()=>{const e=Is.type;return B({modelId:e,modelType:Is.type,options:{}})};function Vm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=bl();return M.jsx(r,{...o,children:M.jsx(e,{...t,oTA:s})})}}function Hm(e,t){g.useEffect(()=>{function s(r){e.current&&!e.current.contains(r.target)&&t()}function o(r){r.key==="Escape"&&t()}return document.addEventListener("mousedown",s),document.addEventListener("keydown",o,!1),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",o,!1)}},[e,t])}function Ym(e){const t=g.useRef(null),s=e.onAlert;return Hm(t,s),M.jsx("div",{ref:t,style:{width:"100%"},children:e.children})}const zm=e=>{var d;const{stateProp:t}=e,[s,o]=g.useState((d=e.stateProp)==null?void 0:d.value),[r,n]=g.useState(!1),[i,c]=g.useState(void 0);return g.useEffect(()=>{async function u(h){try{h&&(await J(h),n(!0))}catch(p){c(p.message)}}u(t)},[t]),g.useEffect(()=>{const u=N(()=>{t&&r&&o(t.value)});return()=>{u()}},[r,t]),[s,{ready:r,error:i}]},vl=()=>{const[e,t]=g.useState(!1),[s,o]=g.useState([]),r=Ze.type,n=B({modelId:r,modelType:Ze.type,options:{}});return g.useEffect(()=>{const i=N(()=>{var c,l;t(((c=n.model)==null?void 0:c.isStorageInserted)??!1),o(((l=n.model)==null?void 0:l.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:e,devices:s}};function qm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=vl();return M.jsx(r,{...o,children:M.jsx(e,{...t,storageDeviceContainer:s})})}}const go=f.createLogger({name:"use-timer"}),Wm=({timerName:e,onTimerExpired:t,onTimerTick:s,timerEventActions:o,autoStart:r})=>{const n=Zc.getTimer(e);g.useEffect(()=>{if(!n){console.warn(`Timer with name ${e} does not exist.`);return}const d=U(Cr,u=>{const{name:h,action:p,remainingTime:w}=u==null?void 0:u.body;h===e&&(p===Rr?t({name:h,action:p,remainingTime:w,timer:n}):o!=null&&o[p]&&o[p]({name:h,action:p,remainingTime:w,timer:n}))});return r&&n.start(),()=>{d.unsubscribe()}},[r,t,o,e,n]),g.useEffect(()=>{if(!n||!s)return;const d=`${Ar}/${e}`,u=U(d,h=>{const{name:p,remainingTime:w}=h==null?void 0:h.body;p===e&&s({name:p,remainingTime:w,timer:n})});return()=>{u.unsubscribe()}},[s,e,n]);const i=g.useCallback(()=>{n?n.start():go.warn(`Timer with name ${e} does not exist.`)},[n,e]),c=g.useCallback(()=>{n?n.reset():go.warn(`Timer with name ${e} does not exist.`)},[n,e]),l=g.useCallback(()=>{n?n.pause():go.warn(`Timer with name ${e} does not exist.`)},[n,e]);return{timer:n,start:i,reset:c,pause:l}},Zm=e=>{const t=/[\\^$.*+?()[\]{}|]/g;return RegExp(t.source).test(e)?e.replace(t,"\\$&"):e},Jm=e=>e instanceof RegExp,Qm=e=>typeof e=="string",Xm=(e,t,s)=>{if(e===""||t==="")return e;let o=t;Jm(o)||(o=new RegExp("("+Zm(o)+")","gi"));const r=e.split(o);for(let n=1,i=r.length;n<i;n+=2)r[n]=s(r[n],n);return r},wl=(e,t,s)=>{let o=e;return Array.isArray(o)||(o=[o]),o.flatMap(r=>Qm(r)?Xm(r,t,s):r)};function ey(e,t){let s=e;return Object.entries(t).forEach(([o,r])=>{const n=new RegExp(`<${o}>(.*?)</${o}>|<${o}/>`,"g");s=wl(s,n,(i,c)=>r.type==="br"?M.jsx("br",{}):g.cloneElement(r,{key:`${o}-${c}`},i))}),s}const ty=e=>{const{i18nKey:t,t:s,defaults:o,components:r,values:n={},context:i}=e,c=s(t,{defaultValue:o,data:n,context:i,returnObjects:!0}),l=ey(c,r||{});return M.jsx("span",{className:e.className,children:l})},je=new Map;function sy(e,t){if(je.has(e)){const s=je.get(e);if(s.status==="finished")return s.result;throw s.promise}else{const s=t().then(r=>{je.set(e,{status:"finished",result:r})},r=>{throw je.set(e,{status:"error",error:r}),r}),o={status:"pending",promise:s};throw je.set(e,o),s}}function Ro(e,t){return sy(e,t)}const oy=async()=>{const e=await Bi(ge.type);return await J(e.model),e.model},ry=async(e,t,s)=>{const o=e.resolveNamespace(t);await J(o);for(const r of s){const n=e.resolveNamespace(r);await J(n),je.set(r,{status:"finished",result:n})}return o},ny=(e,t)=>{const s=[e].flat(),[o,...r]=s,n=Ro(ge.type,oy),i=s.join("__"),c=Ro(i,()=>ry(n,o,r)),l=g.useMemo(()=>({exists:u=>{const h=t!=null&&t.keyPrefix?`${t.keyPrefix}.${u}`:u;return c?c.exists(h):!1}}),[t==null?void 0:t.keyPrefix,c]);return{t:g.useCallback((u,h)=>{const p=t!=null&&t.keyPrefix?`${t.keyPrefix}.${u}`:u;return c?c.resolveKey(p,h):(f.debug(`Translation model ${e} not ready for key: ${p}`),p)},[t==null?void 0:t.keyPrefix,e,c]),i18n:l}},Ml=()=>{const e=ge.type;return B({modelId:e,modelType:ge.type,options:{}})};function iy(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Ml();return M.jsx(r,{...o,children:M.jsx(e,{...t,translationContainer:s})})}}const ay=e=>B({modelId:e,modelType:xt.type}),Ur=()=>B({modelId:ze.type,modelType:ze.type,options:{}}),cy=({troubleType:e,condition:t})=>{const{model:s}=Ur(),[o,r]=g.useState(!1),[n,i]=g.useState([]),c=g.useCallback(()=>{var l,d;return n.length>0&&((l=n[0])!=null&&l.resolvable)?(d=n[0])==null?void 0:d.resolve():Promise.resolve(void 0)},[n]);return g.useEffect(()=>N(()=>{const d=(e?s==null?void 0:s.troubles.getIndexByKey("byType",e):s==null?void 0:s.troubles.data)||[],u=t?d.filter(t):d;r(u.length>0),i(u)}),[t,s,e]),[o,c,n.length>0?n[0]:void 0,n]};function ly(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Ur();return M.jsx(r,{...o,children:M.jsx(e,{...t,troubleContainer:s})})}}const _l=()=>{const e=Bt.type,t=B({modelId:e,modelType:Bt.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,o]=g.useState(!1),[r,n]=g.useState(!1),[i,c]=g.useState([]);return g.useEffect(()=>{const l=N(()=>{var d,u,h;o(((d=t.model)==null?void 0:d.isUsbInserted)??!1),n(((u=t.model)==null?void 0:u.hasAvailableUpdates)??!1),c(((h=t.model)==null?void 0:h.data)??[])});return()=>{l()}},[t.model]),{...t,inserted:s,updateAvailable:r,updates:i}};function dy(e){return t=>{const{model:s,status:o,KosModelLoader:r}=_l();return M.jsx(r,{...o,children:M.jsx(e,{...t,usbUpdateContainer:s})})}}const uy=({path:e,propKey:t})=>{const{status:s}=B({modelType:Ct.type,modelId:e,options:{path:e}}),[o,r]=g.useState(!1),[n,i]=g.useState(),[c,l]=g.useState(""),[d,u]=g.useState(),h=p=>{n&&t&&n.updateProperty(t,p)};return g.useEffect(()=>{var p;s.model&&i(s.model),s.model&&t&&((p=s.model)!=null&&p.props.has(t)?l(s.model.props[t]):u(`property ${t} not found`)),s.ready&&r(s.ready)},[s.ready,s.model,t]),g.useEffect(()=>{t&&v.autorun(()=>{const p=n==null?void 0:n.props[t];l(p||"")})},[n,t]),{config:n,ready:o,value:c,error:d,updateValue:h}},hy=(e,t)=>{switch(t.type){case"UPDATE":return t.payload;default:return e}},El=({configProperty:e,optionsTransformer:t})=>{const[s,o]=g.useState(!1),[r,n]=g.useState(""),[i,c]=g.useReducer(hy,{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}),l=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&(e==null||e.updateProperty(u))},[e]);return g.useEffect(()=>{async function d(u){try{u&&(await J(u),o(!0))}catch(h){n(h.message)}}d(e)},[e]),g.useEffect(()=>{const d=N(()=>{if(e&&s){let u=[];t&&(u=t(e.options)),c({type:"UPDATE",payload:{value:String(e.value),displayValue:e.displayValue,significantValue:e.significantValue,unit:e.unit,options:e.options,mappedOptions:u,updateProperty:e.updateProperty,displayOptions:e==null?void 0:e.displayOptions}})}});return()=>{d()}},[e,t,s]),{...i,configSelectProps:{onChange:l,value:i.value,options:t?i.mappedOptions||[]:i.options||[]},ready:s,error:r}};function gy(e,t){const s=t??new Date().getFullYear(),o=[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:o[e]??0}function fy(e,t){return new Date(e,t,0).getDate()}function Il(e,t){const s=gy(t,e),o=[];for(let r=1;r<=s;r++)o.push(r);return o}function Tl(){return[...Array(12).keys()].map(t=>new Date(0,t).getMonth())}function $l(e=[2018,2028]){const t=[];for(let s=e[0];s<=e[1];s++)t.push(s);return t}function Ol(e,t=[2018,2028]){const s=$l(t);return e==="long"?s:s.map(o=>Number(o.toString().substring(2)))}function jr(e="numeric",t="en-US"){const s=new Intl.DateTimeFormat(t,{month:e,timeZone:"UTC"}).format;return[...Array(12).keys()].map(o=>s(new Date(Date.UTC(0,o,1))))}function py({locale:e="en-US",year:t,month:s,day:o,formatOptions:r={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:n}){const i=s-1,c=new Date(t,i,o),l=new Intl.DateTimeFormat(e,{month:r.month}).format(c),d=new Intl.DateTimeFormat(e,{year:r.year}).format(c),u=new Intl.DateTimeFormat(e,{day:r.day}).format(c);return n?n=="MMDDYY"?`${l} ${u} ${d}`:n==="DDMMYY"?`${u} ${l} ${d}`:n==="YYMMDD"?`${d} ${l} ${u}`:`${d} ${u} ${l}`:new Intl.DateTimeFormat(e,r).format(c)}function oe(e){return e.toString().length===2?new Date(Date.parse(`01 Jan 20${e}`)).getFullYear():e}function my(e){return typeof e=="string"?new Date(Date.parse(`01 ${e.substring(0,3)} 2023`)).getMonth()+1:e}function Dl(e,t,s){const o=oe(t),r=new Date(o,e,1).getDay(),n=new Date(o,e+1,0).getDate();return[...Array(42).keys()].map(c=>c<r||c>n+r-1?{label:"",value:0,disabled:!0}:s[c-r])}function bt(e,t,s){const o=t-1,r=new Date(e,o,s);return new Date(r).getMonth()===o&&new Date(r).getDate()===s}function vt(e,t){return new Date(e,t,0).getDate()}function Sl(e="en-US",t="short"){const s=new Intl.DateTimeFormat(e,{weekday:t}).format;return[...Array(7).keys()].map(o=>s(new Date(Date.UTC(2021,5,o))))}function Cl({locale:e="en-US",year:t=new Date().getFullYear(),month:s=new Date().getMonth(),yearRange:o=[2018,2028],daysOfWeekFilter:r=[],formatOptions:{yearFormat:n="long",monthFormat:i="long",dayFormat:c="short"}={}}){const l=Br(n,o),d=Al(n,o,e),u=Rl(i,e),h=Ll(i,e),p=Kr(t,s),w=Pl(t,s,e,r),b=Fl(s,t,w),_=kl(e,c);return{daysArray:p,monthsArray:u,yearsArray:l,yearsOptionsArray:d,monthsOptionsArray:h,daysOptionsArray:w,calendarDayArray:b,dayNamesArray:_}}function Br(e="long",t=[2018,2028]){return g.useMemo(()=>Ol(e,t),[e,t])}function Al(e="long",t=[2018,2028],s="en-US"){const o=Br(e,t);return g.useMemo(()=>o.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,o])}function Rl(e,t="en-US"){return g.useMemo(()=>jr(e,t),[e,t])}function Ll(e,t="en-US"){const s=g.useMemo(()=>Tl(),[]),o=g.useMemo(()=>jr(e,t),[e,t]);return g.useMemo(()=>[...Array(12).keys()].map(n=>({label:o[n],value:Number(s[n])})),[o,s])}function Kr(e,t){const s=oe(e);return g.useMemo(()=>Il(s,t),[t,s])}const yy=(e,t,s,o=[])=>{const r=new Date(e,t,s).getDay();return o.length>0&&o.includes(r)};function Pl(e,t,s="en-US",o=[]){const r=Kr(e,t);return g.useMemo(()=>r.map(i=>({label:i.toLocaleString(s),value:i,disabled:yy(e,t,i,o)})),[o,s,t,r,e])}function kl(e="en-US",t="short"){return g.useMemo(()=>Sl(e,t),[e,t])}function xl({year:e=new Date().getFullYear(),month:t=new Date().getMonth(),day:s=new Date().getDate(),formatString:o}){const r=t,n=new Date(e,r,s);return{formattedDate:me.format(n,o)}}function Fl(e,t,s){return g.useMemo(()=>Dl(e,t,s),[e,t,s])}var Nl=(e=>(e.MMDDYY="MMDDYY",e.DDMMYY="DDMMYY",e.YYMMDD="YYMMDD",e.YYDDMM="YYDDMM",e))(Nl||{});function by({locale:e="en-US",date:{year:t=new Date().getFullYear(),month:s=new Date().getMonth(),day:o=new Date().getDate()}={year:new Date().getFullYear(),month:new Date().getMonth(),day:new Date().getDate()},formatOptions:{yearFormat:r="long",monthFormat:n="long",dayFormat:i="short",formatString:c="yyyy/MM/dd"}={},filterOptions:{yearsRange:l=[2018,2028],daysOfWeekFilter:d=[]}={}}){const[u,h]=g.useState(t),[p,w]=g.useState(l),[b,_]=g.useState(s),[I,C]=g.useState(o);g.useEffect(()=>{h(t)},[t]),g.useEffect(()=>{_(s)},[s]),g.useEffect(()=>{C(o)},[o]);const{yearsArray:se,yearsOptionsArray:we,monthsArray:rt,monthsOptionsArray:Js,daysArray:Q,daysOptionsArray:Me,calendarDayArray:Qs,dayNamesArray:Xs}=Cl({locale:e,year:u,yearRange:p,month:b,formatOptions:{yearFormat:r,monthFormat:n,dayFormat:i},daysOfWeekFilter:d}),{formattedDate:eo}=xl({year:u,month:b,day:I,formatString:c});return{dateActions:{setYear:h,setYearRange:w,setMonth:_,setDay:C,nextMonth:()=>{const K=b<11?oe(u):oe(u+1),W=b<11?b+1:0;if(!bt(K,W,I)){const _e=vt(K,W);C(_e)}W===0&&h(K),_(W)},previousMonth:()=>{const K=oe(b===0?u-1:u),W=b===0?11:b-1;if(!bt(K,W,I)){const _e=vt(K,W);C(_e)}W===11&&h(K),_(W)},nextYear:()=>{const K=u<p[1]?u+1:p[0],W=oe(K);if(bt(W,b,I))h(K);else{const _e=vt(oe(u+1),b);C(_e),h(K)}},previousYear:()=>{const K=u>p[0]?u-1:p[0],W=oe(K);if(bt(W,b,I))h(K);else{const _e=vt(oe(u-1),b);C(_e),h(K)}}},dateState:{year:u,yearRange:p,month:b,day:I,yearsArray:se,yearsOptionsArray:we,monthsArray:rt,monthsOptionsArray:Js,daysArray:Q,daysOptionsArray:Me,calendarDayNames:Xs,calendarDayArray:Qs,formattedDate:eo}}}function Ul({date:e=new Date,dateFormat:t,timeFormat:s,options:o={}}){const[r,n]=g.useState("Formatting Time..."),[i,c]=g.useState("Formatting Date..."),l=!!o.ignoreDateFormat,{model:d,ready:u}=B({modelId:V.type,modelType:V.type,options:{}}),h=typeof e=="string"?me.parseISO(e):e;return g.useEffect(()=>{l?c(""):t?c(me.format(h,t)):u&&c(me.format(h,d!=null&&d.selectedDateFormat?d==null?void 0:d.selectedDateFormat:""))},[l,e,t,h,d,u]),g.useEffect(()=>{s?n(me.format(h,s)):u&&n(me.format(h,d!=null&&d.selectedTimeFormat?d==null?void 0:d.selectedTimeFormat:""))},[e,s,h,d,u]),{formattedDate:i,formattedTime:r}}const jl=({secondsFromMidnight:e=0})=>{const[t,s]=g.useState(0),[o,r]=g.useState(0),[n,i]=g.useState(0),[c,l]=g.useState(new Date),{formattedTime:d}=Ul({date:c,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const u=Number(e),h=Math.floor(u/3600),p=Math.floor(u%3600/60),w=u%60;s(h),r(p),i(w);const b=new Date;b.setHours(0,0,0,0);const _=new Date(b.getTime()+u*1e3);l(new Date(_))},[e]),{hours:t,minutes:o,seconds:n,formattedTime:d,timeActions:{setHours:s,setMinutes:r,setSeconds:i}}},vy=({configProperty:e})=>{const{value:t}=El({configProperty:e}),s=parseInt(t||"0",10),{hours:o,minutes:r,seconds:n,formattedTime:i,timeActions:c}=jl({secondsFromMidnight:s}),l=g.useRef();return g.useEffect(()=>{const d=o*3600+r*60+n;return l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{e&&e.updateProperty(d.toString())},100),()=>{l.current&&clearTimeout(l.current)}},[e,o,r,n]),{hours:o,minutes:r,seconds:n,formattedTime:i,timeActions:c}};function wy(e,t={}){const{intervalMs:s=5*60*1e3,immediate:o=!0}=t;g.useEffect(()=>{const r=()=>{try{e({__warmup:!0})}catch{}};o&&("requestIdleCallback"in window?requestIdleCallback(r):setTimeout(r,1));const n=s?setInterval(r,s):null;return()=>{n&&clearInterval(n)}},[e,s,o])}const My=e=>M.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),_y=(e=My)=>{const[t,s]=g.useState([]),[o,r]=g.useState(),{model:n,ready:i}=B({modelType:V.type,modelId:V.type,options:{}});g.useEffect(()=>{const l=N(()=>{s((n==null?void 0:n.dateFormatOptions.map(e))||[])});return()=>{l()}},[n,i,e]),g.useEffect(()=>{const l=N(()=>{n!=null&&n.dateFormatId&&(n!=null&&n.selectedDateFormat)&&r({id:n==null?void 0:n.dateFormatId,value:n==null?void 0:n.selectedDateFormat})});return()=>{l()}},[n==null?void 0:n.selectedDateFormat,n==null?void 0:n.dateFormatId]);const c=g.useCallback(l=>{var u;let d="";typeof l=="string"?d=l:(u=l==null?void 0:l.target)!=null&&u.value&&(d=l.target.value),d&&(n==null||n.setSelectedDateFormat(d))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(l=>l.id))??[],regionModel:n,selectedDateFormat:(o==null?void 0:o.value)||"",dateFormatId:(o==null?void 0:o.id)||"",updateDateFormat:c,props:{onChange:c,value:(o==null?void 0:o.id)||"",options:t}}},Ey=e=>M.jsx("option",{title:e,value:e,children:e},e),Bl="kos:service:region:settings",Kl="timeZone",Iy=`${Bl}-${Kl}`,Ty=(e=Ey)=>{const[t,s]=g.useState([]),[o,r]=g.useState(""),{model:n,ready:i}=B({modelType:V.type,modelId:V.type,options:{}}),c=Re.factory(Iy)({path:Bl,attribute:Kl});g.useEffect(()=>{const d=N(()=>{s((n==null?void 0:n.timeZones.map(e))||[]),n!=null&&n.timeZones.length&&Ao(n==null?void 0:n.timeZones[0])});return()=>{d()}},[n,i,e]),g.useEffect(()=>{const d=N(()=>{r(c.value||"")});return()=>{d()}},[c.value]);const l=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&Ao(u)},[]);return{options:t,raw:(n==null?void 0:n.timeZones)??[],regionModel:n,selectedTimeZone:o,timeZones:(n==null?void 0:n.timeZones)??[],updateTimeZone:l,selectProps:{onChange:l,value:o,options:t}}},Gl="kos:service:region",Vl="regionId",$y=`${Gl}-${Vl}`,Oy=e=>M.jsx("option",{title:e,value:e,children:e},e),Hl=(e=Oy)=>{const[t,s]=g.useState([]),[o,r]=g.useState("factory"),{model:n,ready:i}=B({modelType:V.type,modelId:V.type,options:{}}),c=Re.factory($y)({path:Gl,attribute:Vl});g.useEffect(()=>{const d=N(()=>{s((n==null?void 0:n.availableRegions.map(e))||[])});return()=>{d()}},[n,i,e]),g.useEffect(()=>{const d=N(()=>{r(c.value||"factory")});return()=>{d()}},[c.value]);const l=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&qc(u)},[]);return{raw:(n==null?void 0:n.availableRegions)??[],regionModel:n,regionData:n==null?void 0:n.selectedRegion,selectedRegion:o,updateRegion:l,regionSelectProps:{onChange:l,value:o,options:t}}},Dy=e=>M.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),Sy=(e=Dy)=>{const[t,s]=g.useState([]),[o,r]=g.useState(),{model:n,ready:i}=B({modelType:V.type,modelId:V.type,options:{}});g.useEffect(()=>{const l=N(()=>{s((n==null?void 0:n.timeFormatOptions.map(e))||[])});return()=>{l()}},[n,i,e]),g.useEffect(()=>{const l=N(()=>{n!=null&&n.timeFormatId&&(n!=null&&n.selectedTimeFormat)&&r({id:n==null?void 0:n.timeFormatId,value:n==null?void 0:n.selectedTimeFormat})});return()=>{l()}},[n==null?void 0:n.selectedTimeFormat,n==null?void 0:n.timeFormatId]);const c=g.useCallback(l=>{var u;let d="";typeof l=="string"?d=l:(u=l==null?void 0:l.target)!=null&&u.value&&(d=l.target.value),d&&(n==null||n.setSelectedTimeFormat(d))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(l=>l.id))??[],regionModel:n,selectedTimeFormat:(o==null?void 0:o.value)??"",timeFormatId:(o==null?void 0:o.id)??"",updateTimeFormat:c,props:{onChange:c,value:(o==null?void 0:o.id)??"",options:t}}},Cy=(e,t)=>g.useMemo(()=>er(e),t),Ay={config:{attributes:!0,childList:!0,subtree:!0}};function Ry(e,t,s=Ay){const[o,r]=g.useState(null);g.useEffect(()=>{if(!t||typeof t!="function")throw new Error("A valid callback function is required");const n=new MutationObserver(t);r(n)},[t,s,r]),g.useEffect(()=>{if(!o)return()=>{};if(!e)throw new Error("A valid DOM element is required");const{config:n}=s;try{o.observe(e,n)}catch(i){f.error(i)}return()=>{o&&o.disconnect()}},[o,e,s])}const Yl={validateStart:function(e){return!0},validateStop:function(e){const t=e.event.currentTarget.getBoundingClientRect(),[s,o]=e.xy;return s<t.left||s>t.right||o<t.top||o>t.bottom}},fo=f.createLogger({name:"usePressGesture",group:"kos-hooks"});function Ly({onPressed:e,onRelease:t,intersectionStrategy:s=Yl}){const o=g.useRef(!1),r=od.useGesture({onDragStart:l=>{fo.info("onDragStart",l.type),s.validateStart(l)&&(e&&e(),o.current=!0)},onDrag:l=>{fo.info("onDrag",l.type),o.current&&s.validateStop(l)&&(t&&t(),o.current=!1)},onDragEnd:l=>{fo.info("onDragEnd",l.type),o.current&&t&&(t(),o.current=!1)}}),n=()=>{e&&e(),o.current=!0},i=()=>{o.current&&t&&(t(),o.current=!1)},c=()=>{o.current&&t&&(t(),o.current=!1)};return{dom:r,mesh:()=>({onPointerDown:n,onPointerUp:i,onPointerOut:c})}}const zl=()=>{const[e,t]=g.useState(!1),s=E.getInstance();return g.useEffect(()=>{const o=N(()=>{s&&s.reloading!==e&&t(s.reloading)});return()=>{o()}},[s,e]),[e]};function ql(e=!1,t="2-digit"){return g.useMemo(()=>{const s=e?12:24;return Array.from({length:s},(o,r)=>{const n=e&&r===0?12:r%s;return{id:r,label:t==="2-digit"?n.toString().padStart(2,"0"):n.toString()}})},[t,e])}function Lo(e,t="2-digit",s=0,o=0){return g.useMemo(()=>Array.from({length:e},(r,n)=>{const i=String(n+s);return{id:n+o,label:t==="2-digit"?i.padStart(2,"0"):i}}),[e,s,o,t])}function Wl(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 Zl({formatOptions:{hour12:e=!0,hour:t="2-digit",minute:s="2-digit",second:o="2-digit"}={hour12:!0,hour:"2-digit",minute:"2-digit",second:"2-digit"},locale:r="en-US"}){const n=ql(e,t),i=Lo(60,s),c=Lo(60,o),l=Wl(r);return{hourOptions:n,minuteOptions:i,secondOptions:c,amPmOptions:l}}function Jl(e,t){return me.format(e,t)}function Ql({formatOptions:e,initialDate:t=new Date,locale:s="en-US",format:o="HH:mm"}){const[r,n]=g.useState(t),i=g.useCallback(_=>{n(I=>{const C=new Date(I);return C.setHours(Number(_)),C})},[]),c=g.useCallback(_=>{n(I=>{const C=new Date(I);return C.setMinutes(Number(_)),C})},[]),l=g.useCallback(_=>{n(I=>{const C=new Date(I);return C.setSeconds(Number(_)),C})},[]),d=g.useCallback(_=>{const I=new Date(_);n(I)},[]),u=Jl(r,o),{hourOptions:h,minuteOptions:p,secondOptions:w,amPmOptions:b}=Zl({formatOptions:e,locale:s});return{amPmOptions:b,formattedTime:u,hourOptions:h,minuteOptions:p,secondOptions:w,setHours:i,setMinutes:c,setSeconds:l,setTime:d,time:new Date(r)}}const Py=e=>{const{regionModel:t}=Hl(),s=g.useMemo(()=>({hour12:t==null?void 0:t.is12HourTimeFormat}),[t==null?void 0:t.is12HourTimeFormat]);return Ql({...e,locale:t==null?void 0:t.regionId,format:t==null?void 0:t.selectedTimeFormat,formatOptions:s})};function ky(e){return t=>{const[s]=zl();return s?M.jsx(ol,{message:"Wait a moment while your project reloads..."}):M.jsx(e,{...t})}}const In=f.createLogger({name:"studio-properties-service",group:"Services"}),xy="/api/kos/studio/properties",Xl=async e=>{if(In.debug("sending GET for studio-properties"),!e)throw In.error("connectionId is undefined"),new Error("connectionId is undefined");return await Le.get(xy,{},{destinationAddress:e,timeout:500})},Fy=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:Xl},Symbol.toStringTag,{value:"Module"}));var Ny=Object.defineProperty,Uy=Object.getOwnPropertyDescriptor,jy=(e,t,s,o)=>{for(var r=o>1?void 0:o?Uy(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(r=(o?i(t,s,r):i(r))||r);return o&&r&&Ny(t,s,r),r};const ed="studio-properties-model",By="/kos/studio/properties",Tn={"kos.studio.tool.legacy":1};let Po=class{constructor(e,t,s){a(this,"id");a(this,"connectionId");a(this,"unsubscribe",null);a(this,"logger");a(this,"data");this.id=e,this.logger=s.logger,this.data=ye(),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=Vt.getInstance().subscribeTopic({topic:By,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[e,t]=await Xl(this.connectionId);if(e){this.logger.error(`Error loading studio-properties: ${e}`),this.data.setValues(Tn);return}if(t){const s=Object.keys(t).reduce((o,r)=>(o[r]=t[r]??r,o),{});this.data.setValues(s??Tn),f.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(e){return this.data[e]}createObservableProperty(e){return er(()=>this.get(e))}};Po=jy([O(ed)],Po);const Ky=new ae({class:Po,type:ed});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>v.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>v.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>xo.observer});exports.AuthState=zi;exports.BrowserKosRouter=oa;exports.BrowserRouter=Gs;exports.CanvasDispatcher=We;exports.CanvasDispatcherServices=Qf;exports.CanvasRenderer=_r;exports.CanvasStreamer=Fm;exports.CanvasStreamerBase=pl;exports.ChildModels=Mt;exports.ConfigBean=Ct;exports.CoreExtensionManager=Kp;exports.CoreModels=Sr;exports.CreateModelTranslationsContext=dl;exports.CreateModelTranslationsProvider=fm;exports.DateDisplayFormat=Nl;exports.DateHelpers=pd;exports.DependencyLifecycle=x;exports.DependencyModels=P;exports.Device=Ls;exports.DeviceServices=dp;exports.DomIntersectionStrategy=Yl;exports.EVENT_KOS_MODEL_READY=jo;exports.EVENT_TROUBLE_ADDED=$h;exports.EVENT_TROUBLE_REMOVED=Oh;exports.EXTENSION_TROUBLE_DATA_MAPPER=_s;exports.EXTENSION_TROUBLE_MAPPER=Wt;exports.ErrorBoundaryWithFallback=rl;exports.EventBus=ad;exports.ExtensionManager=A;exports.FUTURE_CONTAINER_MODEL_TYPE=Ca;exports.FUTURE_MODEL_TYPE=wa;exports.FUTURE_NOT_ASSIGNED=sr;exports.FeatureFlagService=Hn;exports.FetchError=ce;exports.FutureContainerFactory=be;exports.FutureContainerModel=Ra;exports.FutureEndState=Ve;exports.FutureFactory=st;exports.FutureHandler=lr;exports.FutureManager=De;exports.FutureModel=$a;exports.FutureService=wt;exports.HEADER_CACHE_CONTROL=An;exports.HEADER_CONTENT_TYPE=Cn;exports.HEADER_DESTINATION_ADDR=fe;exports.HEADER_FOS_REQUEST_ID=Rn;exports.HEADER_METHOD=Fs;exports.HEADER_ORDERED=No;exports.HEADER_REQUEST_ID=Kt;exports.HEADER_REQUEST_TYPE=le;exports.HEADER_RESPONSE_ID=Ns;exports.HEADER_SOURCE_ADDR=Sn;exports.HEADER_TOPIC=Dn;exports.HEADER_URL=Qe;exports.HEADER_WORK_TRACKER=Uo;exports.KOS_MODEL_ID=hs;exports.KeyValue=pr;exports.KeyValueServices=_g;exports.Kos=H;exports.KosConfigPropertySpec=Re;exports.KosContainerIndex=Xo;exports.KosContextBean=ea;exports.KosContextManager=k;exports.KosCore=E;exports.KosCoreModelPropertyMapper=re;exports.KosDataContainer=ta;exports.KosDependencyTypes=Ad;exports.KosExtensionUtils=Cu;exports.KosFeatureFlags=md;exports.KosFetchMethods=Ei;exports.KosGlobalConfig=Yo;exports.KosLog=f;exports.KosMockEvents=kn;exports.KosModel=xi;exports.KosModelCollectionProvider=lm;exports.KosModelContainer=de;exports.KosModelContext=Ws;exports.KosModelEvents=D;exports.KosModelFactory=$t;exports.KosModelLoader=cl;exports.KosModelLoaderDisplay=ll;exports.KosModelManager=Ui;exports.KosModelProvider=nl;exports.KosModelRegistrationFactory=ae;exports.KosModelRegistry=Co;exports.KosModelState=y;exports.KosModelSymbol=di;exports.KosModelVisitor=eh;exports.KosObservableData=Zi;exports.KosRegistration=_h;exports.KosSingletonRegistration=Eh;exports.KosTime=vs;exports.KosTimeContext=kr;exports.KosTimeProvider=_m;exports.KosTimeServices=$g;exports.KosTimer=Wc;exports.KosToken=sa;exports.KosTranslationProvider=Sm;exports.KosTranslations=wc;exports.KosWSTransportStatus=ki;exports.KosWsEvents=Gt;exports.LOGIN_HOST=Ln;exports.LOGIN_URL=rd;exports.LoadingMessage=ol;exports.LogBlock=kt;exports.LogBlockContainer=Hs;exports.LogConfig=Et;exports.LogStream=Dt;exports.LogStreamContainer=qt;exports.LogStreamServices=Fg;exports.MODEL_DELETION_DELAY=Ni;exports.MiddlewareChain=Wi;exports.ModelEffects=$e;exports.MultipleFutureHandler=eg;exports.NestedModelContext=Zs;exports.NetworkInterface=Tr;exports.NetworkInterfaceContainer=Ut;exports.NetworkInterfaceServices=wp;exports.ObservableData=ye;exports.Ota=Is;exports.OutsideAlerter=Ym;exports.PLUGIN_EXTENSION_NAME=Au;exports.PORT=Pn;exports.PROFILE_LOG_DEBUG=Zn;exports.PROFILE_LOG_INFO=Jn;exports.PROFILE_RELAX_STORE_VALIDATION=bd;exports.PROFILE_TOOLS_PREVIEW=Wn;exports.ParentModel=_t;exports.PluginExtensionManager=Ru;exports.ProgressBar=nm;exports.ReferenceConfig=is;exports.RegionInfo=V;exports.RegionServices=Fh;exports.RegistrationManager=$;exports.Registry=jp;exports.STATUS=Fo;exports.ServiceFactory=Y;exports.SingletonKosModelRegistrationFactory=pe;exports.SoftwareInfo=Ts;exports.SoftwareInfoContext=Fr;exports.SoftwareInfoProvider=Tm;exports.SoftwareInfoServices=bf;exports.StateBean=Ft;exports.StateBeanServices=If;exports.StateProp=br;exports.StatePropServices=Pf;exports.StorageDevice=ks;exports.StorageDeviceContainer=Ze;exports.StorageDeviceServices=Tp;exports.StudioProperties=Ky;exports.StudioPropertiesServices=Fy;exports.SubscriptionHandlers=G;exports.TIMER_END=Rr;exports.TIMER_EVENT=Cr;exports.TOPIC_TIMER_TICK_EVENT=Ar;exports.TimerManager=Zc;exports.TokenContext=fl;exports.TokenProvider=Om;exports.Topics=Ot;exports.Trans=ty;exports.TransitionMap=as;exports.Transitions=qo;exports.Translation=Ds;exports.TranslationContainer=ge;exports.TranslationContainerContext=Nr;exports.TranslationContext=Hf;exports.TransportFactory=wo;exports.Trouble=xt;exports.TroubleContainer=ze;exports.TroubleServices=of;exports.Troubles=X;exports.UsbUpdate=Dr;exports.UsbUpdateContainer=Bt;exports.UsbUpdateServices=Pp;exports.WS_EVENT_TYPE=Mc;exports.WebSocketEvents=Tt;exports.WebSocketTransport=Vt;exports.WsEventFactory=wr;exports.acceptOrgInvitation=sl;exports.addDaysToDate=Nn;exports.addFuture=_a;exports.addMonthsToDate=Fn;exports.api=Oa;exports.applyMixins=ld;exports.arraysEqual=dd;exports.buildConfigBeanModel=Ch;exports.buildFuture=hr;exports.buildFutureModel=Ia;exports.cancelFuture=Ea;exports.convert=ar;exports.convertFileSizeRaw=cd;exports.convertWithUnits=Gh;exports.createBaseMessage=$i;exports.createBroadcastMessageResponse=Ci;exports.createClient=Jo;exports.createFosBaseMessage=Ti;exports.createHeaders=yo;exports.createKosHtpMessageResponse=Ai;exports.createKosMessage=Di;exports.createKosMessageResponse=Ri;exports.createMessageBody=ve;exports.createModelDependency=bi;exports.createOptionKey=Rd;exports.createPropKey=Se;exports.createReadableStream=bo;exports.createStudioMessage=Ii;exports.createStudioMessageRequest=Oi;exports.createStudioMessageResponse=Si;exports.debounce=Vn;exports.deleteFuture=Ma;exports.destroyKosModel=Oe;exports.evaluateScopes=da;exports.executeChildrenModelLifecycle=Mi;exports.executeDependentModelLifecycle=ct;exports.executeListLifecycle=wi;exports.fetchModel=Bm;exports.findModel=xu;exports.findModels=Ki;exports.formatDate=Bn;exports.formatDateSince=xn;exports.formatDateTime=Gn;exports.formatTime=Kn;exports.getAllKosCompanionModels=Nu;exports.getCalendarMonthArray=Dl;exports.getConfigBean=la;exports.getDayStrings=Sl;exports.getDays=fy;exports.getDaysArray=Il;exports.getDaysInMonth=Ho;exports.getDependenciesByLifecycle=vi;exports.getFormattedDate=py;exports.getFormattedMonth=my;exports.getFormattedMonthsArray=jr;exports.getFormattedYear=oe;exports.getFormattedYearsArray=Ol;exports.getFutures=ag;exports.getKosCompanionModel=Fu;exports.getKosLocalizationDescriptor=pc;exports.getKosMessageLogging=si;exports.getKosModel=Bi;exports.getKosModelSync=Ae;exports.getKosModelType=ku;exports.getKosSessionKey=Xi;exports.getLastDayOfMonth=vt;exports.getLocalizationDescriptor=xf;exports.getLogLevel=ti;exports.getLogMessageToStudio=oi;exports.getMessageBody=vo;exports.getMonthsArray=Tl;exports.getObservableCompanions=Uu;exports.getQueryParams=ee;exports.getTranslations=fc;exports.getYearsArray=$l;exports.hasDecimals=aa;exports.hasKosProfile=po;exports.hslStringToHex=zn;exports.hslToHex=Yn;exports.initKosProvider=mm;exports.isBoolean=rr;exports.isKosCompanionTypeFactory=Fi;exports.isKosDataModel=It;exports.isKosLoggingEnabled=Md;exports.isKosModel=te;exports.isKosModelContainer=Wo;exports.isKosModelReady=fs;exports.isLeapYear=Vo;exports.isLocalRefId=mh;exports.isNumber=js;exports.isPrintable=zd;exports.isValidDate=bt;exports.kosAction=z;exports.kosAutoEffect=N;exports.kosChild=ie;exports.kosCompanion=jd;exports.kosComputed=er;exports.kosConfigBean=Bs;exports.kosConfigProperty=Xh;exports.kosContext=Bd;exports.kosDependency=Ce;exports.kosEffect=na;exports.kosFuture=Lr;exports.kosLogger=Kd;exports.kosModel=O;exports.kosModelEffect=ui;exports.kosObservable=tr;exports.kosParentAware=Us;exports.kosReference=Gd;exports.kosStateBean=qp;exports.kosStateProp=Wp;exports.kosSubscribe=Vd;exports.kosTopicHandler=R;exports.kosWhen=_o;exports.login=Xc;exports.mapConfigBeanModelToDto=fa;exports.mapDataToModel=mo;exports.mapDtoToConfigBeanModel=ha;exports.mapDtoToFutureModel=ur;exports.mapDtoToFutureOptions=dr;exports.mapUpdateDtoToConfigBeanModel=ga;exports.modelEventTopicFactory=ci;exports.modelFactory=et;exports.modelTypeEventTopicFactory=li;exports.modifyConfigBean=ca;exports.modifyFuture=cg;exports.pairedClientHeartbeat=ah;exports.pipe=Qi;exports.preloadKosModel=Ku;exports.processId=fd;exports.processMiddleware=oh;exports.registerCompanionModel=Bu;exports.registerCoreModels=Hc;exports.registerExtensionPoint=zo;exports.registerKosModel=Vi;exports.registerLegacyModel=Gi;exports.resetKosModel=ji;exports.resetPassword=tl;exports.resolveBaseUrl=qi;exports.resolveChild=_i;exports.resolveContainerDeltas=ud;exports.resolveItemListDeltas=gd;exports.resolveKosCompanion=Mo;exports.resolveKosContext=vh;exports.resolveKosProfiles=Xn;exports.resolveListDeltas=hd;exports.resolveServiceUrl=q;exports.resolveVariable=qn;exports.retryWithExponentialBackoff=lh;exports.sendAsyncIntent=Th;exports.sendBroadcastMessage=hu;exports.sendIntent=Ih;exports.sendKosHttpMessageResponse=Pi;exports.sendKosMessage=lu;exports.sendKosMessageResponse=Li;exports.sendRequest=yh;exports.sendStudioMessage=uu;exports.sendStudioMessageRequest=du;exports.startPasswordReset=el;exports.stringComponentInsert=wl;exports.studioAcceptOrgInvitation=Xp;exports.studioLogin=Zp;exports.studioResetPassword=Qp;exports.studioStartPasswordReset=Jp;exports.subscribeStore=Gp;exports.syncPublish=bh;exports.transitionToActive=fi;exports.transitionToInit=yi;exports.transitionToLoad=mi;exports.transitionToReady=pi;exports.transitionToUnload=Yd;exports.troubleByTypeReducer=Yf;exports.troubleDataFactory=rc;exports.unloadKosModel=Pu;exports.updateCompanionModelRegistration=nh;exports.updateModelRegistration=rh;exports.updateRegion=qc;exports.updateTimeZone=Ao;exports.useAmPmValues=Wl;exports.useCalendarDayArray=Fl;exports.useConfigBean=uy;exports.useConfigProperty=El;exports.useContextModel=am;exports.useContextModelHierarchy=al;exports.useDateArrays=Cl;exports.useDateProps=by;exports.useDateRelativeConfig=vy;exports.useDateRelativeData=jl;exports.useDayNames=kl;exports.useDayOptions=Pl;exports.useDays=Kr;exports.useDevice=ml;exports.useFormattedDate=xl;exports.useFormattedTime=Jl;exports.useFunctionWarmup=wy;exports.useHourValues=ql;exports.useKosCore=hl;exports.useKosDateFormats=_y;exports.useKosModel=B;exports.useKosRegions=Hl;exports.useKosTime=Pr;exports.useKosTimeContext=Em;exports.useKosTimeFormats=Sy;exports.useKosTimeZones=Ty;exports.useKosTranslation=ny;exports.useKosTranslationContext=Cm;exports.useLocalComputed=Cy;exports.useModelFromHierarchy=um;exports.useMonths=Rl;exports.useMonthsOptions=Ll;exports.useMutationObserver=Ry;exports.useNetworkInterfaceContainer=yl;exports.useOta=bl;exports.usePressGesture=Ly;exports.useProjectReload=zl;exports.useRegionTimeProps=Py;exports.useRegionalTimeDate=Ul;exports.useSoftwareInfo=xr;exports.useSoftwareInfoContext=$m;exports.useStateProperty=zm;exports.useStorageDeviceContainer=vl;exports.useSuspenseData=Ro;exports.useTimeOptions=Zl;exports.useTimeProps=Ql;exports.useTimeValues=Lo;exports.useTimer=Wm;exports.useTranslationContainer=Ml;exports.useTroubleContainerModel=Ur;exports.useTroubleModel=ay;exports.useTroublePresence=cy;exports.useUsbUpdateContainer=_l;exports.useYears=Br;exports.useYearsOptions=Al;exports.uuid=Xe;exports.variableToHex=yd;exports.waitForRequest=Qo;exports.whenReady=J;exports.withDevice=jm;exports.withKosTime=Km;exports.withNetworkInterfaceContainer=Gm;exports.withOta=Vm;exports.withProjectReloading=ky;exports.withSoftwareInfo=Im;exports.withStorageDeviceContainer=qm;exports.withTranslationContainer=iy;exports.withTroubleContainer=ly;exports.withUsbUpdateContainer=dy;exports.wrapPromise=Ko;
|
|
160
160
|
//# sourceMappingURL=index.cjs.map
|