@kosdev-code/kos-ui-sdk 2.0.8 → 2.0.9

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.
Files changed (72) hide show
  1. package/common/constants/index.d.ts +1 -0
  2. package/common/constants/index.d.ts.map +1 -1
  3. package/common/events/eventBus.d.ts +42 -0
  4. package/common/events/eventBus.d.ts.map +1 -1
  5. package/core/core/decorators/kosModel.d.ts +3 -16
  6. package/core/core/decorators/kosModel.d.ts.map +1 -1
  7. package/core/core/kos-container-model.d.ts +8 -0
  8. package/core/core/kos-container-model.d.ts.map +1 -1
  9. package/core/core/kos-data-container.d.ts +6 -0
  10. package/core/core/kos-data-container.d.ts.map +1 -1
  11. package/core/core/kosModel.d.ts +23 -20
  12. package/core/core/kosModel.d.ts.map +1 -1
  13. package/core/core/kosModelManager.d.ts.map +1 -1
  14. package/core/core/log/log.d.ts.map +1 -1
  15. package/core/core/model/apply-kos-dev-tool-support.d.ts +2 -0
  16. package/core/core/model/apply-kos-dev-tool-support.d.ts.map +1 -0
  17. package/core/core/model/kos-child-resolver.d.ts +10 -0
  18. package/core/core/model/kos-child-resolver.d.ts.map +1 -0
  19. package/core/core/model/kos-companion-model-manager.d.ts +14 -0
  20. package/core/core/model/kos-companion-model-manager.d.ts.map +1 -0
  21. package/core/core/model/kos-effects-manager.d.ts +14 -0
  22. package/core/core/model/kos-effects-manager.d.ts.map +1 -0
  23. package/core/core/model/kos-fsm-manager.d.ts +24 -0
  24. package/core/core/model/kos-fsm-manager.d.ts.map +1 -0
  25. package/core/core/model/kos-logger-factory.d.ts +9 -0
  26. package/core/core/model/kos-logger-factory.d.ts.map +1 -0
  27. package/core/core/model/kos-model-component-factory.d.ts +23 -0
  28. package/core/core/model/kos-model-component-factory.d.ts.map +1 -0
  29. package/core/core/model/kos-offline-queue.d.ts +17 -0
  30. package/core/core/model/kos-offline-queue.d.ts.map +1 -0
  31. package/core/core/model/kos-online-lifecycle-manager.d.ts +12 -0
  32. package/core/core/model/kos-online-lifecycle-manager.d.ts.map +1 -0
  33. package/core/core/model/kos-subscription-manager.d.ts +18 -0
  34. package/core/core/model/kos-subscription-manager.d.ts.map +1 -0
  35. package/core/core/model/logger-utils.d.ts +9 -0
  36. package/core/core/model/logger-utils.d.ts.map +1 -0
  37. package/core/core/model/model-introspection-utils.d.ts +5 -0
  38. package/core/core/model/model-introspection-utils.d.ts.map +1 -0
  39. package/core/types/utils/kos-fetch.d.ts +2 -0
  40. package/core/types/utils/kos-fetch.d.ts.map +1 -1
  41. package/core/util/array-utils.d.ts +2 -0
  42. package/core/util/array-utils.d.ts.map +1 -0
  43. package/core/util/await-first-matching-when.d.ts +5 -0
  44. package/core/util/await-first-matching-when.d.ts.map +1 -0
  45. package/core/util/index.d.ts +1 -0
  46. package/core/util/index.d.ts.map +1 -1
  47. package/core/util/kos-fetch.d.ts.map +1 -1
  48. package/core/util/kos-message-utils.d.ts +1 -1
  49. package/core/util/kos-message-utils.d.ts.map +1 -1
  50. package/core/util/kos-model-utils.d.ts +1 -0
  51. package/core/util/kos-model-utils.d.ts.map +1 -1
  52. package/core/util/kos-service-request.d.ts.map +1 -1
  53. package/core/util/model-utils.d.ts +3 -0
  54. package/core/util/model-utils.d.ts.map +1 -1
  55. package/core/util/service-factory.d.ts.map +1 -1
  56. package/index.cjs +42 -41
  57. package/index.cjs.map +1 -1
  58. package/index.js +3771 -3369
  59. package/index.js.map +1 -1
  60. package/models/models/trouble-container/trouble-container-model.d.ts +1 -1
  61. package/models/models/trouble-container/trouble-container-model.d.ts.map +1 -1
  62. package/models/utils/client.d.ts +4 -0
  63. package/models/utils/client.d.ts.map +1 -1
  64. package/models/utils/index.d.ts +1 -0
  65. package/models/utils/index.d.ts.map +1 -1
  66. package/models/utils/model-event-utils.d.ts +3 -0
  67. package/models/utils/model-event-utils.d.ts.map +1 -0
  68. package/models/utils/service.d.ts +4 -0
  69. package/models/utils/service.d.ts.map +1 -1
  70. package/package.json +2 -2
  71. package/ui/hooks/use-function-warmup.d.ts +34 -17
  72. package/ui/hooks/use-function-warmup.d.ts.map +1 -1
package/index.cjs CHANGED
@@ -1,79 +1,80 @@
1
- "use strict";var Sl=Object.defineProperty;var Al=(e,t,s)=>t in e?Sl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var a=(e,t,s)=>(Al(e,typeof t!="symbol"?t+"":t,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T=require("loglevel"),w=require("mobx"),m=require("robot3"),me=require("date-fns"),_=require("@emotion/react/jsx-runtime"),Cl=require("@emotion/styled"),Rl=require("react-dom"),Ie=require("@emotion/react"),g=require("react"),an=require("mobx-react-lite"),Ll=require("@use-gesture/react"),Rs="method",cn="topic",We="url",xt="request-id",Ls="response-id",Do="status",ge="dst-addr",ln="src-addr",ie="type",So="ordered",Ao="tracker",dn="Content-Type",un="Cache-Control",hn="requestId",gn=process.env.KOS_LOGIN_URL||"http://localhost",fn=process.env.KOS_APP_PORT||"8080",Pl=`${gn}:${fn}`,cs="{MODEL_ID}";var Nt=(e=>(e.SEND="/ws/log/msg/send",e.RECEIVED="/ws/log/msg/receive",e))(Nt||{}),mn=(e=>(e.MSG_RECEIVE="/mock/msg/receive",e))(mn||{});T.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const L=globalThis.kos.subscriptions,kl=()=>Symbol("eventKey");function F(e,t){const s=kl();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 K(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.`),K(n,i)})}else T.debug(`Performing async publish for ${e}`),L[e][r]({body:t,headers:s})}),{eventType:e,subscribers:o}}function xl(){T.warn("Resetting event bus"),Object.keys(L).forEach(e=>delete L[e])}const Nl=Object.freeze(Object.defineProperty({__proto__:null,publish:K,reset:xl,subscribe:F},Symbol.toStringTag,{value:"Module"})),Fl=(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 Co(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 Ft(){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 Ul(e,t){t.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(o=>{const r=Object.getOwnPropertyDescriptor(s.prototype,o);Object.defineProperty(e.prototype,o,r)})})}const Ro=(e,t)=>{const s=e.map(n=>n.id);return t.map(n=>n.id).filter(n=>!s.includes(n))},jl=({container:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o),c=Ro(n,e.data).map(s).filter(Boolean);e.removeAll(c);const l=n.map(t).filter(Boolean);e.addAll(l)},Bl=({container:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o);Ro(n,e.models).forEach(s),n.forEach(t)},Kl=({items:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o);Ro(n,e).forEach(s),n.forEach(t)},Gl=(e,t="parent-")=>{let s=e;return s.startsWith(t)&&(s=s.replace(t,"")),s},Or=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),Dr=[{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<=Dr.length;s++){const o=Dr[s];if(Math.abs(t)<o.amount)return Or.format(Math.round(t),o.name);t/=o.amount}return Or.format(Math.round(t),"years")}const Lo=e=>e%4===0&&e%100!==0||e%400===0,Po=(e,t)=>[31,Lo(e)?29:28,31,30,31,30,31,31,30,31,30,31][t],yn=(e,t)=>{const s=new Date(e),o=e.getDate();return s.setDate(1),s.setMonth(s.getMonth()+t),s.setDate(Math.min(o,Po(s.getFullYear(),s.getMonth()))),s},bn=(e,t)=>{const s=new Date(e);return s.setDate(s.getDate()+t),s},Be="en-US",wn={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"}},vn={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"}},Mn=(e,{dateStyle:t="short",locales:s=Be}={dateStyle:"short",locales:Be})=>{const o=t==="short"?wn.short:{dateStyle:t};return new Intl.DateTimeFormat(s,o).format(e)},_n=(e,{locales:t=Be,timeStyle:s="short"}={locales:Be,timeStyle:"short"})=>{const o=vn[s];return new Intl.DateTimeFormat(t,o).format(e)},En=(e,{dateStyle:t="short",locales:s=Be,timeStyle:o="short"}={dateStyle:"short",locales:Be,timeStyle:"short"})=>{const r={...t&&wn[t],...o&&vn[o]};return new Intl.DateTimeFormat(s,r).format(e)},Hl=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:bn,addMonthsToDate:yn,formatDate:Mn,formatDateSince:pn,formatDateTime:En,formatTime:_n,getDaysInMonth:Po,isLeapYear:Lo},Symbol.toStringTag,{value:"Module"}));function In(e,t,s=300){let o;return(...r)=>{clearTimeout(o),o=setTimeout(()=>{t.apply(e,r)},s)}}class Tn{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 Tn;const Vl=window.KosFeatureFlags,ae=(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),{}),$n=(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)}`},On=e=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(e);if(!s)throw Error("Invalid HSL string");return $n(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},Dn=(e,t)=>getComputedStyle(e).getPropertyValue(t),Yl=(e,t)=>On(Dn(e,t)),Sn="studio.tools.preview",zl="studio.relax.store.validation",An="studio.log.debug",Cn="studio.log.info",ql={profiles:[Sn]};var nn;const Wl=((nn=globalThis.getKosConfig)==null?void 0:nn.call(globalThis))||JSON.stringify(ql),Rn=JSON.parse(Wl);globalThis.kosConfig=Rn;const ko=Rn,Ln=()=>ko.profiles||[],ao=e=>Ln().includes(e),Zl=()=>ko.logging||!1,Ql=(e,t)=>{const s={...e};return s.id&&delete s.id,s},co=(e,t,s=Ql)=>{const o=s(e,t);w.runInAction(()=>{Object.assign(t,o)})},Zs=new Map,Pn={addToDeletionQueue:(e,t)=>{const s=Zs.get(e)||[];s.push(t),Zs.set(e,s)},cancelDeletion:e=>{const t=Zs.get(e);t&&t.forEach(s=>{clearTimeout(s)})}},Xl=()=>{const e=ao(An),t=ao(Cn);return e?"DEBUG":t?"INFO":void 0},kn=()=>{const e=ae(),t=Xl(),o=e.kosLogLevel??t??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return o||"WARN"},xn=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",Nn=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",Fn="ws-log",Jl=T.methodFactory,Un=xn(),ed=Nn();T.methodFactory=function(e,t,s){const o=Jl(e,t,s);return function(r,n){var i;o(r,n||""),(i=globalThis==null?void 0:globalThis.kosConfig)!=null&&i.logging&&globalThis.kosLog&&(s!==Fn||Un&&ed)&&globalThis.kosLog(`UI: ${String(s||"Root")} - ${r}`)}};let jn=kn();T.setLevel(jn);window.setKosLogLevel=e=>{jn=e,T.setLevel(e)};const ls=T.getLogger(Fn);window.enableKosMessageLog=()=>{ls.setLevel(T.levels.INFO)};window.disableKosMessageLog=()=>{ls.setLevel(T.levels.ERROR)};Un?window.enableKosMessageLog():window.disableKosMessageLog();const td=["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(";"),sd=["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(";"),Vt=e=>t=>{T.getLevel()<=e&&t()},f={...T,ifDebug:Vt(T.levels.DEBUG),ifInfo:Vt(T.levels.INFO),ifWarn:Vt(T.levels.WARN),ifError:Vt(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");ls.info(`%c⬆ ${t}`,td)},wsReceive:(...e)=>{const t=String(e).replace(/\n/g,"\\n");ls.info(`%c⬇ ${t}`,sd)}},od=f.createLogger({name:"kos-dependency-manager"});class rd{constructor(){a(this,"_usedByCache",new Map);a(this,"_usesCache",new Map)}add(t,s){Pn.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?(od.info(`Model ${t} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}var p=(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))(p||{}),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 Sr=f.createLogger({name:"kos-model-cache"});class nd{constructor(t=[]){a(this,"_modelsById",w.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?(Sr.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(Sr.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),t(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const J=Symbol("SubscriptionHandlers"),k=Symbol("DependencyModels"),Fe=Symbol("FutureService"),pt=Symbol("ChildModels"),yt=Symbol("ParentModel"),bt=Symbol("LogConfig"),ts=Symbol("ReferenceConfig"),Bn=Symbol("KosModelSymbol"),wt=Symbol("ModelEffects"),Qs=new Map,Ar=new Map,Xs=new Map,Js=new Map,xo=(e,t)=>{Kn[e]=t},Kn={indexExtension:{registerIndexExtension:(e,t)=>{const s=Js.get(e)||{};Object.assign(s,t),Js.set(e,t)},loadIndexExtensions:e=>Js.get(e)||{}},loader:{registerLoader:(e,t)=>{Ar.set(e,t)},executeLoader:async(e,t)=>{const s=Ar.get(e);if(s)return await s(t)}},propertyMapper:{registerPropertyMapper:(e,t)=>{Xs.set(e,t)},hasMapper:e=>Xs.has(e),executeMapper:(e,t,s)=>{const o=Xs.get(e);return o?o(t,s):""}},dataMapper:{registerDataMapper:(e,t)=>{const s=Qs.get(e)||[];s.push(t),Qs.set(e,s)},executeMapper:async(e,t,s)=>{const o=Qs.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=Kn;var U=(e=>(e.INIT="init",e.LOAD="load",e.READY="ready",e.ACTIVATE="activate",e.ONLINE="online",e))(U||{});const id=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:U},Symbol.toStringTag,{value:"Module"})),Gn=({path:e,requestId:t,method:s,destinationAddress:o})=>{let r=`${Rs}:${s}
1
+ "use strict";var kl=Object.defineProperty;var Pl=(e,t,s)=>t in e?kl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var a=(e,t,s)=>(Pl(e,typeof t!="symbol"?t+"":t,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("loglevel"),w=require("mobx"),m=require("robot3"),me=require("date-fns"),M=require("@emotion/react/jsx-runtime"),xl=require("@emotion/styled"),Nl=require("react-dom"),Ie=require("@emotion/react"),h=require("react"),un=require("mobx-react-lite"),Fl=require("@use-gesture/react"),Ls="method",hn="topic",We="url",Ft="request-id",ks="response-id",So="status",ge="dst-addr",gn="src-addr",ie="type",Ao="ordered",Co="tracker",fn="Content-Type",mn="Cache-Control",pn="requestId",yn=process.env.KOS_LOGIN_URL||"http://localhost",bn=process.env.KOS_APP_PORT||"8080",Ul=`${yn}:${bn}`,ls="{MODEL_ID}";var Ut=(e=>(e.SEND="/ws/log/msg/send",e.RECEIVED="/ws/log/msg/receive",e))(Ut||{}),wn=(e=>(e.MSG_RECEIVE="/mock/msg/receive",e))(wn||{});const Ro="/kos/model/ready/";I.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const k=globalThis.kos.subscriptions,jl=()=>Symbol("eventKey");function U(e,t){const s=jl();return k[e]||(I.debug(`Initializing subscription for ${e}`),k[e]={}),I.debug(`Subscribing to ${e} with id ${s.toString()}`),k[e][s]=t,{count:k[e]?Object.getOwnPropertySymbols(k[e]).length:0,unsubscribe:()=>(I.debug(`Unsubscribing from ${e} with id ${s.toString()}`),k[e]&&k[e][s]&&delete k[e][s],k[e]&&Object.getOwnPropertySymbols(k[e]).length===0&&delete k[e],{count:k[e]?Object.getOwnPropertySymbols(k[e]).length:0})}}function j(e,t,s={}){if(!k[e]||Object.getOwnPropertySymbols(k[e]).length===0)return I.debug(`No subscriptions for ${e}. Not publishing.`),{eventType:e,subscribers:0};const o=Object.getOwnPropertySymbols(k[e]).length;return Object.getOwnPropertySymbols(k[e]).forEach(r=>{if(s.sync){const n=s.sync;I.debug(`Performing sync publish for ${e} with sync id ${n}`),k[e][r]({body:t,headers:s}).then(i=>{I.debug(`Response recieved for ${n}, publishing back to source.`),j(n,i)})}else I.debug(`Performing async publish for ${e}`),k[e][r]({body:t,headers:s})}),{eventType:e,subscribers:o}}function Bl(){I.warn("Resetting event bus"),Object.keys(k).forEach(e=>delete k[e])}const Kl=Object.freeze(Object.defineProperty({__proto__:null,publish:j,reset:Bl,subscribe:U},Symbol.toStringTag,{value:"Module"})),Gl=(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 Lo(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 jt(){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 Hl(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 Vl(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))},Yl=({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)},zl=({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)},ql=({items:e,onAddItem:t,onRemoveItem:s,idMapper:o=r=>r})=>r=>{const n=r.map(o);ko(n,e).forEach(s),n.forEach(t)},Wl=(e,t="parent-")=>{let s=e;return s.startsWith(t)&&(s=s.replace(t,"")),s},Ar=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),Cr=[{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 vn(e){let t=(e.getTime()-Date.now())/1e3;for(let s=0;s<=Cr.length;s++){const o=Cr[s];if(Math.abs(t)<o.amount)return Ar.format(Math.round(t),o.name);t/=o.amount}return Ar.format(Math.round(t),"years")}const Po=e=>e%4===0&&e%100!==0||e%400===0,xo=(e,t)=>[31,Po(e)?29:28,31,30,31,30,31,31,30,31,30,31][t],Mn=(e,t)=>{const s=new Date(e),o=e.getDate();return s.setDate(1),s.setMonth(s.getMonth()+t),s.setDate(Math.min(o,xo(s.getFullYear(),s.getMonth()))),s},En=(e,t)=>{const s=new Date(e);return s.setDate(s.getDate()+t),s},je="en-US",_n={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"}},In={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"}},Tn=(e,{dateStyle:t="short",locales:s=je}={dateStyle:"short",locales:je})=>{const o=t==="short"?_n.short:{dateStyle:t};return new Intl.DateTimeFormat(s,o).format(e)},$n=(e,{locales:t=je,timeStyle:s="short"}={locales:je,timeStyle:"short"})=>{const o=In[s];return new Intl.DateTimeFormat(t,o).format(e)},On=(e,{dateStyle:t="short",locales:s=je,timeStyle:o="short"}={dateStyle:"short",locales:je,timeStyle:"short"})=>{const r={...t&&_n[t],...o&&In[o]};return new Intl.DateTimeFormat(s,r).format(e)},Zl=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:En,addMonthsToDate:Mn,formatDate:Tn,formatDateSince:vn,formatDateTime:On,formatTime:$n,getDaysInMonth:xo,isLeapYear:Po},Symbol.toStringTag,{value:"Module"}));function Dn(e,t,s=300){let o;return(...r)=>{clearTimeout(o),o=setTimeout(()=>{t.apply(e,r)},s)}}class Sn{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 Sn;const Jl=window.KosFeatureFlags,ae=(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),{}),An=(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)}`},Cn=e=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(e);if(!s)throw Error("Invalid HSL string");return An(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},Rn=(e,t)=>getComputedStyle(e).getPropertyValue(t),Ql=(e,t)=>Cn(Rn(e,t)),Ln="studio.tools.preview",Xl="studio.relax.store.validation",kn="studio.log.debug",Pn="studio.log.info",ed={profiles:[Ln]};var dn;const td=((dn=globalThis.getKosConfig)==null?void 0:dn.call(globalThis))||JSON.stringify(ed),xn=JSON.parse(td);globalThis.kosConfig=xn;const No=xn,Nn=()=>No.profiles||[],co=e=>Nn().includes(e),sd=()=>No.logging||!1,od=(e,t)=>{const s={...e};return s.id&&delete s.id,s},lo=(e,t,s=od)=>{const o=s(e,t);w.runInAction(()=>{Object.assign(t,o)})},Js=new Map,Fn={addToDeletionQueue:(e,t)=>{const s=Js.get(e)||[];s.push(t),Js.set(e,s)},cancelDeletion:e=>{const t=Js.get(e);t&&t.forEach(s=>{clearTimeout(s)})}},rd=()=>{const e=co(kn),t=co(Pn);return e?"DEBUG":t?"INFO":void 0},Un=()=>{const e=ae(),t=rd(),o=e.kosLogLevel??t??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return o||"WARN"},jn=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",Bn=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",Kn="ws-log",nd=I.methodFactory,Gn=jn(),id=Bn();I.methodFactory=function(e,t,s){const o=nd(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!==Kn||Gn&&id)&&globalThis.kosLog(`UI: ${c}${r}`)}};let Hn=Un();I.setLevel(Hn);window.setKosLogLevel=e=>{Hn=e,I.setLevel(e)};const ds=I.getLogger(Kn);window.enableKosMessageLog=()=>{ds.setLevel(I.levels.INFO)};window.disableKosMessageLog=()=>{ds.setLevel(I.levels.ERROR)};Gn?window.enableKosMessageLog():window.disableKosMessageLog();const ad=["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(";"),cd=["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=>{I.getLevel()<=e&&t()},f={...I,ifDebug:zt(I.levels.DEBUG),ifInfo:zt(I.levels.INFO),ifWarn:zt(I.levels.WARN),ifError:zt(I.levels.ERROR),getLogger:e=>I.getLogger(`kos::${e}`),createLogger:({name:e,group:t})=>I.getLogger(`${t?`${t}:`:"kos"}::${e}`),wsSend:(...e)=>{const t=String(e).replace(/\n/g,"\\n");ds.info(`%c⬆ ${t}`,ad)},wsReceive:(...e)=>{const t=String(e).replace(/\n/g,"\\n");ds.info(`%c⬇ ${t}`,cd)}},ld=f.createLogger({name:"kos-dependency-manager"});class dd{constructor(){a(this,"_usedByCache",new Map);a(this,"_usesCache",new Map)}add(t,s){Fn.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?(ld.info(`Model ${t} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}var p=(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))(p||{}),O=(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))(O||{});const Rr=f.createLogger({name:"kos-model-cache"});class ud{constructor(t=[]){a(this,"_modelsById",w.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?(Rr.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(Rr.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),t(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const Qs=new Map,Lr=new Map,Xs=new Map,eo=new Map,Fo=(e,t)=>{Vn[e]=t},Vn={indexExtension:{registerIndexExtension:(e,t)=>{const s=eo.get(e)||{};Object.assign(s,t),eo.set(e,t)},loadIndexExtensions:e=>eo.get(e)||{}},loader:{registerLoader:(e,t)=>{Lr.set(e,t)},executeLoader:async(e,t)=>{const s=Lr.get(e);if(s)return await s(t)}},propertyMapper:{registerPropertyMapper:(e,t)=>{Xs.set(e,t)},hasMapper:e=>Xs.has(e),executeMapper:(e,t,s)=>{const o=Xs.get(e);return o?o(t,s):""}},dataMapper:{registerDataMapper:(e,t)=>{const s=Qs.get(e)||[];s.push(t),Qs.set(e,s)},executeMapper:async(e,t,s)=>{const o=Qs.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=Vn;function Yn(e,t){return`${Ro}${e}${t?`/${t}`:`/${e}`}`}function zn(e){return`${Ro}${e}`}var F=(e=>(e.INIT="init",e.LOAD="load",e.READY="ready",e.ACTIVATE="activate",e.ONLINE="online",e))(F||{});const hd=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:F},Symbol.toStringTag,{value:"Module"}));function kr(e){const t=[];return new Promise((s,o)=>{for(const{condition:r,onMatch:n}of e){const i=w.when(r,()=>{t.forEach(c=>c());try{n==null||n(),s()}catch(c){o(c)}});t.push(i)}})}const G=Symbol("SubscriptionHandlers"),L=Symbol("DependencyModels"),yt=Symbol("FutureService"),bt=Symbol("ChildModels"),wt=Symbol("ParentModel"),vt=Symbol("LogConfig"),os=Symbol("ReferenceConfig"),qn=Symbol("KosModelSymbol"),$e=Symbol("ModelEffects"),ce=(e,t)=>{e[bt]=e[bt]||{},e[bt][t]=!0},Se=e=>`{PROP_${String(e)}}`,gd=e=>`{PROP_${String(e)}}`,fd=Se("kosParentId"),Ps=e=>t=>{t[wt]=t[wt]||{};const s=(e==null?void 0:e.parentId)||fd;t[wt]={parentId:s}},Be=({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]=Be({value:o[n],modelId:t,modelData:s}),r),{});else if(typeof o=="string"){const r=new RegExp(".*({PROP_(.+)})");let n=o!=null&&o.includes(ls)?o.replace(ls,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},md=f.createLogger({name:"kos-model"});function pd(e,t,s){var n;const o=(n=e[wt])==null?void 0:n.parentId;if(!o)return;const r=Be({value:o,modelData:s,modelId:t});r&&typeof r=="string"&&P.setParentContext(t,r)}function yd(e){const t=e[yt];t&&Object.entries(t).forEach(([s,{handler:o}])=>{e[s]=o})}function bd(e,t){const s=e[L]||{};Object.entries(s).forEach(([o,r])=>{const n=Be({value:r.id||r.modelType,modelData:e,modelId:t}),i=Object.entries((r==null?void 0:r.options)||{}).reduce((c,[l,d])=>(c[l]=Be({value:d,modelData:e,modelId:t}),c),{});if(typeof n=="string"){if(!r.lazy){const c=_.getInstance().modelManager.createModelInstance(r.modelType,n,i);e[o]=c.data}_.getInstance().modelManager.addDependency(t,n)}})}function wd(e){try{return w.makeAutoObservable(e)}catch(t){return md.error("Failed to make observable:",t),e}}const vd={construct(e,t){var c;const[s,o={}]=t,r=P.createContext(s);pd(e,s,o);const n=f.createLogger({name:e.prototype.modelTypeId,group:((c=e[vt])==null?void 0:c.group)??"kos-model"}),i=new e(s,o,{logger:n,kosContext:r});return yd(i),bd(i,s),wd(i)}};function D(e){return t=>{var o,r;const s=t;return s.prototype.modelTypeId=e,s.prototype[qn]=!0,(o=s.prototype)[G]??(o[G]={}),(r=s.prototype)[L]??(r[L]={}),f.ifDebug(()=>{f.debug(`Registering model with id ${e}`)}),new Proxy(s,vd)}}const Md=({modelType:e})=>t=>{Ps()(t),D(e)(t)};function Ed(e,t,s){const o=s.value;s.value=function(...r){const n=P.getContext(this.id);return r.push(n),o.apply(this,r)}}const _d=({group:e}={group:""})=>t=>{t[vt]=t[vt]||{},t[vt]={group:e}};function Wn(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 Id=e=>(t,s)=>{t[os]=t[os]||{},t[os][s]=e},Bt=({modelType:e,id:t,options:s,lifecycle:o})=>(r,n)=>{r[L]=r[L]||{},r[L][n]={modelType:e,id:t,options:s,lifecycle:o||F.INIT}},Td=({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:Dn(r,w.action(t),200),condition:o}};function R({topic:e,condition:t=(l,d)=>!0,transform:s=l=>l,websocket:o=!1,fos:r=!1,bridge:n=!1,skipParse:i=!1,lifecycle:c}){return(l,d,u)=>{l[G]=l[G]||{},Array.isArray(e)?e.forEach(g=>{l[G][g]={websocket:o,fos:r,bridge:n,handler:u.value,condition:t,transform:s,lifecycle:c,skipParse:i}}):l[G][e]={websocket:o,fos:r,bridge:n,handler:u.value,condition:t,transform:s,lifecycle:c,skipParse:i}}}const Zn=5e3;class $d extends Error{constructor(s,o){super(s);a(this,"model");this.model=o}}const Jn=(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 $d(`${t.modelId} - ${t.modelTypeName} - ${s}`,t))},e)}),cancel:()=>{o&&clearTimeout(o)}}},Qn=e=>e.fsm.transitionTo(O.GO_ACTIVE,p.ACTIVE),Xn=e=>e.whenReady(),ei=e=>e.fsm.transitionTo(O.LOAD,p.LOADED),Od=e=>e.fsm.transitionTo(O.UNLOAD,p.UNLOADED),ti=e=>e.fsm.transitionTo(O.INITIALIZE,p.INITIALIZED);var Uo=(e=>(e.ACTIVE="active",e.READY="ready",e.LOAD="load",e.UNLOAD="unload",e.INIT="init",e))(Uo||{});const rs={active:Qn,ready:Xn,load:ei,init:ti},si=(e,t)=>{const s=t.id||t.modelType,o=Be({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]=Be({value:l,modelData:e.modelData,modelId:e.modelId}),i},{});return{dependentModel:_.getInstance().modelManager.createModelInstance(t.modelType,o,r),dataModelId:o}},oi=(e,t=F.READY)=>{var r;const s=((r=e.modelData)==null?void 0:r[L])||{};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}=si(e,i);e.modelData[n]=c.data,f.debug(`waiting for dependent model ${i.modelType} with id ${l} - waiting for WHENREADY`);const d=async(y,v,b)=>{var E;await((E=y.whenReady)==null?void 0:E.call(y)),f.debug(`dependent model ${v} with id ${b} - READY`)},{promise:u,cancel:g}=Jn(Zn,e,e.status);return Promise.race([d(c.model,i.modelType,l).then(()=>{g()}),u])}).filter(n=>!!n)},ri=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 rs[s]&&c?l=rs[s](c):(c||f.error("model is undefined. This shouldn't happen"),rs[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}=Jn(Zn,c.model,c.status);return Promise.race([(u=c.promise)==null?void 0:u.then(()=>{d()}),l])}))).filter(c=>c.status==="rejected");i.length>0&&f.error(`Model ${e.modelId} had ${i.length} failed child models on ${o}`)},ni=async(e,t,s)=>{await ri(e,e.getChildren().filter(o=>!!o),t,s)},nt=async(e,t)=>{const o=(await Promise.allSettled(oi(e,t))).filter(r=>r.status==="rejected");o.length&&(f.error(`There were ${o.length} failed dependent models on ${t}`),f.error(o))},Dd=e=>typeof e.toJSON=="function",Mt=e=>e[L]!==void 0,jo=e=>e.revision!==void 0&&e.index!==void 0,ii=e=>{if(e){if(Mt(e))return e;if(jo(e))return e.data;if(e instanceof Map||e instanceof w.ObservableMap||e instanceof Set)return Array.from(e.values()).filter(Mt);if(Array.isArray(e))return e.filter(Mt)}};function Sd(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}}}),Ad(e.modelData,e.modelTypeName,e.modelId,e)}function Ad(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[L]||{};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];Mt(i)?r[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:jo(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 Cd{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);return s.forEach(o=>{try{P.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[bt])||{};return Object.keys(t).map(o=>ii(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 Rd{constructor(t){a(this,"companions",new w.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 Ld{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})`),w.runInAction(()=>c())},d=n?w.reaction(()=>n(this.modelData),l,{fireImmediately:!!(i!=null&&i.fireImmediately)}):w.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 kd=f.createLogger({name:"model-active-machine"}),Pd=e=>{const t=m.createMachine(p.INACTIVE,{[p.FAILED]:m.state(m.transition(O.GO_ACTIVE,p.ACTIVATING)),[p.INACTIVE]:m.state(m.transition(O.GO_ACTIVE,p.ACTIVATING)),[p.ACTIVATING]:m.invoke(()=>(e.activeStatus=p.ACTIVATING,e.activate()),m.transition("done",p.ACTIVE,m.action(()=>{e.activeStatus=p.ACTIVE})),m.transition("error",p.FAILED,m.action(()=>{e.activeStatus=p.FAILED}))),[p.ACTIVE]:m.state(m.transition(O.GO_INACTIVE,p.DEACTIVATING)),[p.DEACTIVATING]:m.invoke(()=>(e.activeStatus=p.DEACTIVATING,e.deactivate()),m.transition("done",p.INACTIVE,m.action(()=>{e.activeStatus=p.INACTIVE})),m.transition("error",p.FAILED,m.action(()=>{e.activeStatus=p.FAILED})))});return{service:m.interpret(t,o=>kd.debug(o.machine.current)),machine:t}},Pr=f.createLogger({name:"model-online-machine"}),xd=e=>{const t=m.createMachine(p.OFFLINE,{[p.ONLINE]:m.state(m.transition(O.GO_OFFLINE,p.OFFLINE,m.action(async()=>{await e.offline(),e.onlineStatus=p.OFFLINE}))),[p.OFFLINE]:m.state(m.transition(O.GO_ONLINE,p.ONLINE,m.action(async()=>{Pr.debug(`Going online with model ${e.modelId}`),await e.online(),e.onlineStatus=p.ONLINE,await e.fsm.transitionTo(O.INITIALIZE,p.INITIALIZED)})))}),s=m.interpret(t,o=>Pr.debug(o.machine.current));return{machine:t,service:s}},Nd=e=>{var o;const t=Pd(e).service,s=xd(e).service;return m.createMachine(p.CREATING,{[p.CREATING]:m.state(m.transition(O.CREATE,p.CREATED)),[p.CREATED]:m.state(m.immediate(p.INITIALIZING)),[p.INITIALIZING]:m.invoke(()=>(Y(()=>{e.status=p.INITIALIZING}),e.init()),m.transition("done",p.INITIALIZED,m.action(()=>{e.status=p.INITIALIZED}))),[p.INITIALIZED]:m.state(m.immediate(p.LOADING)),[p.LOADING]:m.invoke(()=>(Y(()=>{e.status=p.LOADING}),e.load()),m.transition("done",p.LOADED,m.action(()=>{e.status=p.LOADED})),m.transition("error",p.FAILED,m.action(()=>{e.status=p.FAILED}))),[p.LOADED]:m.state(m.immediate(p.READYING),m.transition(O.UNLOAD,p.UNLOADING)),[p.RESETTING]:m.invoke(()=>{var r;return Y(()=>{e.status=p.RESETTING}),(r=e.unload)==null||r.call(e),e.load()},m.transition("done",p.LOADED,m.action(()=>{e.status=p.LOADED}))),[p.READYING]:m.invoke(()=>(Y(()=>{e.status=p.READYING}),e.ready()),m.transition("done",p.READY,m.action(()=>{Y(()=>{e.status=p.READY}),s.send(O.GO_ONLINE)})),m.transition("error",p.FAILED,m.action(()=>{e.status=p.FAILED}))),[p.READY]:m.state(m.transition(O.UNLOAD,p.UNLOADED,m.action((o=e.unload)==null?void 0:o.bind(e))),m.transition(O.RESET,p.RESETTING),m.transition(O.GO_ONLINE,p.READY,m.action(()=>{s.send(O.GO_ONLINE)})),m.transition(O.GO_OFFLINE,p.READY,m.action(()=>{s.send(O.GO_OFFLINE)})),m.transition(O.GO_ACTIVE,p.READY,m.action(()=>{t.send(O.GO_ACTIVE)})),m.transition(O.GO_INACTIVE,p.READY,m.action(()=>{t.send(O.GO_INACTIVE)}))),[p.UNLOADED]:m.state(),[p.FAILED]:m.state()})},Fd=f.createLogger({name:"kos-model-lifecycle"}),Ud=e=>({service:m.interpret(Nd(e),s=>Fd.debug(`state machine for model ${e.modelId}: ${s.machine.current});`))});class jd{constructor(t,s){a(this,"disposer");a(this,"service");this.model=t,this.log=s;const o=Ud(t);this.service=o.service,this.service.send(O.CREATE)}get current(){return this.service.machine.current}async transitionTo(t,s,o=p.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=w.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[p.ACTIVE,p.INACTIVE].includes(t)?this.model.activeStatus:this.model.status}}class Bd{static create({modelId:t,modelTypeName:s,component:o}){const r=[o??"kos",s,t].filter(Boolean).join(".");return f.createLogger({name:r})}}class Kd{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 Gd{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(O.GO_ONLINE,p.ONLINE)}),o=U("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${t} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(O.GO_OFFLINE,p.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(o.unsubscribe)}dispose(){this.unsubscribers.forEach(t=>t()),this.unsubscribers=[]}}const ai=({path:e,requestId:t,method:s,destinationAddress:o})=>{let r=`${Ls}:${s}
2
2
  `;return r+=`topic:${e}
3
3
  `,r+=`${We}:${e}
4
- `,r+=`${xt}:${t}
4
+ `,r+=`${Ft}:${t}
5
5
  `,o&&(r+=`${ge}:${o}
6
6
  `),r+=`${ie}:kos.studio.request
7
7
  `,r+=`
8
- `,r},Hn=({path:e,requestId:t,method:s,destinationAddress:o,ordered:r,tracker:n})=>{let i=`${cn}:/http${e}
9
- `;return i+=`${Rs}:${s}
8
+ `,r},ci=({path:e,requestId:t,method:s,destinationAddress:o,ordered:r,tracker:n})=>{let i=`${hn}:/http${e}
9
+ `;return i+=`${Ls}:${s}
10
10
  `,i+=`${We}:${e}
11
- `,i+=`${hn}:${t}
11
+ `,i+=`${pn}:${t}
12
12
  `,o&&(i+=`${ge}:${o}
13
- `),r&&(i+=`${So}:true
14
- `),n&&(i+=`${Ao}:${n}
13
+ `),r&&(i+=`${Ao}:true
14
+ `),n&&(i+=`${Co}:${n}
15
15
  `),i+=`${ie}:fos.http.request
16
16
  `,i+=`
17
- `,i},Vn=({path:e,requestId:t,method:s,destinationAddress:o,ordered:r,tracker:n,bridge:i})=>{let c=`${Rs}:${s}
18
- `;return c+=`${We}:${e}
19
- `,c+=`${xt}:${t}
20
- `,o&&(c+=`${ge}:${o}
21
- `),r&&(c+=`${So}:true
22
- `),n&&(c+=`${Ao}:${n}
23
- `),c+=`${ie}:${i?"fos":"kos"}.http.request
24
- `,c+=`
25
- `,c},be=(e,t)=>{let s=e;return t&&(s+=t),s};function lo(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 uo(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 Yn=({path:e,requestId:t,destinationAddress:s})=>{let o=`topic:${e}
17
+ `,i},li=({path:e,requestId:t,method:s,destinationAddress:o,ordered:r,tracker:n,bridge:i,headers:c})=>{let l=`${Ls}:${s}
18
+ `;return l+=`${We}:${e}
19
+ `,l+=`${Ft}:${t}
20
+ `,o&&(l+=`${ge}:${o}
21
+ `),r&&(l+=`${Ao}:true
22
+ `),n&&(l+=`${Co}:${n}
23
+ `),c&&Object.keys(c).forEach(d=>{l+=`${d}:${c[d]}
24
+ `}),l+=`${ie}:${i?"fos":"kos"}.http.request
25
+ `,l+=`
26
+ `,l},be=(e,t)=>{let s=e;return t&&(s+=t),s};function uo(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 ho(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 di=({path:e,requestId:t,destinationAddress:s})=>{let o=`topic:${e}
26
27
  `;return o+=`${We}:${e}
27
- `,o+=`${xt}:${t}
28
+ `,o+=`${Ft}:${t}
28
29
  `,o+=`${ge}:${s}
29
30
  `,o+=`${ie}:kos.studio.request
30
31
  `,o+=`
31
- `,o},zn=({requestId:e,destinationAddress:t,requestType:s,headers:o})=>{let r=`${xt}:${e}
32
+ `,o},ui=({requestId:e,destinationAddress:t,requestType:s,headers:o})=>{let r=`${Ft}:${e}
32
33
  `;return r+=`${ge}:${t}
33
34
  `,r+=`${ie}:${s}
34
35
  `,o&&Object.keys(o).forEach(n=>{r+=`${n}:${o[n]}
35
36
  `}),r+=`
36
- `,r},ad=(e,t)=>{const s=e,o=be(zn(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")},qn=({path:e,responseId:t,status:s,destinationAddress:o})=>{let r=`topic:${e}
37
+ `,r},Hd=(e,t)=>{const s=e,o=be(ui(t),typeof s=="string"?s:JSON.stringify(s)),r=_.getInstance().transport.socket;r?(f.debug("Sending message",o),r.socket.send(o)):f.error("socket transport is not initialized")},hi=({path:e,responseId:t,status:s,destinationAddress:o})=>{let r=`topic:${e}
37
38
  `;return r+=`${We}:${e}
38
- `,t&&(r+=`${Ls}:${t}
39
- `),r+=`${Do}:${s}
39
+ `,t&&(r+=`${ks}:${t}
40
+ `),r+=`${So}:${s}
40
41
  `,r+=`${ge}:${o}
41
42
  `,r+=`${ie}:kos.studio.response
42
43
  `,r+=`
43
- `,r},cd=(e,t)=>{const s=e,o=be(Yn(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},ld=(e,t)=>{const s=t.responseId?{status:t.status,data:e}:e,o=be(qn(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},Wn=({topic:e})=>{let t=`topic:${e}
44
+ `,r},Vd=(e,t)=>{const s=e,o=be(di(t),JSON.stringify(s)),r=_.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},Yd=(e,t)=>{const s=t.responseId?{status:t.status,data:e}:e,o=be(hi(t),JSON.stringify(s)),r=_.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},gi=({topic:e})=>{let t=`topic:${e}
44
45
  `;return t+=`${ie}:kos.broker.send
45
46
  `,t+=`
46
- `,t},Zn=({responseId:e,destinationAddress:t,type:s,sourceAddress:o,status:r})=>{let n=`${Ls}:${e}
47
+ `,t},fi=({responseId:e,destinationAddress:t,type:s,sourceAddress:o,status:r})=>{let n=`${ks}:${e}
47
48
  `;return n+=`${ge}:${t}
48
- `,n+=`${ln}:${o}
49
+ `,n+=`${gn}:${o}
49
50
  `,n+=`${ie}:${s??"kos.message.request"}
50
- `,n+=`${Do}:${r}
51
- `,n+=`${dn}:application/json
52
- `,n+=`${un}:no-cache
51
+ `,n+=`${So}:${r}
52
+ `,n+=`${fn}:application/json
53
+ `,n+=`${mn}:no-cache
53
54
  `,n+=`
54
- `,n},Qn=({topic:e,responseId:t,destinationAddress:s,type:o})=>{let r=`topic:${e}
55
- `;return t&&(r+=`${Ls}:${t}
55
+ `,n},mi=({topic:e,responseId:t,destinationAddress:s,type:o})=>{let r=`topic:${e}
56
+ `;return t&&(r+=`${ks}:${t}
56
57
  `),r+=`${ge}:${s}
57
58
  `,r+=`${ie}:${o??"kos.message.request"}
58
59
  `,r+=`
59
- `,r},dd=({msg:e,options:t})=>{const s=e,o=be(Wn(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},Xn=({msg:e,options:t})=>{const s=e,o=be(Qn(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},Jn=({msg:e,options:t})=>{const s=e,o=be(Zn(t),JSON.stringify(s)),r=E.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},ho=(e,t)=>{try{return t?e.body??e:JSON.parse(e.body)}catch{return e.body||e}},ce=(e,t)=>{e[pt]=e[pt]||{},e[pt][t]=!0},De=e=>`{PROP_${String(e)}}`,ud=e=>`{PROP_${String(e)}}`,hd=De("kosParentId"),Ps=e=>t=>{t[yt]=t[yt]||{};const s=(e==null?void 0:e.parentId)||hd;t[yt]={parentId:s}},Ue=({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]=Ue({value:o[n],modelId:t,modelData:s}),r),{});else if(typeof o=="string"){const r=new RegExp(".*({PROP_(.+)})");let n=o!=null&&o.includes(cs)?o.replace(cs,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},Cr=f.createLogger({name:"kos-model"}),gd={construct(e,t){var c,l;const s=P.createContext(t[0]);let o=(c=e[yt])==null?void 0:c.parentId;o&&(o=Ue({value:o,modelData:t[1]||{},modelId:t[0]}),P.setParentContext(t[0],o));const r=new e(...t,{logger:f.createLogger({name:e.prototype.modelTypeId,group:((l=e[bt])==null?void 0:l.group)??"kos-model"}),kosContext:s});try{Object.keys(r[Fe]||{}).forEach(d=>{r[d]=r[Fe][d].handler})}catch(d){Cr.error("error while creating model instance",d)}const n=r[k]||{};Object.keys(n).forEach(d=>{const u=n[d],h=Ue({value:u.id||u.modelType,modelData:r,modelId:t[0]}),y=Object.keys((u==null?void 0:u.options)||{}).reduce((v,b)=>{const M=u.options[b];return v[b]=Ue({value:M,modelData:r,modelId:t[0]}),v},{});typeof h=="string"&&(r[d]=u.lazy?void 0:E.getInstance().modelManager.createModelInstance(u.modelType,h,y||{}).data,E.getInstance().modelManager.addDependency(t[0],h))});let i;try{i=w.makeAutoObservable(r)}catch(d){Cr.error(d)}return i}},S=e=>t=>{t.prototype.modelTypeId=e,t.prototype[Bn]=!0,t.prototype[J]=t.prototype[J]||{},t.prototype[k]=t.prototype[k]||{};const s={};return f.ifDebug(()=>{f.debug(`Registering model with options ${s}`)}),new Proxy(t,gd)},fd=({modelType:e})=>t=>{Ps()(t),S(e)(t)};function md(e,t,s){const o=s.value;s.value=function(...r){const n=P.getContext(this.id);return r.push(n),o.apply(this,r)}}const pd=({group:e}={group:""})=>t=>{t[bt]=t[bt]||{},t[bt]={group:e}};function ei(e){return(t,s,o)=>{t[wt]=t[wt]||{},t[wt][s]={dependencies:e==null?void 0:e.dependencies,value:o.value},o.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const yd=e=>(t,s)=>{t[ts]=t[ts]||{},t[ts][s]=e},Ut=({modelType:e,id:t,options:s,lifecycle:o})=>(r,n)=>{r[k]=r[k]||{},r[k][n]={modelType:e,id:t,options:s,lifecycle:o||U.INIT}},bd=({topic:e,handler:t,websocket:s=!1,condition:o=()=>!0})=>r=>{r[J]=r[J]||{},Array.isArray(e)?e.forEach(n=>{r[J][n]={websocket:s,handler:t,condition:o}}):r[J][e]={websocket:s,handler:In(r,w.action(t),200),condition:o}};function R({topic:e,condition:t=(l,d)=>!0,transform:s=l=>l,websocket:o=!1,fos:r=!1,bridge:n=!1,skipParse:i=!1,lifecycle:c}){return(l,d,u)=>{l[J]=l[J]||{},Array.isArray(e)?e.forEach(h=>{l[J][h]={websocket:o,fos:r,bridge:n,handler:u.value,condition:t,transform:s,lifecycle:c,skipParse:i}}):l[J][e]={websocket:o,fos:r,bridge:n,handler:u.value,condition:t,transform:s,lifecycle:c,skipParse:i}}}const ti=5e3;class wd extends Error{constructor(s,o){super(s);a(this,"model");this.model=o}}const si=(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 wd(`${t.modelId} - ${t.modelTypeName} - ${s}`,t))},e)}),cancel:()=>{o&&clearTimeout(o)}}},oi=e=>e.transition(D.GO_ACTIVE,p.ACTIVE),ri=e=>e.whenReady(),ni=e=>e.transition(D.LOAD,p.LOADED),vd=e=>e.transition(D.UNLOAD,p.UNLOADED),ii=e=>e.transition(D.INITIALIZE,p.INITIALIZED);var No=(e=>(e.ACTIVE="active",e.READY="ready",e.LOAD="load",e.UNLOAD="unload",e.INIT="init",e))(No||{});const ss={active:oi,ready:ri,load:ni,init:ii},ai=(e,t)=>{const s=t.id||t.modelType,o=Ue({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]=Ue({value:l,modelData:e.modelData,modelId:e.modelId}),i},{});return{dependentModel:E.getInstance().modelManager.createModelInstance(t.modelType,o,r),dataModelId:o}},ci=(e,t=U.READY)=>{var r;const s=((r=e.modelData)==null?void 0:r[k])||{};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}=ai(e,i);e.modelData[n]=c.data,f.debug(`waiting for dependent model ${i.modelType} with id ${l} - waiting for WHENREADY`);const d=async(y,v,b)=>{var M;await((M=y.whenReady)==null?void 0:M.call(y)),f.debug(`dependent model ${v} with id ${b} - READY`)},{promise:u,cancel:h}=si(ti,e,e.status);return Promise.race([d(c.model,i.modelType,l).then(()=>{h()}),u])}).filter(n=>!!n)},li=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 ss[s]&&c?l=ss[s](c):(c||f.error("model is undefined. This shouldn't happen"),ss[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}=si(ti,c.model,c.status);return Promise.race([(u=c.promise)==null?void 0:u.then(()=>{d()}),l])}))).filter(c=>c.status==="rejected");i.length>0&&f.error(`Model ${e.modelId} had ${i.length} failed child models on ${o}`)},di=async(e,t,s)=>{await li(e,e.getChildren().filter(o=>!!o),t,s)},rt=async(e,t)=>{const o=(await Promise.allSettled(ci(e,t))).filter(r=>r.status==="rejected");o.length&&(f.error(`There were ${o.length} failed dependent models on ${t}`),f.error(o))},os=e=>e[k]!==void 0,ui=e=>e.revision!==void 0&&e.index!==void 0,hi=e=>{if(e){if(os(e))return e;if(ui(e))return e.data;if(e instanceof Map||e instanceof w.ObservableMap||e instanceof Set)return Array.from(e.values()).filter(os);if(Array.isArray(e))return e.filter(os)}},Md=f.createLogger({name:"model-active-machine"}),_d=e=>{const t=m.createMachine(p.INACTIVE,{[p.FAILED]:m.state(m.transition(D.GO_ACTIVE,p.ACTIVATING)),[p.INACTIVE]:m.state(m.transition(D.GO_ACTIVE,p.ACTIVATING)),[p.ACTIVATING]:m.invoke(()=>(e.activeStatus=p.ACTIVATING,e.activate()),m.transition("done",p.ACTIVE,m.action(()=>{e.activeStatus=p.ACTIVE})),m.transition("error",p.FAILED,m.action(()=>{e.activeStatus=p.FAILED}))),[p.ACTIVE]:m.state(m.transition(D.GO_INACTIVE,p.DEACTIVATING)),[p.DEACTIVATING]:m.invoke(()=>(e.activeStatus=p.DEACTIVATING,e.deactivate()),m.transition("done",p.INACTIVE,m.action(()=>{e.activeStatus=p.INACTIVE})),m.transition("error",p.FAILED,m.action(()=>{e.activeStatus=p.FAILED})))});return{service:m.interpret(t,o=>Md.debug(o.machine.current)),machine:t}},Rr=f.createLogger({name:"model-online-machine"}),Ed=e=>{const t=m.createMachine(p.OFFLINE,{[p.ONLINE]:m.state(m.transition(D.GO_OFFLINE,p.OFFLINE,m.action(async()=>{await e.offline(),e.onlineStatus=p.OFFLINE}))),[p.OFFLINE]:m.state(m.transition(D.GO_ONLINE,p.ONLINE,m.action(async()=>{Rr.debug(`Going online with model ${e.modelId}`),await e.online(),e.onlineStatus=p.ONLINE,await e.transition(D.INITIALIZE,p.INITIALIZED)})))}),s=m.interpret(t,o=>Rr.debug(o.machine.current));return{machine:t,service:s}},Id=e=>{var o;const t=_d(e).service,s=Ed(e).service;return m.createMachine(p.CREATING,{[p.CREATING]:m.state(m.transition(D.CREATE,p.CREATED)),[p.CREATED]:m.state(m.immediate(p.INITIALIZING)),[p.INITIALIZING]:m.invoke(()=>(V(()=>{e.status=p.INITIALIZING}),e.init()),m.transition("done",p.INITIALIZED,m.action(()=>{e.status=p.INITIALIZED}))),[p.INITIALIZED]:m.state(m.immediate(p.LOADING)),[p.LOADING]:m.invoke(()=>(V(()=>{e.status=p.LOADING}),e.load()),m.transition("done",p.LOADED,m.action(()=>{e.status=p.LOADED})),m.transition("error",p.FAILED,m.action(()=>{e.status=p.FAILED}))),[p.LOADED]:m.state(m.immediate(p.READYING),m.transition(D.UNLOAD,p.UNLOADING)),[p.RESETTING]:m.invoke(()=>{var r;return V(()=>{e.status=p.RESETTING}),(r=e.unload)==null||r.call(e),e.load()},m.transition("done",p.LOADED,m.action(()=>{e.status=p.LOADED}))),[p.READYING]:m.invoke(()=>(V(()=>{e.status=p.READYING}),e.ready()),m.transition("done",p.READY,m.action(()=>{V(()=>{e.status=p.READY}),s.send(D.GO_ONLINE)})),m.transition("error",p.FAILED,m.action(()=>{e.status=p.FAILED}))),[p.READY]:m.state(m.transition(D.UNLOAD,p.UNLOADED,m.action((o=e.unload)==null?void 0:o.bind(e))),m.transition(D.RESET,p.RESETTING),m.transition(D.GO_ONLINE,p.READY,m.action(()=>{s.send(D.GO_ONLINE)})),m.transition(D.GO_OFFLINE,p.READY,m.action(()=>{s.send(D.GO_OFFLINE)})),m.transition(D.GO_ACTIVE,p.READY,m.action(()=>{t.send(D.GO_ACTIVE)})),m.transition(D.GO_INACTIVE,p.READY,m.action(()=>{t.send(D.GO_INACTIVE)}))),[p.UNLOADED]:m.state(),[p.FAILED]:m.state()})},Td=f.createLogger({name:"kos-model-lifecycle"}),$d=e=>({service:m.interpret(Id(e),s=>Td.debug(`state machine for model ${e.modelId}: ${s.machine.current});`))});class Od extends WebSocket{constructor(t){super(t)}}function Lr(e){const t=`
60
+ `,r},zd=({msg:e,options:t})=>{const s=e,o=be(gi(t),JSON.stringify(s)),r=_.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},pi=({msg:e,options:t})=>{const s=e,o=be(mi(t),JSON.stringify(s)),r=_.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},yi=({msg:e,options:t})=>{const s=e,o=be(fi(t),JSON.stringify(s)),r=_.getInstance().transport.socket;r?r.socket.send(o):f.error("socket transport is not initialized")},go=(e,t)=>{try{return t?e.body??e:JSON.parse(e.body)}catch{return e.body||e}};class qd extends WebSocket{constructor(t){super(t)}}function xr(e){const t=`
60
61
 
61
62
  `,s=`
62
- `,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 Dd(e){const t=`
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(g=>g.trim());return d&&u&&(c[d]=u),c},{}),body:n}}function Wd(e){const t=`
63
64
 
64
65
  `,s=`
65
- `,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 Fo{constructor({host:t,port:s,protocol:o,alias:r,onConnectionEstablished:n,onConnectionLost:i,Transport:c=Od}){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,F("/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)}}),w.makeObservable(this,{connectionEstablished:w.observable})}addOfflineMessage(t){this.offlineMessages.push({msg:t})}processMessageEvent(t){const{data:s}=t;return Lr(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}=Dd(t.data);n=l,i={...s,...c}}K(r,n,i)}}catch(s){f.error("onMessage exception",s.message,s.stack)}}onOpen(t){f.info("websocket connection opened"),this.socket=t.currentTarget,w.runInAction(()=>{var s;this.connectionEstablished=!0,this.alias&&this.socket.send(`type:kos.addr.alias
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(g=>g.trim());return d&&u&&(c[d]=u),c},{}),body:n}}class Bo{constructor({host:t,port:s,protocol:o,alias:r,onConnectionEstablished:n,onConnectionLost:i,Transport:c=qd}){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 g={data:l.body};(u=(d=this.socket)==null?void 0:d.onmessage)==null||u.call(d,g)}}),w.makeObservable(this,{connectionEstablished:w.observable})}addOfflineMessage(t){this.offlineMessages.push({msg:t})}processMessageEvent(t){const{data:s}=t;return xr(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}=Wd(t.data);n=l,i={...s,...c}}j(r,n,i)}}catch(s){f.error("onMessage exception",s.message,s.stack)}}onOpen(t){f.info("websocket connection opened"),this.socket=t.currentTarget,w.runInAction(()=>{var s;this.connectionEstablished=!0,this.alias&&this.socket.send(`type:kos.addr.alias
66
67
  alias:${this.alias}
67
68
 
68
- `),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(),w.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}=Lr(String(t));K(Nt.SEND,{headers:r,body:n})}if(window.kosTopicIntercept&&window.kosEnableMocks){const{handler:r,requestId:n}=window.kosTopicIntercept(t);if(r){t=`mocked:true
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(),w.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}=xr(String(t));j(Ut.SEND,{headers:r,body:n})}if(window.kosTopicIntercept&&window.kosEnableMocks){const{handler:r,requestId:n}=window.kosTopicIntercept(t);if(r){t=`mocked:true
69
70
  ${t}`;const c={data:`mocked:true
70
- ${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 Sd{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 Ad extends Fo{constructor({host:s,port:o,alias:r}){super({host:s,port:o,Transport:Sd,alias:r,protocol:"kos://"});a(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}class Cd extends Fo{constructor({host:s,port:o}){super({host:s,port:o,protocol:"ws://"});a(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="requestId"}}class Rd extends Fo{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 go{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 Ad({host:t,port:s,protocol:o,onConnectionEstablished:i,onConnectionLost:c,alias:n})):r?new Cd({host:t,port:s,protocol:o,alias:n,onConnectionEstablished:i,onConnectionLost:c}):new Rd({host:t,port:s,protocol:o,alias:n,onConnectionEstablished:i,onConnectionLost:c})}}const Ld=ae();Ld.fos&&(window.kosUseFos=!0);const Pr=process.env.KOS_FOS_PORT;window.kosUseFos=!!(window.kosUseFos||process.env.KOS_USE_FOS==="true");window.kosFosPort=Pr?parseInt(Pr):0;const Ee=T.getLogger("web-socket-transport");var gi=(e=>(e.NOT_INITIALIZED="not_initialized",e.INITIALIZED="initialized",e.OFFLINE="OFFLINE",e.ONLINE="ONLINE",e))(gi||{}),vt=(e=>(e.CONNECTED="websocket.connected",e.DISCONNECTED="websocket.disconnected",e.RELOAD="websocket.reload",e))(vt||{});class ks{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;w.makeObservable(this,{authorized:w.observable,socket:w.observable,fosSocket:w.observable,init:w.action,connectionEstablished:w.computed}),w.reaction(()=>this.connectionEstablished,d=>{d&&(Ee.warn("Connection Established"),K("websocket.connected","websocket.connected"),l&&K("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=go.build({host:this.host,port:this.fosPort||9854,protocol:this.protocol,fos:!0})),this.socket=go.build({host:this.host,port:this.port,protocol:this.protocol,alias:this.alias,onConnectionLost:()=>{Ee.error("Connection Lost"),K("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){var h,y,v,b;Ee.debug(`${s} to topic ${t}`);const n=ae(),c=(n==null?void 0:n.connId)||((h=window==null?void 0:window.kosBridge)==null?void 0:h.call(window,"connId"));Ee.debug(`subscribing with connId ${c}`);const l=c?`dst-addr:${c}
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 Zd{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);I.debug(`called Bridge Transport with addr ${t}`);const s=this;globalThis.kosWindowWebsocketRecv=o=>{if(s.onmessage){const r={data:o};s.onmessage(r)}},I.debug("Opening bridge transport"),globalThis.kosWindowWebsocketOpen(),I.debug("Opened bridge transport"),this._onclose=null,this._onerror=null,this._onmessage=null,this._onopen=null,this.addEventListener=()=>I.debug("not implemented"),this.dispatchEvent=()=>I.debug("not implemented"),this.removeEventListener=()=>I.debug("not implemented")}close(){I.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 Jd extends Bo{constructor({host:s,port:o,alias:r}){super({host:s,port:o,Transport:Zd,alias:r,protocol:"kos://"});a(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}class Qd extends Bo{constructor({host:s,port:o}){super({host:s,port:o,protocol:"ws://"});a(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="requestId"}}class Xd extends Bo{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 fo{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 Jd({host:t,port:s,protocol:o,onConnectionEstablished:i,onConnectionLost:c,alias:n})):r?new Qd({host:t,port:s,protocol:o,alias:n,onConnectionEstablished:i,onConnectionLost:c}):new Xd({host:t,port:s,protocol:o,alias:n,onConnectionEstablished:i,onConnectionLost:c})}}const eu=ae();eu.fos&&(window.kosUseFos=!0);const Nr=process.env.KOS_FOS_PORT;window.kosUseFos=!!(window.kosUseFos||process.env.KOS_USE_FOS==="true");window.kosFosPort=Nr?parseInt(Nr):0;const _e=I.getLogger("web-socket-transport");var bi=(e=>(e.NOT_INITIALIZED="not_initialized",e.INITIALIZED="initialized",e.OFFLINE="OFFLINE",e.ONLINE="ONLINE",e))(bi||{}),Et=(e=>(e.CONNECTED="websocket.connected",e.DISCONNECTED="websocket.disconnected",e.RELOAD="websocket.reload",e))(Et||{});class xs{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;w.makeObservable(this,{authorized:w.observable,socket:w.observable,fosSocket:w.observable,init:w.action,connectionEstablished:w.computed}),w.reaction(()=>this.connectionEstablished,d=>{d&&(_e.warn("Connection Established"),j("websocket.connected","websocket.connected"),l&&j("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=fo.build({host:this.host,port:this.fosPort||9854,protocol:this.protocol,fos:!0})),this.socket=fo.build({host:this.host,port:this.port,protocol:this.protocol,alias:this.alias,onConnectionLost:()=>{_e.error("Connection Lost"),j("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){var g,y,v,b;_e.debug(`${s} to topic ${t}`);const n=ae(),c=(n==null?void 0:n.connId)||((g=window==null?void 0:window.kosBridge)==null?void 0:g.call(window,"connId"));_e.debug(`subscribing with connId ${c}`);const l=c?`dst-addr:${c}
71
72
  `:"",d=o?`subscribe:${t}`:r?`type:fos.broker
72
73
  cmd:${s}
73
74
  ${l}topics:${t}
74
75
  `:`${l}type:kos.broker.${s}
75
76
 
76
- ["${t}"]`;if(o?(y=this.fosSocket)==null?void 0:y.connectionEstablished:(v=this.socket)==null?void 0:v.connectionEstablished){const M=o?this.fosSocket:this.socket;(b=M==null?void 0:M.socket)==null||b.send(d)}else{Ee.debug("no connection adding to offline messages");const M=o?this.fosSocket:this.socket;M==null||M.addOfflineMessage(d)}}subscribeTopic({topic:t,callback:s,fos:o,bridge:r}){const{unsubscribe:n,count:i}=F(t,s);return Ee.debug(`Topic ${t} currently has ${i} subscribers`),this._sendSubscriptionMessage(t,"subscribe",o,r),()=>{const{count:c}=n();Ee.debug(`Topic ${t} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(t,"unsubscribe",o)}}async whenReady(){const t=this;return this.webSocketSupported?(await w.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(ks,"_instance");const I=T.getLogger("kos-model"),kr="kos.extension.model.loader",Pd=({subscription:e,modelData:t,skipParse:s,model:o,resolvedTopic:r})=>n=>{try{if(o!=null&&o.isReady){const i=ho(n,s),c=e.transform(i);if(e.condition(c,t,n))return e.handler.call(t,c,n,t)}else{f.warn(`model ${o==null?void 0:o.modelId} not ready. adding message for topic ${r} to offline queue`);const i=()=>{f.warn(`processing offline message for ${r} on model ${o==null?void 0:o.modelId}`);const c=ho(n,s),l=e.transform(c);if(e.condition(l,t))return e.handler.call(t,l,n,t)};o._offlineQueue.push(i)}}catch(i){I.error(i)}},kd=(e,t,s)=>{const o=new RegExp(".*({PROP_(.+)})");let r=e.includes("{MODEL_ID}")?e.replace("{MODEL_ID}",t):e;const n=r.match(o);if(n&&s&&Object.getOwnPropertyNames(s).includes(n[2])){const i=s[n[2]];r=r.replace(n[1],i)}return r};class fi{constructor({modelTypeName:t,id:s,modelData:o}){a(this,"_id");a(this,"_status");a(this,"_activeStatus");a(this,"_onlineStatus");a(this,"_subscriptions");a(this,"_onlineSubscriptions");a(this,"modelData");a(this,"modelTypeName");a(this,"initialized");a(this,"loaded");a(this,"_offlineQueue");a(this,"fsmService");a(this,"disposers",[]);a(this,"_companionModels");this._id=typeof s<"u"?`${s}`:t,this.modelTypeName=t,this.initialized=!1,this.loaded=!1,this.modelData=o,this._status=p.CREATED,this._activeStatus=p.INACTIVE,this._onlineStatus=p.OFFLINE,this.fsmService=$d(this),this._subscriptions=[],this._onlineSubscriptions=[],this.fsmService.service.send(D.CREATE),this._companionModels=new Map,this._offlineQueue=[],w.makeAutoObservable(this)}get companionModels(){return this._companionModels}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===p.ACTIVE}isOnline(){return this._onlineStatus===p.ONLINE}isReady(){return this._status===p.READY}async deactivate(){var t,s;I.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=P.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.deactivate)==null?void 0:s.call(t,o)),I.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`)}catch(o){throw I.debug(`Model ${this.modelId} failed to deactivated`),o}}transition(t,s,o=p.FAILED){const r=this;if((s===p.ACTIVE||s===p.INACTIVE?r.activeStatus:r.status)===s)return I.debug(`model ${this.modelId} already at target state ${s}. resolving immediately. `),Promise.resolve();let i;return new Promise((c,l)=>{i=w.autorun(()=>{const d=s===p.ACTIVE||s===p.INACTIVE?r.activeStatus:r.status;d===o?l(Error(`Failed to transition ${r.modelId} to ${t}`)):d===s&&c()}),r.fsmService.service.send(t)}).then(()=>{i==null||i()})}async activate(){var t,s;I.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await rt(this,U.ACTIVATE);try{const o=P.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.activate)==null?void 0:s.call(t,o)),I.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(o){throw I.debug(`Model ${this.modelId} failed to activate`),o}}async whenInitialized(){const t=this;let s,o;return new Promise((r,n)=>{s=w.when(()=>t._status===p.FAILED,()=>{n(Error(`Failed to load ${t.modelId} model ${t.modelTypeName}`))}),o=w.when(()=>t.initialized,()=>{r()})}).then(()=>{s==null||s(),o==null||o()})}async whenReady(){const t=this;let s,o;return new Promise((r,n)=>{s=w.when(()=>t._status===p.FAILED,()=>{n(Error(`Failed to load ${t.modelId} model ${t.modelTypeName}`))}),o=w.when(()=>t._status===p.READY,()=>{r()})}).then(()=>{s==null||s(),o==null||o()})}async ready(){var t,s;if(this.fsmService.service.machine.current===p.READY){I.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{I.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await rt(this,U.READY),await di(this,No.READY,U.READY);const o=P.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.ready)==null?void 0:s.call(t,o)),this._offlineQueue.length>0&&(f.warn(`processing ${this._offlineQueue.length} messages offline queue for ${this.modelId}`),this._offlineQueue.forEach(r=>r()),f.info(`offline queue processed for ${this.modelId}`)),this._offlineQueue=[],I.debug(`Model ${this.modelId} is ready`)}catch(o){throw I.error(o),Error(o)}}async load(){var t,s,o;if(this.fsmService.service.machine.current===p.LOADED||this.fsmService.service.machine.current===p.LOADING){I.debug(`already loaded model ${this.modelTypeName} with id ${this.modelId} returning`);return}I.debug(`loading model ${this.modelTypeName} with id ${this.modelId}`),await rt(this,U.LOAD),I.debug(`loading model ${this.modelTypeName} with id ${this.modelId}`);try{const r=P.getContext(this.modelId),n=await C.loader.executeLoader(kr,{});n&&(I.info(`setting loaded context for ${this.modelId}, type: ${this.modelTypeName}`),r==null||r.set(kr,n)),await((s=(t=this.modelData)==null?void 0:t.load)==null?void 0:s.call(t,r)),this.loaded=!0,I.debug(`Model ${this.modelTypeName} with id ${this.modelId} loaded`),this.registerSubscribers(U.LOAD);const i=((o=this.modelData)==null?void 0:o[wt])||{};Object.keys(i).forEach(c=>{var u;const l=i[c].value.bind(this.modelData),d=function(){I.info(`running effect ${c} for model type ${this.modelTypeName} id: ${this.modelId}`),w.runInAction(()=>{l.apply(this.modelData)})};if(i[c].dependencies){const h=()=>i[c].dependencies(this.modelData),y=w.reaction(h,d.bind(this),{fireImmediately:!!((u=i[c].options)!=null&&u.fireImmediately)});this.disposers.push(y)}else{const h=w.autorun(d.bind(this));this.disposers.push(h)}})}catch(r){throw I.error(`Model ${this.modelId} failed to load`),r}}async unload(){var t,s;I.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const o=this.getChildren().map(n=>{var i;return(i=n.unload)==null?void 0:i.call(n)}).filter(n=>!!n);await Promise.allSettled(o);const r=P.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.unload)==null?void 0:s.call(t,r)),this.loaded=!1,this._onlineSubscriptions.forEach(n=>n()),this._onlineSubscriptions=[],I.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),this.disposers.forEach(n=>n()),this.disposers=[]}catch(o){throw I.debug(`Model ${this.modelId} failed to unload`),o}}async init(){var t,s;I.debug(`initializing init dependencies of model ${this.modelTypeName} with id ${this.modelId}`),await rt(this,U.INIT),I.debug(`initializing model ${this.modelTypeName} with id ${this.modelId}`);try{const o=P.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.init)==null?void 0:s.call(t,o)),this.initialized=!0,I.debug(`Model ${this.modelTypeName} with id ${this.modelId} initialized`);const r=F("/kosCore/online",async()=>{I.debug(`online subscription called for ${this.modelId} waiting for ready state`),await this.whenReady(),I.debug(` ${this.modelId} is ready. Going online`),this.fsmService.service.send(D.GO_ONLINE)}),n=F("/kosCore/offline",async()=>{I.debug(` offline sub called for model ${this.modelId}. Going offline`),this.fsmService.service.send(D.GO_OFFLINE)});this._onlineSubscriptions.push(r.unsubscribe),this._onlineSubscriptions.push(n.unsubscribe),this.registerSubscribers(U.INIT)}catch(o){throw I.error(`Model ${this.modelId} failed to initialize`),o}}_registerSubscription(t,s,o){if(t.websocket){I.debug(`subscribing ${s} via WebSocketTransport`);const r=ks.getInstance().subscribeTopic({topic:s,callback:o,fos:t.fos,bridge:t.bridge});this._subscriptions.push(r)}else{I.debug(`subscribing ${s} directly to EventBus`);const{unsubscribe:r}=F(s,o);this._subscriptions.push(r)}}async registerSubscribers(t){var o;I.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`);const s=((o=this.modelData)==null?void 0:o[J])||{};I.debug(`found ${Object.keys(s).length} topics to subscribe to`),Object.keys(s).forEach(r=>{const n=s[r].lifecycle;if(t&&t!==n)return;const i=!!s[r].skipParse;I.debug(`found subscription for ${r}`),I.debug(`${r} skipParse: ${i}`);const c=kd(r,this.modelId,this.modelData);I.debug(`resolved subscription to ${c}`);const l=Pd({model:this,resolvedTopic:c,skipParse:i,modelData:this.modelData,subscription:s[r]});this._registerSubscription(s[r],c,l)})}async online(){var s,o;I.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const t=P.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;I.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),this._subscriptions.forEach(r=>{r()}),this._subscriptions=[];const t=P.getContext(this.modelId);await((o=(s=this.modelData)==null?void 0:s.offline)==null?void 0:o.call(s,t))}accept(t){t.visit(this)}getChildren(){const t=this.getDecoratedChildren(),s=this.getResolvedChildren(t),o=this.getAdditionalChildren(),r=Array.from(new Set([...s,...o,...Array.from(this._companionModels.values())]));return this.filterAndMapToModels(r)}clearCompanionModels(){this._companionModels.clear()}addCompanionModel(t){this._companionModels.set(t.modelTypeName,t)}getDecoratedChildren(){var t;return((t=this.modelData)==null?void 0:t[pt])||{}}getResolvedChildren(t){return Object.keys(t).map(s=>{var o;return hi((o=this.modelData)==null?void 0:o[s])}).filter(s=>!!s).flat()}getAdditionalChildren(){var t,s;return((s=(t=this.modelData)==null?void 0:t.getChildren)==null?void 0:s.call(t))||[]}filterAndMapToModels(t){const s=t.map(o=>this.modelManager.getModelById(o.id||"")).filter(o=>!!o);return s.forEach(o=>{try{P.setParentContext(o.modelId,this.modelId)}catch{I.error(`failed to set parent context for model ${o.modelId} with parent ${this.modelId}`)}}),s}}const mi=e=>typeof e=="function",xr=f.createLogger({name:"kos-model-instantiator"});class xd{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)){xr.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 fi({modelTypeName:t,id:n,modelData:c});this.cache.addModel(l),this._createCompanionModels(l,o)}const i=this.cache.getModelById(n);if(!i)throw xr.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=mi(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 Nd=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 Qe(t)}};const pi=10,Nr=f.createLogger({name:"kos-model-manager"});class yi{constructor(){a(this,"cache");a(this,"instantiator");a(this,"dependencies");a(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new rd,globalThis.kos.modelManager=this}static create(t,s){const o=this.getInstance(s);return o._registry=new Nd(t),o.cache=new nd(t.preloadModels),o.instantiator=new xd(t,o.cache),o}static getInstance(t){var s,o;return(!((s=globalThis.kos)!=null&&s.modelManager)||t)&&(Nr.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=>(Nr.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 Qe(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.transition(D.RESET,p.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),Pn.addToDeletionQueue(t.id,setTimeout(()=>this.destroyModel(s),pi)))}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 Fd=async({context:e,extension:t})=>{const s=await C.loader.executeLoader(t,{});return e==null||e.set(t,s),s},Ud=async({extension:e,contextData:t,data:s})=>await C.dataMapper.executeMapper(e,s,t),jd=async({extension:e,contextData:t,data:s})=>await C.propertyMapper.executeMapper(e,s,t),Bd=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:Ud,executeLoaderExtension:Fd,executePropertyMapperExtension:jd},Symbol.toStringTag,{value:"Module"})),Kd="Extensions";class Gd{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 rs=(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))(rs||{}),xe=(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))(xe||{});const Hd=e=>{const t=m.createMachine("offline",{online:m.state(m.transition("go_offline","offline",m.action(()=>{e.offline(),w.runInAction(()=>{e.isOnline=!1})}))),offline:m.state(m.transition("go_online","online",m.action(()=>{e.online(),w.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(()=>{w.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}},Z=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},$e=async e=>{await E.getInstance().whenReady(),await E.getInstance().modelManager.initiateDestroyModel(e)},Vd=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.transition(D.UNLOAD,p.UNLOADED)},bi=async e=>{await E.getInstance().whenReady(),await E.getInstance().modelManager.reloadModel(e),f.debug(`reload model initiated for model ${e.id}, model ready: ${ds(e)} - ${Date.now()} `),await Z(e),f.debug(`reload model complete for model ${e.id}, model ready: ${ds(e)} - ${Date.now()} `)},Yd=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},wi=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}},Ze=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}},vi=(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]))},zd=(e,t)=>vi(e,t)[0],qd=(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},Wd=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.values()).map(o=>o.modelData)},fo=(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.values()).find(r=>t(r.modelData))},ee=e=>t=>Object.getPrototypeOf(t).modelTypeId===e,ds=e=>{const t=E.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return t.isReady()},Zd=f.createLogger({name:"kos-model-factory"}),Mt={byModelType:e=>E.getInstance().modelManager.getModelFactory(e),getModelInstance:(e,t,s)=>{const o=Mt.byModelType(t);if(!o)throw Zd.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)}},G={Factory:{create:e=>t=>(s,o)=>(o&&P.setParentContext(t,o),Mt.getModelInstance(t,e,s))},Singleton:{create:e=>(t,s)=>(s&&P.setParentContext(e,s),Mt.getModelInstance(e,e,t))},Model:{instance:e=>t=>Mt.getModelInstance(t,e)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const Fr=window.KosRegistry.coreModels,eo=window.KosRegistry.preloadModels,to=window.KosRegistry.companionModels,Yt=window.KosRegistry.models,$={model:{registerLegacyModel:e=>(t,s)=>(Fr.set(t,s),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}),preloadModel:e=>t=>(eo.includes(t)||eo.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=so(t)?t.registration():t;return Yt.set(o.type,o),so(t)&&t.relatedModels.forEach(r=>Yt.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],so(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=>Yt.get(e),getAll:()=>Array.from(Yt.entries()),getPreloadModels:()=>eo,getLegacyModels:()=>Array.from(Fr.entries()).reduce((e,[t,s])=>(e[t]=s,e),{})},companion:{register:e=>(t,s)=>{const o=to.get(t)||[];return o.push(s),to.set(t,o),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e),root:e}},getAll:()=>Array.from(to.entries())}},Mi=$.model.registerLegacyModel,_i=$.model.register,Qd=$.companion.register,Xd=$.model.preloadModel,Ei=e=>typeof e.updateModel=="function",so=e=>e.registration!==void 0&&typeof e.registration=="function";class Ii{constructor(t){a(this,"singleton");a(this,"type");a(this,"class");a(this,"guard");a(this,"factory");a(this,"relatedModels",[]);this.singleton=t.singleton,this.guard=ee(t.type),this.type=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 le extends Ii{constructor(t){super({...t,singleton:!1,factory:G.Factory.create(t.type)})}instance(t){const s=this.factory(t);return{get:()=>{const o=Ze(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(Ei(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 we extends Ii{constructor(t){super({...t,singleton:!0,factory:G.Singleton.create(t.type)})}instance(){const t=this.factory;return{get:()=>{const o=Ze(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)},forceUpdate:{options:o=>({build:()=>{const r=t(o);if(this.guard(r)){if(Ei(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=t(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:!0}},factory:this.factory}}}const N=f.createLogger({name:"kos-core"}),Jd=()=>{const e=window.location.protocol,t=ae(),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://")},eu=()=>{const e=window.location.hostname,t=process.env.KOS_HOST,s=ae(),o=s==null?void 0:s.host;let r;try{r=new URL(o).hostname}catch{}return r??t??e},tu=()=>{const e=window.location.port,t=process.env.KOS_PORT,s=ae(),o=s==null?void 0:s.host;let r;try{r=new URL(o).port}catch{}return r??t??e},su=(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)}}},Ur=e=>typeof e.reload=="function",ou=e=>typeof e.unload=="function";var Ti=(e=>(e.LOGGED_IN="logged_in",e.LOGGED_OUT="logged_out",e))(Ti||{});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=rs.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,w.makeAutoObservable(this),F("token",c=>{c&&(this.transport.token=c.body)}),F(vt.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(xe.GO_ONLINE)}),F(vt.DISCONNECTED,async()=>{this.fsmService.service.send(xe.GO_OFFLINE)}),F("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),F("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),F(vt.RELOAD,()=>{this.fsmService.service.send(xe.RELOAD)}),F("/studio/project/reload",()=>{this.fsmService.service.send(xe.RELOAD)});const s=ks.getInstance(),o=eu(),r=tu(),n=Jd();s.host=o,s.port=Number.parseInt(r),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=t||process.env.KOS_CONNECTION_ALIAS;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=Hd(this),this.fsmService.service.send(xe.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;const t=Date.now();if(this._reloading){N.info("reload already in progress");return}this._reloading=!0,N.warn("reloading KOS Core"),N.warn("reloading preloaded models");const s=this.modelManager;for(const i of s.preloadedModels)Ur(i.modelData)&&(N.info(`reloading model ${i.modelId}`),(r=i.unload)==null||r.call(i),await i.modelData.reload(),N.info(`reloading model ${i.modelId} complete`));for(const i of s.models)!s.preloadedModels.includes(i)&&Ur(i.modelData)&&((n=i.unload)==null||n.call(i),await i.modelData.reload());const o=Date.now()-t;setTimeout(()=>{w.runInAction(()=>{N.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-o)}async online(){N.debug("KOS Core going online"),await this._transport.whenReady(),N.debug("KOS Transport Ready. Calling online() for models"),K("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){N.debug("KOS Core going offline"),K("/kosCore/offline","/kosCore/offline")}async unload(){var r;N.debug("Unloading KOS Core");const t=Date.now();this._unloading=!0,N.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)ou(n.modelData)&&((r=n.unload)==null||r.call(n));const o=Date.now()-t;setTimeout(()=>{w.runInAction(()=>{this._unloading=!1})},1e3-o)}async whenReady(){await w.when(()=>this.status===rs.READY)}async ready(){N.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}=su(5e3,r.model);Promise.race([r.promise.then(()=>{i()}),n])}))).filter(r=>r.status==="rejected");if(o.length)throw N.error(`There were ${o.length} failed models on model preloading`),Error(`There were ${o.length} failed models on model preloading`);N.debug("leaving kos-core ready() ")}get isReady(){return this.status===rs.READY}set transport(t){this._transport=t}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){N.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,N.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){N.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,N.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,y;const u=(y=(h=t.extensions)==null?void 0:h.dataMapper)==null?void 0:y[d];u&&(Array.isArray(u)?u.forEach(v=>{C.dataMapper.registerDataMapper(d,v)}):C.dataMapper.registerDataMapper(d,u))}),(c=t.extensions)!=null&&c.propertyMapper&&Object.keys(t.extensions.propertyMapper).forEach(d=>{var h,y;const u=(y=(h=t.extensions)==null?void 0:h.propertyMapper)==null?void 0:y[d];u&&C.propertyMapper.registerPropertyMapper(d,u)}),(l=t.extensions)!=null&&l.contextLoader&&Object.keys(t.extensions.contextLoader).forEach(d=>{var h,y;const u=(y=(h=t.extensions)==null?void 0:h.contextLoader)==null?void 0:y[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=yi.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 ru=f.createLogger({name:"kos-fetch"}),nu=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,iu=()=>new Promise(e=>{setTimeout(()=>{e(!0)},0)}),au=e=>e!=null&&e.studio?Gn:e!=null&&e.fos?Hn:Vn,cu=async(e,t)=>{const s=E.getInstance().transport;await s.whenReady();const o=Ft(),r=new URL(e),n=`${r.pathname}${r.search}`,i=(t==null?void 0:t.timeout)||nu,c=au(t),l=be(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(()=>{ru.error(`Timeout occurred - url: ${e}`),u.abort(),d({headers:lo({}),status:404,ok:!1,json:async()=>null,body:uo(""),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:y}=F(o,b=>{var O,A,te;clearTimeout(h);const M={headers:lo((b==null?void 0:b.headers)||{}),status:((O=b==null?void 0:b.headers)==null?void 0:O.status)&&parseInt((A=b==null?void 0:b.headers)==null?void 0:A.status)||200,ok:((te=b==null?void 0:b.headers)==null?void 0:te.status)==="200",json:async()=>{var ve;try{return(ve=b==null?void 0:b.body)!=null&&ve.length?JSON.parse(b.body):null}catch{throw Error("Not a JSON response")}},text:async()=>(b==null?void 0:b.body)||"",body:uo((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.")}};y(),iu().then(()=>d(M))}),v=t!=null&&t.fos?s.fosSocket:s.socket;if(!v)throw Error(`No web socket transport available: ${t}`);v==null||v.send(l)})};exports.BASE_URL="kos:";exports.kosFetch=cu;if(process.env.KOS_MOCK_FETCH==="true"){const e=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${e}`}const lu=f.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class du{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)){lu.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 $i=()=>({isMock:!1,URL:exports.BASE_URL}),uu="errUnknown";async function zt(e,t,s,o,r){const n=o!=null&&o.path?Object.keys(o.path).reduce((h,y)=>String(h).replace(`{${y}}`,o==null?void 0:o.path[y]),String(e)):String(e),i=o!=null&&o.query?Object.keys(o.query).map(h=>`${h}=${o.query[h]}`).join("&"):"",c=`${$i().URL}//${n}${i?`?${encodeURIComponent(i)}`:""}`,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||uu}`,null]:[null,(await d.json()).data]}function Uo(){return{get:(e,t,s)=>zt(e,"get",s,t),post:(e,t,s,o)=>zt(e,"post",o,t,s),put:(e,t,s,o)=>zt(e,"put",o,t,s),delete:(e,t,s)=>zt(e,"delete",s,t)}}class Oi{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 hu=async(e,t)=>{const s=new Oi;t.forEach(r=>s.use(r));const o={data:e,result:{}};return await s.execute(o),o.result},Qe=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}}),gu=e=>{E.getInstance().modelManager.registerModel(e)},fu=(e,t)=>{E.getInstance().modelManager.registerCompanionModel(e,t)},Di=Symbol("KosObservableData");class Si{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,w.createAtom(s.toString())),(r=this.atomMap.get(s))==null||r.reportChanged(),!0},ownKeys:()=>Array.from(this.map.keys())});this.map=w.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)}}Si.prototype[Di]=!0;function mu(e,t){return new Proxy(e,{construct:(s,o)=>{const r=new e(...o);return r.setValues(t),r.proxy}})}const pe=e=>{const t=mu(Si,e);return new t(e)},jr="/kos/ui/internal/heartbeat/",pu=({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:`${jr}${e}`,callback:()=>{c=performance.now()}}),d=o??3e3,u=window.setInterval(()=>{let M=performance.now()-c;M=M/1e3,M>d/1e3&&i.abort()},d),h=r??2e3,y=window.setInterval(()=>{Xn({msg:{},options:{topic:`${jr}${e}`,destinationAddress:t}})},h),v=()=>{window.clearInterval(y),window.clearInterval(u),l()},b=()=>{v(),s&&s(),i.signal.removeEventListener("abort",b)};return i.signal.addEventListener("abort",b),{cleanUpHeartbeat:v}},Ai=(...e)=>t=>e.reduce((s,o)=>o(s),t),yu={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function bu(e,t){let s=1;const o={...yu,...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 z=e=>({isMock:!1,URL:exports.BASE_URL}),wu=(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),Xe(h,{ordered:i,studio:c,fos:l,bridge:d,destinationAddress:u});const y=await s(n||`${t}/${o}`,h);if(!y.ok)throw Error(`There was a problem deleting the model; returned status ${y.status}`);return await y.json()},Xe=(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),vu=(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),Xe(u,{timeout:l,ordered:r,studio:n,fos:i,bridge:c,destinationAddress:d});const y=await s(o||t,u);if(!y.ok){let b;try{b=await y.json()}catch{}throw new ne(`There was a problem retrieving the model; returned status ${y.status}`,b)}return await y.json()},Mu=(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),Xe(h,{timeout:d,ordered:r,studio:n,fos:i,bridge:c,destinationAddress:u});const v=await s(o||t,h);if(!v.ok){let M;try{M=await v.json()}catch{}throw new ne(`There was a problem retrieving the model; returned status ${v.status}`,M)}return await v.json()},_u=(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),Xe(h,{timeout:d,ordered:n,studio:i,fos:c,bridge:l,destinationAddress:u});const y=o||`${t}/${r}`,v=await s(y,h);if(!v.ok){let M;try{M=await v.json()}catch{}throw new ne(`There was a problem retrieving the model; returned status ${v.status}`,M)}return await v.json()};class ne extends Error{constructor(s,o){super(s);a(this,"payload");this.name="FetchException",this.payload=o}}const Br=(e,t,s)=>async({model:o,urlOverride:r,ordered:n,tracker:i,studio:c,fos:l,bridge:d,timeout:u,destinationAddress:h})=>{const y={method:"POST",body:typeof o=="string"?o:JSON.stringify(o)};e&&(y.destinationAddress=e),i&&(y.tracker=i),Xe(y,{timeout:u,ordered:n,studio:c,fos:l,bridge:d,destinationAddress:h});const v=await s(r||t,y);if(!v.ok){let M;try{M=await v.json()}catch{}throw new ne(`There was a problem sending the POST data; returned status ${v.status}`,M)}return await v.json()},Kr=(e="POST",t,s,o)=>async({model:r,id:n,urlOverride:i,ordered:c,studio:l,fos:d,bridge:u,timeout:h,destinationAddress:y})=>{const v={method:e};r&&(v.body=JSON.stringify(r)),t&&(v.destinationAddress=t),Xe(v,{timeout:h,ordered:c,studio:l,fos:d,bridge:u,destinationAddress:y});const b=await o(i||`${s}/${n}`,v);if(!b.ok){let O;try{O=await b.json()}catch{}throw new ne(`There was a problem modifying the model; returned status ${b.status}`,O)}return await b.json()},H={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:vu(e,s||t,l),getModelById:_u(e,o||t,l),getOne:Mu(e,o||t,l),addModel:Br(e,n||t,l),deleteModel:wu(e,r||t,l),modifyModel:Kr("POST",e,i||t,l),putModel:Kr("PUT",e,i||t,l),postModel:Br(e,n||t,l)}}},Eu=Ft(),Ci=()=>`kos-${Eu}`,Iu=e=>!!e&&!e.includes("VM_SERVICE")&&e.startsWith(Ci()),jo=async(e,t=6e4)=>new Promise((s,o)=>{const{unsubscribe:r}=F(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)}),Tu=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)},$u=async({topic:e,msg:t,requestId:s})=>{const o=s??Ft(),r=jo(o);K(e,t,{sync:o});const n=await r;if(n.error)throw Error(n.error);return n},de=new Map;class Ri{constructor(t){a(this,"_context");a(this,"_parent");a(this,"_id");this._id=t,this._context=new w.ObservableMap({}),this._parent="",w.makeAutoObservable(this)}setParent(t){V(()=>{this._parent=t})}get id(){return this._id}get context(){return this._context}get parentModel(){var t;if(this._parent)return(t=Ze(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=de.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 P={createContext:(e,t)=>{const s=de.get(e)??new Ri(e);if(t){if(!de.has(t))throw new Error(`Parent context ${t} does not exist`);s.setParent(t)}else e!=="root"&&s.setParent("root");return de.set(e,s),s},getContext:e=>de.get(e),deleteContext:e=>{de.delete(e)},setParentContext:(e,t)=>{var s;if(!de.has(t))throw new Error(`Parent context ${t} does not exist`);(s=de.get(e))==null||s.setParent(t)},rootContext:()=>de.get("root")};P.createContext("root");const Ou=e=>P.getContext(e.id);function Du(e,t){return e.length!==t.length?!1:e.every(s=>t.includes(s))}class Bo{constructor({container:t,key:s}){a(this,"_container");a(this,"_map");a(this,"_key");a(this,"data");this._container=t,this._map=w.observable.map(new Map),this._key=s,this.data=pe(),this.generateIndex(),w.autorun(()=>{this._container.revision&&this.generateIndex()}),w.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(Du(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(){w.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 Su(e,t,s=[]){const o=Object.getOwnPropertyDescriptors(e);return Object.keys(o).filter(i=>w.isComputedProp(e,i)).filter(i=>s.includes(i)).map(i=>w.reaction(()=>e[i],(c,l)=>{t({name:i,newValue:c,oldValue:l})}))}const st=f.createLogger({name:"kos-container-model"});class fe{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=w.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=w.observable.map(r),this.idx=pe(),this._parentId=t==null?void 0:t.parentId,w.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],o=new Bo({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(){w.runInAction(()=>{this._revision=this._revision+1})}addAll(t){w.runInAction(()=>{t.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(t){w.runInAction(()=>{t.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(t,s){this._data.set(t.id||"",t),t.id&&this._parentId&&P.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 y,v;n.includes(u.name)&&((y=this.index.get(i.get(u.name)))==null||y.refresh());const h=r.filter(([,b])=>typeof b=="function");for(const[b]of h)(v=this.index.get(b))==null||v.refresh()},l=Su(t,c,n.filter(u=>typeof u=="string")),d=w.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??[]:(st.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):(st.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return st.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(t=>{const s=t.id;$e(t).then(()=>{st.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(o=>st.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)}}const oo=f.createLogger({name:"kos-data-container"});class Li{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=w.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=w.observable.map(s),this.idx=pe(),w.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],o=new Bo({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){w.runInAction(()=>{t.forEach(s=>this.addModel(s))})}removeAll(t){w.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(){w.runInAction(()=>{this._revision=this._revision+1})}addModel(t,s){const o=w.isObservable(t)?t:w.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=w.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=w.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??[]:(oo.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):(oo.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return oo.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)}}class Au{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 G.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return ee(this.type)}}class Cu{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 G.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return ee(this.type)}}class Pi{constructor(){a(this,"_token");w.makeAutoObservable(this),F("token",t=>{this.token=t==null?void 0:t.body})}get token(){return this._token}set token(t){this._token=t}}class ki{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 y=l.middlewares[u++];await y(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{unsubscribe:Ru}=F("kos.intent",e=>{if(e){const t=e.body,s=t.type;xi(s,t.options)}}),us=new Map,Lu=(e,t)=>{const s=us.get(e)||[];s.push(t),us.set(e,s)},xi=(e,t)=>{us.has(e)&&us.get(e)[0].call(void 0,t)};var Ni=(e=>(e.GET="GET",e.PUT="PUT",e.POST="POST",e.DELETE="DELETE",e))(Ni||{});const mo=w.when,Ko=w.computed,V=w.runInAction,x=w.autorun,Fi=w.reaction,Go=w.observable,Ho="Not Assigned",Pu="kos.trouble.added",ku="kos.trouble.removed";var oe=(e=>(e.TroubleRank="kos.trouble.rank.mapper",e.TroubleColor="kos.trouble.color.mapper",e.TroubleRole="kos.trouble.role.mapper",e))(oe||{}),_t=(e=>(e.TIME_CHANGE="/kos/internal/time/time",e.DAY_CHANGE="/kos/internal/time/day",e.TIMEZONE_CHANGE="/kos/internal/time/timezone",e))(_t||{});const Ui=f.createLogger({name:"config-bean-service",group:"Services"}),Vo=exports.BASE_URL,ji=e=>(e==null?void 0:e.decimals)!==void 0,{postModel:xu,getOne:Nu}=H.build({destinationAddress:"",basePath:`${Vo}/kos/config/`}),Bi=async(e,t,s="/api/kos/config")=>(Ui.debug(`sending modify request for ConfigBean: ${e}`),xu({model:t,urlOverride:`${Vo}${s}/${e}`})),Ki=async(e,t="/api/kos/config")=>(Ui.debug(`sending get request for ConfigBean: ${e}`),await Nu({urlOverride:`${Vo}${t}/details/${e}/15`})),Yo=e=>e.toLowerCase()==="true"||e.toLowerCase()==="false",xs=e=>{try{const t=Number(e);return!isNaN(t)}catch{return!1}};function Gi(e=[]){return e.reverse().reduce((t,s)=>{const{overrides:o}=s;return o&&(t={...t,...o}),t},{})}function Hi(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])?Hi(e[o],r,s):s[r]=e[o]}return s}const Vi=(e,t)=>{const s=e.details[0].bean||Gi(e.details[0].scopes),o=Hi(s);w.runInAction(()=>{const r={...o};t.props.setValues(r)})},Yi=(e,t)=>{w.runInAction(()=>{e.changes.forEach(s=>{const o=s.attr;let r=s.currentValue,n=s.previousValue;typeof r=="string"&&Yo(r)&&(r=r.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof r=="string"&&xs(r)&&(r=Number(r),n=Number(n)),t.props[o]=r,t.prevProps[o]=n})})},zi=e=>Object.fromEntries(e.props.entries),Fu=e=>t=>s=>e.build(t,s);var Uu=Object.defineProperty,ju=Object.getOwnPropertyDescriptor,qi=(e,t,s,o)=>{for(var r=o>1?void 0:o?ju(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&&Uu(t,s,r),r};function Bu(e,t){for(const s of e)if(new RegExp(`^${s}$`).test(t))return s}const zo="config-bean-model",qt=f.getLogger(zo),Ku=De("path");let hs=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=Bi,getConfigBean:o=Ki}=t;this._modifyConfigBean=s,this._getConfigBean=o,this.props=pe(),this.prevProps=pe()}get values(){return this.props.values}async ready(){qt.debug(`readying config bean ${this.path}`),qt.debug(`complete readying config bean ${this.path}`)}async load(){qt.debug(`loading config bean ${this.path}`);const e=await this._getConfigBean(this.path,this.serviceBasePath);if(e!=null&&e.data){const t=e.data;Vi(t,this),qt.debug(this.values);const s=e==null?void 0:e.data.details[0].schema;V(()=>{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=Bu(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=zi(this);await this._modifyConfigBean(this.path,e,this.serviceBasePath)}handleConfigBeanUpdated(e){Yi(e,this)}};qi([R({topic:`/kos/config/${Ku}`,websocket:!0})],hs.prototype,"handleConfigBeanUpdated",1);hs=qi([S(zo)],hs);const Tt=new le({class:hs,type:zo}),Ns=({path:e,lazy:t,serviceBasePath:s})=>(o,r)=>{o[k]=o[k]||{},o[k][r]={modelType:Tt.type,id:`${Tt.type}-${e}`,options:{path:e,serviceBasePath:s},lifecycle:U.INIT,lazy:t}},{URL:Wi}=z(),{getOne:Gu,getAll:Hu}=H.build({basePath:`${Wi}/api/kos/regions/info`}),Zi=async()=>await Gu({}),Qi=async()=>await Hu({urlOverride:`${Wi}/api/kos/regions`}),Vu=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:Zi,getRegions:Qi},Symbol.toStringTag,{value:"Module"}));var W=(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))(W||{});const Xi={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 Yu(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},{...Xi});return{...e,...o}}function zu(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]:{...Xi}}});return Object.keys(o).forEach(r=>{e[r]={...e[r],...o[r]}}),e}function qu(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 Wu=Object.defineProperty,Zu=Object.getOwnPropertyDescriptor,qo=(e,t,s,o)=>{for(var r=o>1?void 0:o?Zu(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&&Wu(t,s,r),r};const ns="region-info-model",ot=f.createLogger({name:"region-info-model"});let $t=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[W.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[W.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[W.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[W.family]!==s[W.family])throw new Error(`Cannot convert between units of different families: ${t[W.family]} and ${s[W.family]}`);const o=t[W.offset],r=t[W.scale],n=s[W.scale],i=s[W.offset],c=s[W.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||ot.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||ot.info("Could not find default unit for measure",t.measure)}return!n||!i?(ot.warn("Could not find unit to convert to or from. Return value as is"),String(e)):this.convertByUnit(e,n,i)}async init(){ot.debug("initializing region info")}async load(){ot.debug("loading region info");const e=await Qi();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 Zi();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(Yu,{}),this.measureMap=t.data.unitSystems.reduce(zu,{}),this.defaultMeasureMap=t.data.unitSystems.reduce(qu,{}),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))}};qo([Ns({path:"kos:service:region:settings"})],$t.prototype,"regionSource",2);qo([Ns({path:"kos:service:region"})],$t.prototype,"region",2);$t=qo([S(ns)],$t);const Y={registration:{[ns]:{class:$t,singleton:!0}},type:ns,factory:G.Singleton.create(ns)},Gr=({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},Ji=(e,t,s)=>{const{model:o}=Ze(Y.type);if(!o)throw new Error("RegionInfo model not found");if(!ds(o))throw new Error("RegionInfo model not ready");const r={system:o.defaultUnitSystem},n=Gr({source:t}),i=Gr({source:s||r,defaultMeasure:o.getUnitMeasure(n.unit||"")});return o.convert(e,n,i)};function Hr({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 Vr({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 Re=(e,t)=>s=>!e||!t?s:xs(s)?Ji(Number(s),e,t):s,Qu=(e,t,s,o)=>{if((e==null?void 0:e.type)==="enum"||!(e!=null&&e.options))return[];if(e.options.type==="rangeCount")return Hr(e.options).map(Re(s,o));if(e.options.type==="rangeInterval")return Vr(e.options).map(Re(s,o));if(e.options.type==="list"){const{list:r}=e.options;return r.map(Re(s,o))}else{if(e.options.type==="unitSystemRangeCount"&&t)return Hr(e.options.unitSystems[t]).map(Re(s,o));if(e.options.type==="unitSystemRangeInterval"&&t)return Vr(e.options.unitSystems[t]).map(Re(s,o));if(e.options.type==="unitSystemList"&&t){const{list:r}=e.options.unitSystems[t];return r.map(Re(s,o))}}return[]},Xu=(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 Ju=Object.defineProperty,eh=Object.getOwnPropertyDescriptor,Wo=(e,t,s,o)=>{for(var r=o>1?void 0:o?eh(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&&Ju(t,s,r),r};function th(e){return(e==null?void 0:e.type)==="enum"}function sh(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 oh(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 is="config-bean-prop-model",Le=f.createLogger({name:"config-bean-prop-model"}),rh=De("path"),nh=De("serviceBasePath");let Ot=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 ji(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?sh(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=th(o)?o.values:Qu(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){Le.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(){Le.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 oh(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){Le.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 Xu(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){Le.error(`error creating formatter ${u}. Returning the raw value`,h)}}else Le.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,y,v;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,M=(n=(r=this.converter)==null?void 0:r.to)==null?void 0:n.measure,O=(c=(i=this.converter)==null?void 0:i.from)==null?void 0:c.measure,A=b||M||O||t,te=((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),ve=((v=(y=this.converter)==null?void 0:y.to)==null?void 0:v.system)??this.regionInfo.getUnitSystem(te),tt=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:tt,...this.converter.from},to:{...this.converter.to,unit:te,system:ve},measure:A}}if(s&&t){const b=this.regionInfo.getDefaultUnitForMeasure(t,this.regionInfo.defaultUnitSystem),M=this.regionInfo.getUnitSystem(s),O=this.regionInfo.getUnitSystem(b);return{measure:t,to:{unit:M===O?s:b}}}}async updateProperty(e){Le.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)}};Wo([Ut({modelType:Y.type})],Ot.prototype,"regionInfo",2);Wo([Ns({path:rh,serviceBasePath:nh})],Ot.prototype,"bean",2);Ot=Wo([S(is)],Ot);const Se={registration:{[is]:{class:Ot,singleton:!1}},type:is,factory:G.Factory.create(is)};function ih(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[k]=d[k]||{},d[k][u]={modelType:Se.type,id:`${t}-${s}`,options:{path:t,attribute:s,serviceBasePath:c,converter:l,formatter:r,optionsExpander:i},lifecycle:U.INIT,lazy:n}}}class ah{constructor(t,s){a(this,"futures");a(this,"defaultContext");a(this,"context");a(this,"disposers",new Map);a(this,"container");this.futures=Go.map(new Map),this.context="",this.defaultContext=s||"",this.container=t,w.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=x(()=>{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)}}class Zo{constructor(t){a(this,"disposer");a(this,"_future");a(this,"container");a(this,"onFutureUpdate");this._future=void 0,this.container=t,w.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=x(()=>{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 ea="future-model",Je=Qe(ea),Fs=f.createLogger({name:"future-service",group:"Services"}),{isMock:ch,URL:jt}=z();var Ke=(e=>(e.Success="SUCCESS",e.Fail="FAIL",e.Aborted="ABORT",e.Canceled="CANCEL",e))(Ke||{});const{getAll:lh,modifyModel:dh,addModel:uh,deleteModel:hh,postModel:gh}=H.build({destinationAddress:"",basePath:`${jt}/api/future`,mock:ch}),fh=async()=>await lh({}),ta=async(e,t="/api/kos/future")=>(Fs.info(`sending delete request for Future: ${e}`),await hh({id:e,urlOverride:`${jt}${t}/${e}`})),sa=async(e,t="/api/kos/future")=>(Fs.info("sending add request for Future"),await uh({model:e,urlOverride:`${jt}${t}`})),mh=async(e,t,s="/api/kos/future")=>(Fs.info(`sending modify request for Future: ${e}`),dh({model:t,id:e,urlOverride:`${jt}${s}/${e}`})),oa=async(e,t="/api/kos/future")=>(Fs.info(`sending cancel request for Future: ${e}`),gh({urlOverride:`${jt}${t}/${e}/cancel`,ordered:!0,model:{}})),Qo=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}),Xo=(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}`),w.runInAction(()=>{const s=Qo(e);V(()=>{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]})})}))},ra=e=>t=>s=>e.build(String(t),s),Jo=e=>t=>Ai(Qo,ra(e)(t.tracker||t.id))(t);var ph=Object.defineProperty,yh=Object.getOwnPropertyDescriptor,na=(e,t,s,o)=>{for(var r=o>1?void 0:o?yh(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&&ph(t,s,r),r};const ro=f.getLogger(Je.type);let gs=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=oa,mo(()=>this.status===Ke.Success||this.status===Ke.Fail,()=>{ro.info(`Future ${this.id} has completed with status ${this.status}`),$e(this)})}async load(){ro.debug(`loading Future ${this.id}`)}unload(){ro.info(`unloading Future ${this.id}`)}async cancelFuture(){const e=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await mo(()=>this.futureId!==Ho),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}`),Xo(e,this)}};na([R({topic:`kos.future/${cs}`})],gs.prototype,"handleFutureUpdated",1);gs=na([S(Je.type)],gs);const ia=gs,aa=Uo();var bh=Object.defineProperty,wh=Object.getOwnPropertyDescriptor,ca=(e,t,s,o)=>{for(var r=o>1?void 0:o?wh(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 la="browser-router-model",vh="kos.http.request",Mh="kos.http.response";let fs=class{constructor(e,t,s){a(this,"_id");a(this,"logger");a(this,"router");this._id=e,this.logger=s.logger,this.router=new ki}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};let l=200;const d={send:u=>{this.logger.debug(`sending response to ${o}`),this.logger.debug(u),Jn({msg:u,options:{responseId:i,destinationAddress:s,type:Mh,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}`)}};ca([R({topic:vh})],fs.prototype,"handleRequest",1);fs=ca([S(la)],fs);const da=new we({class:fs,type:la}),ua="future-container-model",ye=Qe(ua),ha=e=>Jo(Je)(e),_h=e=>{const t=ha(e);return ye.build(ye.type,{}).addFutureModel(t),t},Eh=e=>ye.build(ye.type,{}).getFuture(String(e)),Oe={buildFutureModel:ha,initiateFuture:_h,getFuture:Eh};var Ih=Object.defineProperty,Th=Object.getOwnPropertyDescriptor,er=(e,t,s,o)=>{for(var r=o>1?void 0:o?Th(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&&Ih(t,s,r),r};const Wt=f.getLogger(ye.type);let Dt=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=ta,addFuture:r=sa}=t;this.logger=s.logger,this._deleteFuture=o,this._addFuture=r,this.id=e,this._futures=new fe,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){Wt.error("error deleting a Future"),Wt.error(t)}}async createFuture(e){try{const t=await this._addFuture(e),s=t==null?void 0:t.data;if(s){const o=Jo(Je)(s);return this.addFutureModel(o),o}}catch(t){throw Wt.error("error creating a Future"),Wt.error(t),t}}handleFutureUpdated(e,t){const s=Oe.buildFutureModel(e);this.addFutureModel(s);const o=`kos.future/${e.tracker||e.id}`;this.logger.debug(`publishing future update to ${o}`),K(o,t.body,t.headers)}};er([ce],Dt.prototype,"_futures",2);er([R({topic:"kos.future"})],Dt.prototype,"handleFutureUpdated",1);Dt=er([S(ye.type)],Dt);const ga=Dt,{URL:Bt}=z(),{getOne:$h,postModel:Oh,deleteModel:fa}=H.build({basePath:`${Bt}/api/keyVal`}),po=f.createLogger({name:"key-value-service",group:"Services"}),ma=async(e,t)=>{await fa({urlOverride:`${Bt}/api/keyVal/${e}/${t}`,id:t})},pa=async(e,t,s)=>{const o=await Oh({urlOverride:`${Bt}/api/keyVal/${e}/${t}`,model:s.toString()});if((o==null?void 0:o.status)!==200)throw po.error("Failed to update studio-state data",o),new Error(`Failed to update studio-state data for namespace ${e}`);return o.data},ya=async(e="studio")=>{po.debug("sending GET for studio-state");const t=await $h({urlOverride:`${Bt}/api/keyVal/${e}`});if((t==null?void 0:t.status)!==200)throw po.error("Failed to retrieve studio-state data",t),new Error(`Failed to retrieve studio-state data for namespace ${e}`);return t.data},Dh=async e=>{await fa({urlOverride:`${Bt}/api/keyVal/${e}}`,id:""})},Sh=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:ma,deleteKeyValueNamespace:Dh,getKeyValue:ya,updateKeyValue:pa},Symbol.toStringTag,{value:"Module"}));var Ah=Object.defineProperty,Ch=Object.getOwnPropertyDescriptor,tr=(e,t,s,o)=>{for(var r=o>1?void 0:o?Ch(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};const ba="key-value-model";let St=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=pe(),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 pa(this.namespace,e,t),this.data[e]=t):(await ma(this.namespace,e),this.data[e]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const e=await ya(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)}};tr([R({topic:"/keyVal/set"})],St.prototype,"handleStateUpdate",1);tr([R({topic:"/keyVal/remove"})],St.prototype,"handleStateDelete",1);St=tr([S(ba)],St);const sr=new le({class:St,type:ba}),{URL:Kt}=z(),{postModel:or,getOne:Rh}=H.build({basePath:`${Kt}/api/kos-time`});f.createLogger({name:"kos-time-service",group:"Services"});const wa=async e=>{const t=await or({model:e,urlOverride:`${Kt}/api/kos/time/time`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},va=async e=>{const t=await or({model:e,urlOverride:`${Kt}/api/kos/time/date`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},Ma=async e=>{const t=await or({model:{},urlOverride:`${Kt}/api/kos/time/timezone?tz=${e}`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data},_a=async()=>{const e=await Rh({urlOverride:`${Kt}/api/kos/time/timezone`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data.timeZone},Lh=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:_a,setDate:va,setTime:wa,setTimezone:Ma},Symbol.toStringTag,{value:"Module"}));var Ph=Object.defineProperty,kh=Object.getOwnPropertyDescriptor,Us=(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&&Ph(t,s,r),r};const nt="kos-time-model",xh="/kos/time/time",Nh="/kos/time/day",Fh="/kos/time/timezone";let Ge=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 wa(e)}async updateSystemDate(e){await va(e)}async updateSystemTimezone(e){await Ma(e)}handleTimeChange(){K(_t.TIME_CHANGE,{})}handleDayChange(){K(_t.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),K(_t.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const e=await _a();this.setTimezone(e)}setTimezone(e){this.timezone=e}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};Us([R({topic:xh,websocket:!0})],Ge.prototype,"handleTimeChange",1);Us([R({topic:Nh,websocket:!0})],Ge.prototype,"handleDayChange",1);Us([R({topic:Fh,websocket:!0})],Ge.prototype,"handleTimeZoneChange",1);Ge=Us([S(nt)],Ge);const ms={registration:{[nt]:{class:Ge,singleton:!0}},type:nt,predicate:ee(nt),factory:G.Singleton.create(nt)};var Uh=Object.defineProperty,jh=Object.getOwnPropertyDescriptor,Ea=(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 Ia="log-block-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 fe({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}`)}};Ea([ce],ps.prototype,"_models",2);ps=Ea([S(Ia)],ps);const Ae=Uo(),Bh=f.createLogger({name:"log-stream-container-service",group:"Services"}),Ta=()=>{var o;const e=ae(),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},et=Ta(),Kh="/api/kos/logs/node/{nodeId}/streams",$a=async()=>(Bh.debug("sending GET for log-stream-container"),await Ae.get(Kh,{path:{nodeId:"primary"}},{destinationAddress:et})),Oa=async(e,t="primary")=>{await Ae.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:t,stream:e}},void 0,{destinationAddress:et})},Da=async e=>{await Ae.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:e}},void 0,{destinationAddress:et})},Gh=async()=>{await Ae.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:et})},Sa=async e=>await Ae.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:e}},{destinationAddress:et}),Aa=async(e,t)=>await Ae.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:e,blockId:t}},{destinationAddress:et}),Hh=Object.freeze(Object.defineProperty({__proto__:null,createOverride:Gh,getKosConnectionId:Ta,getLogStreamBlock:Aa,getLogStreamBlocks:Sa,getLogStreams:$a,subscribeToLogStream:Oa,unsubscribeFromLogStream:Da},Symbol.toStringTag,{value:"Module"}));var Vh=Object.defineProperty,Yh=Object.getOwnPropertyDescriptor,zh=(e,t,s,o)=>{for(var r=o>1?void 0:o?Yh(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};const Ca="log-block-model";let yo=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 Aa(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}`)}};yo=zh([S(Ca)],yo);const At=new le({class:yo,type:Ca}),js=new le({class:ps,type:Ia});js.addRelatedModel(At);var qh=Object.defineProperty,Wh=Object.getOwnPropertyDescriptor,Ra=(e,t,s,o)=>{for(var r=o>1?void 0:o?Wh(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&&qh(t,s,r),r};const La="log-stream-model";let ys=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=js.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=At.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=At.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 Oa(this.name)}async unsubscribe(){await Da(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 Sa(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=Fi(()=>{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()}}};Ra([ce],ys.prototype,"_blocks",2);ys=Ra([S(La)],ys);const Et=new le({class:ys,type:La});var Zh=Object.defineProperty,Qh=Object.getOwnPropertyDescriptor,Ce=(e,t,s,o)=>{for(var r=o>1?void 0:o?Qh(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&&Zh(t,s,r),r};const Pa="log-stream-container-model",Xh="/kos/logs/subscription/addBlock/*",Jh="/kos/logs/subscription/updateBlock/*",eg="/kos/logs/subscription/removeBlock/*",tg="/kos/logs/subscription/lines/*",ka="/kos/logs/streams/add/*";let ue=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 fe({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: ${ka}`);const t=e.stream,s=Et.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=Et.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 $a();if(e){this.logger.error(`Error loading log-streams: ${e}`);return}t&&t.forEach(s=>{const o=Et.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(o)})}};Ce([ce],ue.prototype,"_models",2);Ce([R({topic:[ka],websocket:!0})],ue.prototype,"handleStreamAdded",1);Ce([R({topic:[Xh],websocket:!0})],ue.prototype,"handleAddBlock",1);Ce([R({topic:[eg],websocket:!0})],ue.prototype,"handleRemoveBlock",1);Ce([R({topic:[Jh],websocket:!0})],ue.prototype,"handleUpdateBlock",1);Ce([R({topic:[tg],websocket:!0})],ue.prototype,"handleLogLine",1);ue=Ce([S(Pa)],ue);const Gt=new we({class:ue,type:Pa});Gt.addRelatedModel(Et);Gt.addRelatedModel(js);Gt.addRelatedModel(At);const sg=e=>e.rank!==void 0,og=e=>e.visibleRole!==void 0,rg=e=>e.color!==void 0,ng=e=>{const t=e.info;return sg(t)?t.rank:0},ig=e=>{const t=e.info;return rg(t)?t.color:"orange"},ag=e=>{const t=e.info;return og(t)?t.visibleRole:"TECHNICIAN"},{URL:rr}=z(),{getAll:cg,postModel:xa}=H.build({basePath:`${rr}/api/kos/troubles`}),Na=async()=>await cg({}),Fa=async(e,t)=>{try{const s=await xa({model:{},urlOverride:`${rr}/api/kos/troubles/resolve/${e}`,tracker:t});return s!=null&&s.data&&Oe.initiateFuture(s.data),s.data}catch{const o={id:t||"",endState:Ke.Fail,tracker:t,reason:"Failed to resolve trouble"};return Oe.initiateFuture(o),o}},lg=async(e,t)=>{try{const s=await xa({model:e,urlOverride:`${rr}/api/kos/troubles/resolve/`,tracker:t});return s!=null&&s.data&&Oe.initiateFuture(s.data),s.data}catch{const o={id:t||"",endState:Ke.Fail,tracker:t,reason:"Failed to resolve troubles"};return Oe.initiateFuture(o),o}},dg=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:lg,getTroubles:Na,resolveTrouble:Fa},Symbol.toStringTag,{value:"Module"})),bs="troubleDataMapper",Zt=new Map;xo(bs,{register:(e,t)=>{var s;Zt.has(e)||Zt.set(e,[]),(s=Zt.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Zt.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 Ht="troubleMapper",Qt=new Map;xo(Ht,{register:(e,t)=>{var s;Qt.has(e)||Qt.set(e,[]),(s=Qt.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Qt.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[Ht].register("nozzle",async e=>[e.data.nozzlePath]);C[Ht].register("path",async e=>[e.data.path]);const ug=async e=>{const t=new Set,s=e.ifaces,o=s==null?void 0:s.map(n=>C[Ht].execute(n,e));return(await Promise.allSettled(o)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>t.add(i))}),Array.from(t)},Ua=async e=>{const t=e.ifaces,s=t==null?void 0:t.map(i=>C[bs].execute(i,e)),o=C[bs].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 hg{constructor(){a(this,"type","ResolvableTrouble");a(this,"title","Resolvable Trouble");a(this,"subtitle","Trouble")}}class gg{constructor(){a(this,"type","BlockPumpTrouble");a(this,"title","Block Pump Trouble");a(this,"subtitle","Trouble")}}class Pe{static getHandler(t){switch(t){case"ResolvableTrouble":return new hg;case"BlockPumpTrouble":return new gg;default:return}}}var fg=Object.defineProperty,mg=Object.getOwnPropertyDescriptor,ja=(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&&fg(t,s,r),r};const it="trouble-model";function Xt(e){return typeof e.shouldDefer=="boolean"}let ws=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:y,...v},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=y,this.tags=s,this.info=o,this.group=d,this.createTime=u,this.clientData=n,this.data={},Object.assign(this.data,v),this.futureHandler=new Zo(this)}getTitleWithContext(e){var s,o;const t=e?(o=(s=Pe.getHandler(this.type))==null?void 0:s.context)==null?void 0:o[e]:Pe.getHandler(this.type);return(t==null?void 0:t.title)||"Trouble"}getSubtitleWithContext(e){var s,o;const t=e?(o=(s=Pe.getHandler(this.type))==null?void 0:s.context)==null?void 0:o[e]:Pe.getHandler(this.type);return(t==null?void 0:t.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var e;return((e=Pe.getHandler(this.type))==null?void 0:e.title)||"Trouble"}get subtitle(){var e;return((e=Pe.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 Ua(this)}get deferredCompanion(){const e=fo(this.id,t=>Xt(t));if(e&&Xt(e.modelData))return e.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const e=fo(this.id,t=>Xt(t));return e&&Xt(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 Fa(this._troubleId,e)}};ja([yr()],ws.prototype,"resolve",1);ws=ja([S(it)],ws);const Ct={registration:{[it]:{class:ws,singleton:!1}},type:it,predicate:ee(it),factory:G.Factory.create(it)};var pg=Object.defineProperty,yg=Object.getOwnPropertyDescriptor,Bs=(e,t,s,o)=>{for(var r=o>1?void 0:o?yg(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 Yr=f.createLogger({name:"trouble-container-model"});function zr(e){return C.propertyMapper.hasMapper(oe.TroubleRank)?C.propertyMapper.executeMapper(oe.TroubleRank,e):ng(e)}function qr(e){return(C.propertyMapper.hasMapper(oe.TroubleColor)?C.propertyMapper.executeMapper(oe.TroubleColor,e):ig(e)).toLowerCase()}function Wr(e){return(C.propertyMapper.hasMapper(oe.TroubleRole)?C.propertyMapper.executeMapper(oe.TroubleRole,e):ag(e)).toLowerCase()}const bg="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 He=class{constructor(e){a(this,"id");a(this,"troubles");this.id=e,this.troubles=new fe({indexMap:{[X.INDEX_TROUBLES_BY_IFACE]:ug,[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(){Yr.debug("loading trouble container");const e=await Na();try{e==null||e.data.forEach(t=>{const s={...t,rank:zr(t),color:qr(t),role:Wr(t),id:String(t.id)},o=Ct.factory(`trouble-${t.id}`)(s);this.troubles.addModel(o)})}catch(t){throw Yr.error(t),t}}handleTroubleRemoved(e){const t=`trouble-${e}`,s=this.troubles.getModel(t);this.troubles.removeModel(t),s&&$e(s)}handleTroubleAdded(e){const t={...e,rank:zr(e),color:qr(e),role:Wr(e),id:String(e.id)};if(t.role==="NONE")return;const s=Ct.factory(`trouble-${e.id}`)(t);this.troubles.addModel(s)}};Bs([ce],He.prototype,"troubles",2);Bs([R({topic:"/kos/trouble/remove",websocket:!0,lifecycle:U.INIT})],He.prototype,"handleTroubleRemoved",1);Bs([R({topic:"/kos/trouble/add",websocket:!0})],He.prototype,"handleTroubleAdded",1);He=Bs([S(bg)],He);const Jt="trouble-container-model",Ve={registration:{[Jt]:{class:He,singleton:!0}},type:Jt,predicate:ee(Jt),factory:G.Singleton.create(Jt)},{URL:Ba}=z(),{getAll:wg}=H.build({basePath:`${Ba}/api/kos/ota`}),Zr=f.createLogger({name:"ota-service",group:"Services"}),vg=async()=>{Zr.debug("sending GET request to /api/kos/ota/artifacts");const e=await wg({urlOverride:`${Ba}/api/kos/ota/artifacts`});return Zr.debug("getArtifacts - response:",e),e==null?void 0:e.data};var Mg=Object.defineProperty,_g=Object.getOwnPropertyDescriptor,Ks=(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="ota-model",Eg=e=>{let t=null;for(const s in e){const o=e[s],r=o.lastUpdateTime;(!t||t.lastUpdateTime<r)&&(t=o)}return t},no=e=>{const t=e.artifactInfo,s=Eg(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 Ye=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"data",new Li);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 vg();e&&e.forEach(t=>{const s=no(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=no(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=no(t);s&&this.data.updateModel(s)})}catch(t){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,t)}}};Ks([Ut({modelType:Ve.type})],Ye.prototype,"troubleContainer",2);Ks([R({topic:"/kos/ota/artifacts/all",websocket:!0})],Ye.prototype,"handleAllArtifacts",1);Ks([R({topic:"/kos/ota/artifacts/changed",websocket:!0})],Ye.prototype,"handleChangedArtifacts",1);Ye=Ks([S(Ka)],Ye);const vs=new we({class:Ye,type:Ka}),Qr=f.createLogger({name:"software-info-service",group:"Services"}),Ga=async()=>{Qr.debug("sending GET for software-info");const[e,t]=await aa.get("/api/kos/manifest/info");if(!t)throw Qr.error("Failed to fetch software-info",e),new ne("Failed to fetch software-info");return t},Ig=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:Ga},Symbol.toStringTag,{value:"Module"}));var Tg=Object.defineProperty,$g=Object.getOwnPropertyDescriptor,Og=(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 at="software-info-model";let bo=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 Ga(),t=(e==null?void 0:e.nodes)||{};V(()=>{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 ne&&this.logger.error("Failed to fetch software-info",e)}}};bo=Og([S(at)],bo);const Ms={registration:{[at]:{class:bo,singleton:!1}},type:at,predicate:ee(at),factory:G.Factory.create(at)},{URL:Ha}=z(),{getOne:Dg}=H.build({basePath:`${Ha}/api/kos/state`}),Sg=f.createLogger({name:"state-bean-service",group:"Services"}),Va=async({path:e})=>(Sg.debug("sending GET for state-bean"),await Dg({urlOverride:`${Ha}/api/kos/state/${e}`})),Ag=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:Va},Symbol.toStringTag,{value:"Module"}));var Cg=Object.defineProperty,Rg=Object.getOwnPropertyDescriptor,Ya=(e,t,s,o)=>{for(var r=o>1?void 0:o?Rg(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&&Cg(t,s,r),r};const ct="state-bean-model",Lg=De("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=Go.map(new Map),co(t,this)}updateModel(e){co(e,this)}handleConfigBeanUpdated(e){Object.entries(e).forEach(([t,s])=>{let o=s;typeof o=="string"&&Yo(o)&&(o=o.toLowerCase()=="true"),typeof o=="string"&&xs(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 Va({path:this.path});e!=null&&e.data&&this.updateProps(e.data)}};Ya([R({topic:`/kos/state/${Lg}`,websocket:!0})],_s.prototype,"handleConfigBeanUpdated",1);_s=Ya([S(ct)],_s);const Rt={registration:{[ct]:{class:_s,singleton:!1}},type:ct,predicate:ee(ct),factory:G.Factory.create(ct)};var Pg=Object.defineProperty,kg=Object.getOwnPropertyDescriptor,za=(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&&Pg(t,s,r),r};const lt="state-prop-model",Xr=De("path");let Es=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())??""}};za([Ut({modelType:Rt.type,id:`state-bean-${Xr}`,options:{path:Xr}})],Es.prototype,"stateBean",2);Es=za([S(lt)],Es);const nr={registration:{[lt]:{class:Es,singleton:!1}},type:lt,predicate:ee(lt),factory:G.Factory.create(lt)},{URL:xg}=z(),{getAll:Ng}=H.build({basePath:`${xg}/api/state-prop`}),Fg=f.createLogger({name:"state-prop-service",group:"Services"}),Ug=async()=>(Fg.debug("sending GET for state-prop"),await Ng({})),jg=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:Ug},Symbol.toStringTag,{value:"Module"})),{URL:ir}=z(),{getOne:qa}=H.build({basePath:`${ir}/api/translation`}),It=f.createLogger({name:"translation-service",group:"Services"}),Bg=()=>{const e=window.location.origin,t=ae();return(t==null?void 0:t.host)||e},Wa=async(e,t)=>{It.debug("sending GET for translation");const s=t??Bg();try{const o=await fetch(`${s}${e}`);return o.status!==200?(It.warn(`Failed to fetch translations at ${e}: ${o.status}`),{}):await o.json()}catch(o){throw It.error("Error fetching translations",o),o}},Kg=async()=>{It.debug("getting localization descriptor");const e=await qa({urlOverride:`${ir}/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},Za=e=>async()=>{It.debug("getting kos localization descriptor");const t=await qa({urlOverride:`${ir}/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]},Qa="langResolver";var Gg=Object.defineProperty,Hg=Object.getOwnPropertyDescriptor,Vg=(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&&Gg(t,s,r),r};const dt="translation-model";function Yg(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 Xa(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=Xa(e[o],r);return{...s,...n}}else return{...s,[r]:e[o]}},{})}function Ja(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]=Ja(e[o],t[o]):s[o]=t[o]);return s}const wo=(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)?wo(o,t):o},es=(e,t,s)=>{const o=/{{(.*?)}}/g,n=wo(e,t).replace(o,(c,l)=>Object.prototype.hasOwnProperty.call(s||{},l.trim())?s==null?void 0:s[l.trim()]:c);return wo(n,t)},Jr=(e,t)=>{if(t.includes(":")){const[s,o]=t.split(":");return{namespace:s,key:o}}else return{namespace:e,key:t}};let vo=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(Qa),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=P.getContext(this.id);return this.bundleResolver(this.namespace,o,r)}try{const r=this.resolver(this.namespace,o);return Wa(r,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(t);V(()=>{const o=s.reduce((r,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${e[i]}`,n.value),n.value&&(r=Ja(r,n.value))):this.logger.error(`failed to load translation ${this.id} for ${e[i]}`),r),{});this.data=Xa(o)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(e){const{namespace:t,key:s}=Jr(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.warn("key is empty"),"";const{defaultValue:s,context:o,data:r}=Yg(t),{namespace:n,key:i}=Jr(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=>es(d,this.data,r)):es(this.data[c],this.data,r)}if(this.data[i]){const l=this.data[c];return Array.isArray(l)?l.map(d=>es(d,this.data,r)):es(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=w.reaction(()=>this.currentLocale,(e,t)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${t} to ${e}`),this.loadTranslations()})}};vo=Vg([Ps(),S(dt)],vo);const Is={registration:{[dt]:{class:vo,singleton:!1}},type:dt,predicate:ee(dt),factory:G.Factory.create(dt)};var zg=Object.defineProperty,qg=Object.getOwnPropertyDescriptor,ec=(e,t,s,o)=>{for(var r=o>1?void 0:o?qg(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&&zg(t,s,r),r};const ut="translation-container-model",Wg=(e,t="/")=>e.join(t).replace(new RegExp(t+"{1,}","g"),t);function Zg(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 Wg([o,r])}let Ts=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||Zg.bind(this),s.kosContext.set(Qa,this.resolver),this.logger=s.logger,this._models=new fe({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 bi(this);for(const e of this.namespaces){const t=this.resolveNamespace(e);await Z(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=Is.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)||V(()=>{this.namespaces.push(e)}),n}else{this.logger.warn(`namespace ${e} not found in descriptor`);const o=Is.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}`)}};ec([ce],Ts.prototype,"_models",2);Ts=ec([S(ut)],Ts);const he={registration:{[ut]:{class:Ts,singleton:!0}},type:ut,predicate:ee(ut),factory:G.Singleton.create(ut)},Qg={set(e,t){const s=P.getContext(he.type);s&&s.set(e,t)},get(e){const t=P.getContext(he.type);return t==null?void 0:t.get(e)}},tc={async init(e){const t=he.factory(e);return await Z(t),{translations:t}}},Xg=(e,t)=>{const s=t.type;return e[s]||(e[s]=[]),e[s].push(t),e},sc="kos-ws-event",ar=Qe(sc);var Jg=Object.defineProperty,ef=Object.getOwnPropertyDescriptor,cr=(e,t,s,o)=>{for(var r=o>1?void 0:o?ef(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&&Jg(t,s,r),r};const tf=({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=w.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:tf({headers:r,body:o}),direction:s?"send":"receive",mocked:!!r.mocked};this.events.set(c,l),f.debug(`logged ${this.events.size} events`)}}};cr([R({topic:[Nt.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);cr([R({topic:[Nt.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=cr([S(ar.type)],exports.WsEventModel);const{URL:lr}=z(),{getOne:oc}=H.build({basePath:`${lr}/api/device`}),$s=f.createLogger({name:"device-service",group:"Services"}),rc=async()=>{$s.debug("sending GET for device serial number");try{const e=await oc({urlOverride:`${lr}/api/kos/device/serialNumber`});return[void 0,e==null?void 0:e.data.serialNumber]}catch(e){if(e instanceof ne)return $s.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},nc=async()=>{$s.debug("sending GET for device details");try{const e=await oc({urlOverride:`${lr}/api/kos/device`});return e?[void 0,e.data]:["unknownError",void 0]}catch(e){if(e instanceof ne)return $s.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},sf=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:nc,getSerialNumber:rc},Symbol.toStringTag,{value:"Module"}));var of=Object.defineProperty,rf=Object.getOwnPropertyDescriptor,ic=(e,t,s,o)=>{for(var r=o>1?void 0:o?rf(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&&of(t,s,r),r};const ac="device-model",nf="/kos/criticalData/changed",af="/kos/criticalData/available";let Os=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 nc();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 rc();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()}};ic([R({topic:[nf,af],websocket:!0})],Os.prototype,"handleCriticalDataChanged",1);Os=ic([S(ac)],Os);const Ds=new we({class:Os,type:ac});var cf=Object.defineProperty,lf=Object.getOwnPropertyDescriptor,df=(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 cc="network-interface-model";let Mo=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}`)}};Mo=df([S(cc)],Mo);const dr=new le({class:Mo,type:cc}),{URL:uf}=z(),{getAll:hf}=H.build({basePath:`${uf}/api/kos/network/interfaces`}),en=f.createLogger({name:"network-interface-service",group:"Services"}),lc=async()=>{en.debug("sending GET for copy-logs");try{const e=await hf({});return[void 0,e==null?void 0:e.data]}catch(e){if(e instanceof ne)return en.error(`Error fetching log file size: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},gf=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:lc},Symbol.toStringTag,{value:"Module"}));var ff=Object.defineProperty,mf=Object.getOwnPropertyDescriptor,dc=(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&&ff(t,s,r),r};const uc="network-interface-container-model";let Ss=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new fe({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 lc();if(e){this.logger.error(`Error loading network interfaces: ${e}`);return}t&&t.forEach(s=>{const o=dr.instance(s.name).forceUpdate.options(s).build();this.addModel(o)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};dc([ce],Ss.prototype,"_models",2);Ss=dc([S(uc)],Ss);const Lt=new we({class:Ss,type:uc});Lt.addRelatedModel(dr);const{URL:pf}=z(),{getAll:yf}=H.build({basePath:`${pf}/api/kos/storage/devices`}),tn=f.createLogger({name:"storage-device-service",group:"Services"}),hc=async()=>{tn.debug("sending GET for storage-device");const e=await yf({});return!(e!=null&&e.data)||e.status!==200?(tn.error("Failed to retrieve storage-device data",e),[]):e.data},bf=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:hc},Symbol.toStringTag,{value:"Module"}));var wf=Object.defineProperty,vf=Object.getOwnPropertyDescriptor,Mf=(e,t,s,o)=>{for(var r=o>1?void 0:o?vf(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&&wf(t,s,r),r};const gc="storage-device-model";let _o=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}`)}};_o=Mf([Ps(),S(gc)],_o);const As=new le({class:_o,type:gc});var _f=Object.defineProperty,Ef=Object.getOwnPropertyDescriptor,ur=(e,t,s,o)=>{for(var r=o>1?void 0:o?Ef(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 fc="storage-device-container-model",If="/kos/storage";let Pt=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new fe({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=As.instance(s.id).options(r).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await hc()).forEach(t=>{const s={...t,kosParentId:this.id},o=As.instance(t.id).options(s).build();this.addModel(o)})}};ur([ce],Pt.prototype,"_models",2);ur([R({topic:If,websocket:!0})],Pt.prototype,"handleStorageAvailability",1);Pt=ur([S(fc)],Pt);const ze=new we({class:Pt,type:fc});ze.addRelatedModel(As);const{URL:hr}=z(),{getAll:Tf,postModel:$f}=H.build({basePath:`${hr}/api/kos/update/available`}),sn=f.createLogger({name:"usb-update-service",group:"Services"}),mc=async()=>{sn.debug("sending GET for usb-update");const e=await Tf({urlOverride:`${hr}/api/kos/update/available`});return!(e!=null&&e.data)||(e==null?void 0:e.status)!==200?(sn.error("Failed to retrieve usb-update data",e),[]):e.data},pc=async(e,t,s)=>{const o=await $f({model:{manifestId:e,deviceId:t},tracker:s,urlOverride:`${hr}/api/kos/update/install`});if(!(o!=null&&o.data))throw new Error("No response from server");return o.data},Of=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:mc,installUpdate:pc},Symbol.toStringTag,{value:"Module"}));var Df=Object.defineProperty,Sf=Object.getOwnPropertyDescriptor,yc=(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 bc="usb-update-model";let Cs=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 Zo(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}`),pc(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}`)}};yc([yr()],Cs.prototype,"install",1);Cs=yc([S(bc)],Cs);const gr=new le({class:Cs,type:bc});var Af=Object.defineProperty,Cf=Object.getOwnPropertyDescriptor,Gs=(e,t,s,o)=>{for(var r=o>1?void 0:o?Cf(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&&Af(t,s,r),r};const wc="usb-update-container-model";let qe=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 fe({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 mc();V(()=>{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=gr.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}`)}};Gs([Ut({modelType:ze.type})],qe.prototype,"storageService",2);Gs([ce],qe.prototype,"_models",2);Gs([ei({dependencies:e=>[e.isUsbInserted]})],qe.prototype,"usbInsertedEffect",1);qe=Gs([S(wc)],qe);const kt=new we({class:qe,type:wc});kt.addRelatedModel(gr);const Rf=()=>({...{[Je.type]:{class:ia},[ye.type]:{class:ga,singleton:!0},...Y.registration,...Se.registration,...Ve.registration,...Is.registration,...he.registration,[ar.type]:{class:exports.WsEventModel,singleton:!0},...Rt.registration,...nr.registration,...ms.registration}}),fr=Rf(),Lf={models:fr,preloadModels:[]},Pf=!0,vc=e=>()=>{const t=fr;return _i(Eo)(Ct).model(Ve).model(ze).model(kt).model(Ds).model(vs).model(Tt).model(Ms).model(sr).model(Lt).model(da,Pf).model(Gt),Object.keys(t).forEach(s=>{const o=t[s];Mi(Eo)(s,o)}),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e)}},re={};re.core={models:vc(re)};re.preload=$.model.preloadModel(re);re.model=$.model.register(re);re.companion=$.companion.register(re);re.legacy=$.model.registerLegacyModel(re);const Eo=re;class kf{registerTroubleRankMapper(t){return C.propertyMapper.registerPropertyMapper(oe.TroubleRank,t),this}registerTroubleRoleMapper(t){return C.propertyMapper.registerPropertyMapper(oe.TroubleRole,t),this}registerTroubleColorMapper(t){return C.propertyMapper.registerPropertyMapper(oe.TroubleColor,t),this}}const xf=async(e,t)=>{const s=sr.instance(e).options({}).build(),o=t?`${t}-`:"";return await Z(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:()=>{$e(s)}}},Mc="kos:service:region",_c="regionId",Nf=`${Mc}-${_c}`,Ec=async e=>{const t=Se.factory(Nf)({path:Mc,attribute:_c});await Z(t),t.updateProperty(e)},mr="/kos-timer-event",pr="defaultTimerEnd",ht=f.createLogger({name:"timer-manager"}),Ff=e=>e.updateProperty!==void 0;class Ic{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,Ff(s)&&x(()=>{f.info(`Updating config value timer ${t} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:pr}),o&&o.forEach(n=>{this.addTimeoutAction(n)})}start(){if(this.state==="active"){ht.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&&(ht.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;ht.debug(`Executing timer action ${s.name} at ${t}`),(o=s.action)==null||o.call(s,s.name,t),this.notifyTimeoutAction(s),s.singleUse&&(ht.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))})}notifyTimeoutAction(t){K(mr,{name:this.name,action:t.name,remainingTime:this.remainingTime})}}const gt=new Map,ke=(e,t)=>{const s=gt.get(e);if(!s){ht.error(`Timer ${e} not found`);return}t(s)},Tc={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(gt.has(e))return gt.get(e);const o=new Ic(e,t,s);return gt.set(e,o),o},getTimer(e){return gt.get(e)},clearTimer(e){ke(e,t=>t.pause())},restartTimer(e){ke(e,t=>t.restart())},resetTimer(e){ke(e,t=>t.reset())},addTimeoutAction(e,t){ke(e,s=>s.addTimeoutAction(t))},removeTimeoutAction(e,t){ke(e,s=>s.removeTimeoutAction(t))},startTimer(e){ke(e,t=>t.start())}},$c="kos:service:region:settings",Oc="timeZone",Uf=`${$c}-${Oc}`,Io=async e=>{const t=Se.factory(Uf)({path:$c,attribute:Oc});await Z(t),t.updateProperty(e)},jf=e=>!e||!e.data;function yr(e={}){const{alias:t,namespace:s}=e;return(o,r,n)=>{o[Fe]=o[Fe]||{};const i=n.value,c=async function(...l){const d=Ft();f.debug(`Calling future service ${r} with tracker ${d}`);const u=Oe.initiateFuture({tracker:d,id:Ho});s&&(u.namespace=s),f.debug(`waiting for future ${u.id} to be ready`),await Z(u),f.debug(`future ${u.id} is ready`),V(()=>{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 y=jf(h)?h:h==null?void 0:h.data;return y?(y.progress=1,f.debug("mapping future response to future model"),u.endState?f.debug(`future ${u.id} has already completed. Not updating the model`):Xo(y,u)):this.futureHandler.removeFuture(t),y}catch(h){throw f.error(h),h}};o[Fe][r]={handler:c}}}const Bf=({path:e})=>(t,s)=>{t[k]=t[k]||{},t[k][s]={modelType:Rt.type,id:`${Rt.type}-${e}`,options:{path:e},lifecycle:U.INIT}};function Kf(e){const{path:t,attribute:s}=e;return(o,r)=>{o[k]=o[k]||{},o[k][r]={modelType:nr.type,id:`${t}-${s}`,options:{path:t,attribute:s},lifecycle:U.INIT}}}const je=f.createLogger({name:"services",group:"Services"}),Gf=async(e,t)=>Dc(e,t,`${exports.BASE_URL}/api/server/login`),Dc=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()},Hf=async e=>Sc(e,`${exports.BASE_URL}/api/server/startPasswordReset`,""),Sc=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()},Vf=async(e,t)=>Ac(e,t,`${exports.BASE_URL}/api/server/resetPassword`),Ac=async(e,t,s=`${exports.BASE_URL}/api/resetPassword`)=>{je.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(je.debug(`password reset returned status ${o.status}`),!o.ok){je.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()},Yf=async(e,t,s)=>Cc(e,t,s,`${exports.BASE_URL}/api/server/acceptInvite`),Cc=async(e,t,s,o=`${exports.BASE_URL}/api/server/acceptInvite`)=>{je.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(je.debug(`invitation accept returned status ${r.status}`),!r.ok){je.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()},zf=Ie.keyframes`
77
+ ["${t}"]`;if(o?(y=this.fosSocket)==null?void 0:y.connectionEstablished:(v=this.socket)==null?void 0:v.connectionEstablished){const E=o?this.fosSocket:this.socket;(b=E==null?void 0:E.socket)==null||b.send(d)}else{_e.debug("no connection adding to offline messages");const E=o?this.fosSocket:this.socket;E==null||E.addOfflineMessage(d)}}subscribeTopic({topic:t,callback:s,fos:o,bridge:r}){const{unsubscribe:n,count:i}=U(t,s);return _e.debug(`Topic ${t} currently has ${i} subscribers`),this._sendSubscriptionMessage(t,"subscribe",o,r),()=>{const{count:c}=n();_e.debug(`Topic ${t} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(t,"unsubscribe",o)}}async whenReady(){const t=this;return this.webSocketSupported?(await w.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(xs,"_instance");class tu{constructor(t,s,o,r,n){a(this,"disposers",[]);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.resolveTopic(n);this.log.debug(`Resolved topic: ${n} → ${l}`);const d=this.createHandler(l,i);this.subscribe(i,l,d)})}disposeAll(){this.log.debug(`Disposing ${this.disposers.length} subscriptions for ${this.modelId}`);for(const t of this.disposers)try{t()}catch(s){this.log.error("Error during subscription disposal",s)}this.disposers=[]}subscribe(t,s,o){if(t.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const r=xs.getInstance().subscribeTopic({topic:s,callback:o,fos:t.fos,bridge:t.bridge});this.disposers.push(r)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:r}=U(s,o);this.disposers.push(r)}}createHandler(t,s){return o=>{try{if(this.model.isReady()){const r=go(o,s.skipParse),n=s.transform(r);s.condition(n,this.modelData,o)&&s.handler.call(this.modelData,n,o,this.modelData)}else{this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${t}`);const r=()=>{const n=go(o,s.skipParse),i=s.transform(n);s.condition(i,this.modelData,o)&&s.handler.call(this.modelData,i,o,this.modelData)};this.offlineQueue.enqueue(r)}}catch(r){this.log.error(`Error handling subscription for ${t}`,r)}}}resolveTopic(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 st(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 su(e){return!!(e!=null&&e[$e])&&Object.keys(e[$e]).length>0}function ou(e){return!!(e!=null&&e[G])&&Object.keys(e[G]).length>0}class ru{static createAll(t){const{modelId:s,modelTypeName:o,modelData:r}=t,n=Bd.create({modelId:s,modelTypeName:o}),i=new jd(t,st(n,"fsm")),c=new Kd(st(n,"offline-queue")),l=new Rd(t),d=new Cd(t),u={fsm:i,offlineQueue:c,companionManager:l,childResolver:d};if(su(r)&&(u.effectManager=new Ld(o,s,r,st(n,"effect"))),ou(r)){const g=st(n,"subscription");u.subscriptionManager=new tu(t,r,s,c,g),u.onlineLifecycleManager=new Gd(t,st(n,"online"))}return u}}const A=I.getLogger("kos-model"),Fr="kos.extension.model.loader";class wi{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=p.CREATED,this._activeStatus=p.INACTIVE,this._onlineStatus=p.OFFLINE;const r=ru.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),w.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),Sd(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===p.ACTIVE}isOnline(){return this._onlineStatus===p.ONLINE}isReady(){return this._status===p.READY}async deactivate(){var t,s;A.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=P.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.deactivate)==null?void 0:s.call(t,o)),A.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`)}catch(o){throw A.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var t,s;A.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await nt(this,F.ACTIVATE);try{const o=P.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.activate)==null?void 0:s.call(t,o)),A.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(o){throw A.debug(`Model ${this.modelId} failed to activate`),o}}async whenInitialized(){await kr([{condition:()=>this.status===p.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{A.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await kr([{condition:()=>this.status===p.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===p.READY,onMatch:()=>{A.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var t,s,o;if(this.fsm.current===p.READY){A.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{A.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await nt(this,F.READY),await ni(this,Uo.READY,F.READY);const r=P.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(F.READY),A.debug(`Model ${this.modelId} is ready`);const n={modelId:this.modelId,modelType:this.modelTypeName};j(Yn(this.modelTypeName,this.modelId),n),j(zn(this.modelTypeName),n)}catch(r){throw A.error(r),Error(r)}}async load(){var o,r,n,i;const{modelTypeName:t,modelId:s}=this;if(this.fsm.current===p.LOADED||this.fsm.current===p.LOADING){A.debug(`Model ${t} with id ${s} already loaded or loading`);return}A.debug(`Loading model ${t} with id ${s}`),await nt(this,F.LOAD);try{const c=P.getContext(s),l=await C.loader.executeLoader(Fr,{});l&&(A.info(`Setting loaded context for ${s}, type: ${t}`),c==null||c.set(Fr,l)),await((r=(o=this.modelData)==null?void 0:o.load)==null?void 0:r.call(o,c)),this.loaded=!0,A.debug(`Model ${t} with id ${s} successfully loaded`),(n=this.subscriptionManager)==null||n.registerAll(F.LOAD),(i=this.effectManager)==null||i.setup()}catch(c){throw A.error(`Model ${s} failed to load`,c),c}}async unload(){var t,s,o,r,n;A.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=P.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(),A.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(r=this.effectManager)==null||r.disposeAll(),(n=this.subscriptionManager)==null||n.disposeAll()}catch(i){throw A.debug(`Model ${this.modelId} failed to unload`),i}}async init(){var r,n,i;const{modelId:t,modelTypeName:s}=this,o=P.getContext(t);A.debug(`Initializing model ${s} with id ${t}`),await nt(this,F.INIT);try{await((n=(r=this.modelData)==null?void 0:r.init)==null?void 0:n.call(r,o)),this.initialized=!0,A.debug(`Model ${s} with id ${t} initialized`),(i=this.onlineLifecycleManager)==null||i.register(),this.registerSubscribers(F.INIT)}catch(c){throw A.error(`Model ${t} failed to initialize`,c),c}}async registerSubscribers(t){var s;A.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(t)}async online(){var s,o;A.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const t=P.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;A.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const t=P.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 vi=e=>typeof e=="function",Ur=f.createLogger({name:"kos-model-instantiator"});class nu{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)){Ur.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 wi({modelTypeName:t,id:n,modelData:c});this.cache.addModel(l),this._createCompanionModels(l,o)}const i=this.cache.getModelById(n);if(!i)throw Ur.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=vi(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 Je(t)}};const Mi=10,jr=f.createLogger({name:"kos-model-manager"});class Ei{constructor(){a(this,"cache");a(this,"instantiator");a(this,"dependencies");a(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new dd,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 ud(t.preloadModels),o.instantiator=new nu(t,o.cache),o}static getInstance(t){var s,o;return(!((s=globalThis.kos)!=null&&s.modelManager)||t)&&(jr.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=>(jr.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 Je(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(O.RESET,p.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),Fn.addToDeletionQueue(t.id,setTimeout(()=>this.destroyModel(s),Mi)))}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 au=async({context:e,extension:t})=>{const s=await C.loader.executeLoader(t,{});return e==null||e.set(t,s),s},cu=async({extension:e,contextData:t,data:s})=>await C.dataMapper.executeMapper(e,s,t),lu=async({extension:e,contextData:t,data:s})=>await C.propertyMapper.executeMapper(e,s,t),du=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:cu,executeLoaderExtension:au,executePropertyMapperExtension:lu},Symbol.toStringTag,{value:"Module"})),uu="Extensions";class hu{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 ns=(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))(ns||{}),Ne=(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))(Ne||{});const gu=e=>{const t=m.createMachine("offline",{online:m.state(m.transition("go_offline","offline",m.action(()=>{e.offline(),w.runInAction(()=>{e.isOnline=!1})}))),offline:m.state(m.transition("go_online","online",m.action(()=>{e.online(),w.runInAction(()=>{e.isOnline=!0})})))}),s=m.interpret(t,n=>I.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(()=>{w.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=>I.debug(n.machine.current)),online:s}},J=async e=>{if(e.id){const t=_.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 _.getInstance().whenReady(),await _.getInstance().modelManager.initiateDestroyModel(e)},fu=async e=>{if(await _.getInstance().whenReady(),!e.id)throw new Error("Model ID is required");const t=_.getInstance().modelManager.getModelById(e.id);t&&await t.fsm.transitionTo(O.UNLOAD,p.UNLOADED)},_i=async e=>{await _.getInstance().whenReady(),await _.getInstance().modelManager.reloadModel(e),f.debug(`reload model initiated for model ${e.id}, model ready: ${us(e)} - ${Date.now()} `),await J(e),f.debug(`reload model complete for model ${e.id}, model ready: ${us(e)} - ${Date.now()} `)},mu=async e=>{if(await _.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=_.getInstance().modelManager.getModelById(e);return t==null?void 0:t.modelTypeName},Ii=async e=>{if(await _.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=_.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},Ze=e=>{if(!e)throw new Error("Model ID is required");const t=_.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},Ti=(e,t)=>{if(!e)throw new Error("Model type is required");return _.getInstance().modelManager.getModelsByType(e).filter(r=>Object.keys(t).every(n=>r[n]===t[n]))},pu=(e,t)=>Ti(e,t)[0],yu=(e,t)=>{if(!e.id)throw new Error("Model ID is required");const s=_.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},bu=e=>{if(!e.id)throw new Error("Model ID is required");const t=_.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return Array.from(t.companionModels.all()).map(o=>o.modelData)},wu=e=>{if(!e)throw new Error("Model ID is required");const t=_.getInstance().modelManager.getModelById(e);if(!t)throw new Error("Model not found");return t.companionModels.data},mo=(e,t)=>{const s=_.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))},ee=e=>t=>Object.getPrototypeOf(t).modelTypeId===e,us=e=>{const t=_.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return t.isReady()},vu=f.createLogger({name:"kos-model-factory"}),_t={byModelType:e=>_.getInstance().modelManager.getModelFactory(e),getModelInstance:(e,t,s)=>{const o=_t.byModelType(t);if(!o)throw vu.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&&P.setParentContext(t,o),_t.getModelInstance(t,e,s))},Singleton:{create:e=>(t,s)=>(s&&P.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 Br=window.KosRegistry.coreModels,to=window.KosRegistry.preloadModels,so=window.KosRegistry.companionModels,qt=window.KosRegistry.models,T={model:{registerLegacyModel:e=>(t,s)=>(Br.set(t,s),{preload:T.model.preloadModel(e),model:T.model.register(e),companion:T.companion.register(e),legacy:T.model.registerLegacyModel(e),root:e}),preloadModel:e=>t=>(to.includes(t)||to.push(t),{preload:T.model.preloadModel(e),model:T.model.register(e),companion:T.companion.register(e),legacy:T.model.registerLegacyModel(e),root:e}),register:e=>(t,s)=>{const o=oo(t)?t.registration():t;return qt.set(o.type,o),oo(t)&&t.relatedModels.forEach(r=>qt.set(r.type,r.registration())),_.getInstance().isReady&&(_.getInstance().modelManager.registry.models[o.type]||(console.info(`Model with type ${o.type} doesn't exist. Adding new registration`),_.getInstance().modelManager.registry.models[o.type]=o.registration[o.type],oo(t)&&t.relatedModels.forEach(r=>_.getInstance().modelManager.registry.models[r.type]=r.registration().registration))),s&&T.model.preloadModel(e)(o.type),{preload:T.model.preloadModel(e),model:T.model.register(e),companion:T.companion.register(e),legacy:T.model.registerLegacyModel(e),root:e}},get:e=>qt.get(e),getAll:()=>Array.from(qt.entries()),getPreloadModels:()=>to,getLegacyModels:()=>Array.from(Br.entries()).reduce((e,[t,s])=>(e[t]=s,e),{})},companion:{register:e=>(t,s)=>{const o=so.get(t)||[];return o.push(s),so.set(t,o),{preload:T.model.preloadModel(e),model:T.model.register(e),companion:T.companion.register(e),legacy:T.model.registerLegacyModel(e),root:e}},getAll:()=>Array.from(so.entries())}},$i=T.model.registerLegacyModel,Oi=T.model.register,Mu=T.companion.register,Eu=T.model.preloadModel,Di=e=>typeof e.updateModel=="function",oo=e=>e.registration!==void 0&&typeof e.registration=="function";class Si{constructor(t){a(this,"singleton");a(this,"type");a(this,"class");a(this,"guard");a(this,"factory");a(this,"relatedModels",[]);this.singleton=t.singleton,this.guard=ee(t.type),this.type=t.type,this.factory=t.factory,this.class=t.class}addRelatedModel(t){this.relatedModels.push(t)}registerRelatedModels(){this.relatedModels.forEach(t=>t.register())}register(){T.model.register({})(this.registration()),this.registerRelatedModels()}}class le extends Si{constructor(t){super({...t,singleton:!1,factory:H.Factory.create(t.type)})}instance(t){const s=this.factory(t);return{get:()=>{const o=Ze(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(Di(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 we extends Si{constructor(t){super({...t,singleton:!0,factory:H.Singleton.create(t.type)})}instance(){const t=this.factory;return{get:()=>{const o=Ze(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)},forceUpdate:{options:o=>({build:()=>{const r=t(o);if(this.guard(r)){if(Di(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=t(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:!0}},factory:this.factory}}}const N=f.createLogger({name:"kos-core"}),_u=()=>{const e=window.location.protocol,t=ae(),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://")},Iu=()=>{const e=window.location.hostname,t=process.env.KOS_HOST,s=ae(),o=s==null?void 0:s.host;let r;try{r=new URL(o).hostname}catch{}return r??t??e},Tu=()=>{const e=window.location.port,t=process.env.KOS_PORT,s=ae(),o=s==null?void 0:s.host;let r;try{r=new URL(o).port}catch{}return r??t??e},$u=(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)}}},Kr=e=>typeof e.reload=="function",Ou=e=>typeof e.unload=="function";var Ai=(e=>(e.LOGGED_IN="logged_in",e.LOGGED_OUT="logged_out",e))(Ai||{});class _{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=ns.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,w.makeAutoObservable(this),U("token",c=>{c&&(this.transport.token=c.body)}),U(Et.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(Ne.GO_ONLINE)}),U(Et.DISCONNECTED,async()=>{this.fsmService.service.send(Ne.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(Et.RELOAD,()=>{this.fsmService.service.send(Ne.RELOAD)}),U("/studio/project/reload",()=>{this.fsmService.service.send(Ne.RELOAD)});const s=xs.getInstance(),o=Iu(),r=Tu(),n=_u();s.host=o,s.port=Number.parseInt(r),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=t||process.env.KOS_CONNECTION_ALIAS;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=gu(this),this.fsmService.service.send(Ne.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;const t=Date.now();if(this._reloading){N.info("reload already in progress");return}this._reloading=!0,N.warn("reloading KOS Core"),N.warn("reloading preloaded models");const s=this.modelManager;for(const i of s.preloadedModels)Kr(i.modelData)&&(N.info(`reloading model ${i.modelId}`),(r=i.unload)==null||r.call(i),await i.modelData.reload(),N.info(`reloading model ${i.modelId} complete`));for(const i of s.models)!s.preloadedModels.includes(i)&&Kr(i.modelData)&&((n=i.unload)==null||n.call(i),await i.modelData.reload());const o=Date.now()-t;setTimeout(()=>{w.runInAction(()=>{N.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-o)}async online(){N.debug("KOS Core going online"),await this._transport.whenReady(),N.debug("KOS Transport Ready. Calling online() for models"),j("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){N.debug("KOS Core going offline"),j("/kosCore/offline","/kosCore/offline")}async unload(){var r;N.debug("Unloading KOS Core");const t=Date.now();this._unloading=!0,N.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)Ou(n.modelData)&&((r=n.unload)==null||r.call(n));const o=Date.now()-t;setTimeout(()=>{w.runInAction(()=>{this._unloading=!1})},1e3-o)}async whenReady(){await w.when(()=>this.status===ns.READY)}async ready(){N.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}=$u(5e3,r.model);Promise.race([r.promise.then(()=>{i()}),n])}))).filter(r=>r.status==="rejected");if(o.length)throw N.error(`There were ${o.length} failed models on model preloading`),Error(`There were ${o.length} failed models on model preloading`);N.debug("leaving kos-core ready() ")}get isReady(){return this.status===ns.READY}set transport(t){this._transport=t}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){N.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,N.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){N.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,N.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 g,y;const u=(y=(g=t.extensions)==null?void 0:g.dataMapper)==null?void 0:y[d];u&&(Array.isArray(u)?u.forEach(v=>{C.dataMapper.registerDataMapper(d,v)}):C.dataMapper.registerDataMapper(d,u))}),(c=t.extensions)!=null&&c.propertyMapper&&Object.keys(t.extensions.propertyMapper).forEach(d=>{var g,y;const u=(y=(g=t.extensions)==null?void 0:g.propertyMapper)==null?void 0:y[d];u&&C.propertyMapper.registerPropertyMapper(d,u)}),(l=t.extensions)!=null&&l.contextLoader&&Object.keys(t.extensions.contextLoader).forEach(d=>{var g,y;const u=(y=(g=t.extensions)==null?void 0:g.contextLoader)==null?void 0:y[d];u&&C.loader.registerLoader(d,u)}),T.model.getAll().forEach(([,d])=>{t.models={...t.models,...d.registration}}),t.models={...t.models,...T.model.getLegacyModels()},T.companion.getAll().forEach(([d,u])=>{t.companionModels={...t.companionModels},t.companionModels[d]=t.companionModels[d]||[];for(const g of u)t.companionModels[d].push({type:g})}),T.model.getPreloadModels().forEach(d=>{t.preloadModels.includes(d)||t.preloadModels.push(d)});const n=Ei.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(_,"_instance");const Gr=f.createLogger({name:"kos-fetch"}),Du=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,Su=()=>new Promise(e=>{setTimeout(()=>{e(!0)},0)}),Au=e=>e!=null&&e.studio?ai:e!=null&&e.fos?ci:li,Cu=async(e,t)=>{const s=_.getInstance().transport;await s.whenReady();const o=jt(),r=new URL(e),n=`${r.pathname}${r.search}`;Gr.debug(`path: ${n}`);const i=(t==null?void 0:t.timeout)||Du,c=Au(t),l=be(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,g=setTimeout(()=>{Gr.error(`Timeout occurred - url: ${e}`),u.abort(),d({headers:uo({}),status:404,ok:!1,json:async()=>null,body:ho(""),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:y}=U(o,b=>{var $,S,te;clearTimeout(g);const E={headers:uo((b==null?void 0:b.headers)||{}),status:(($=b==null?void 0:b.headers)==null?void 0:$.status)&&parseInt((S=b==null?void 0:b.headers)==null?void 0:S.status)||200,ok:((te=b==null?void 0:b.headers)==null?void 0:te.status)==="200",json:async()=>{var ve;try{return(ve=b==null?void 0:b.body)!=null&&ve.length?JSON.parse(b.body):null}catch{throw Error("Not a JSON response")}},text:async()=>(b==null?void 0:b.body)||"",body:ho((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.")}};y(),Su().then(()=>d(E))}),v=t!=null&&t.fos?s.fosSocket:s.socket;if(!v)throw Error(`No web socket transport available: ${t}`);v==null||v.send(l)})};exports.BASE_URL="kos:";exports.kosFetch=Cu;if(process.env.KOS_MOCK_FETCH==="true"){const e=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${e}`}const Ru=f.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Lu{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=_.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)){Ru.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 Ci=()=>({isMock:!1,URL:exports.BASE_URL}),ku=f.createLogger({name:"kos-service-request"}),Pu="errUnknown";async function Wt(e,t,s,o,r){const n=o!=null&&o.path?Object.keys(o.path).reduce((g,y)=>String(g).replace(`{${y}}`,o==null?void 0:o.path[y]),String(e)):String(e),i=o!=null&&o.query?Object.keys(o.query).map(g=>`${g}=${o.query[g]}`).join("&"):"",c=`${Ci().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;ku.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||Pu}`,null]:[null,(await d.json()).data]}function Ko(){return{get:(e,t,s)=>Wt(e,"get",s,t),post:(e,t,s,o)=>Wt(e,"post",o,t,s),put:(e,t,s,o)=>Wt(e,"put",o,t,s),delete:(e,t,s)=>Wt(e,"delete",s,t)}}class Ri{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 xu=async(e,t)=>{const s=new Ri;t.forEach(r=>s.use(r));const o={data:e,result:{}};return await s.execute(o),o.result},Je=e=>({type:e,build:(t,s)=>_.getInstance().modelManager.createModelInstance(e,t,s).data,buildAsync:async(t,s)=>{const o=_.getInstance().modelManager.createModelInstance(e,t,s);return await o.model.whenInitialized(),o.data}}),Nu=e=>{_.getInstance().modelManager.registerModel(e)},Fu=(e,t)=>{_.getInstance().modelManager.registerCompanionModel(e,t)},Li=Symbol("KosObservableData");class ki{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,w.createAtom(s.toString())),(r=this.atomMap.get(s))==null||r.reportChanged(),!0},ownKeys:()=>Array.from(this.map.keys())});this.map=w.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)}}ki.prototype[Li]=!0;function Uu(e,t){return new Proxy(e,{construct:(s,o)=>{const r=new e(...o);return r.setValues(t),r.proxy}})}const pe=e=>{const t=Uu(ki,e);return new t(e)},Hr="/kos/ui/internal/heartbeat/",ju=({relationshipId:e,destinationAddress:t,onAbort:s,waitTime:o,beatTime:r})=>{const n=_.getInstance().transport,i=new AbortController;let c=performance.now();const l=n.subscribeTopic({topic:`${Hr}${e}`,callback:()=>{c=performance.now()}}),d=o??3e3,u=window.setInterval(()=>{let E=performance.now()-c;E=E/1e3,E>d/1e3&&i.abort()},d),g=r??2e3,y=window.setInterval(()=>{pi({msg:{},options:{topic:`${Hr}${e}`,destinationAddress:t}})},g),v=()=>{window.clearInterval(y),window.clearInterval(u),l()},b=()=>{v(),s&&s(),i.signal.removeEventListener("abort",b)};return i.signal.addEventListener("abort",b),{cleanUpHeartbeat:v}},Pi=(...e)=>t=>e.reduce((s,o)=>o(s),t),Bu={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function Ku(e,t){let s=1;const o={...Bu,...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 Gu=f.createLogger({name:"kos-service-request"}),q=e=>({isMock:!1,URL:exports.BASE_URL}),Hu=(e,t,s)=>async({id:o,tracker:r,urlOverride:n,ordered:i,studio:c,fos:l,bridge:d,destinationAddress:u})=>{const g={method:"DELETE"};e&&(g.destinationAddress=e),r&&(g.tracker=r),Qe(g,{ordered:i,studio:c,fos:l,bridge:d,destinationAddress:u});const y=await s(n||`${t}/${o}`,g);if(!y.ok)throw Error(`There was a problem deleting the model; returned status ${y.status}`);return await y.json()},Qe=(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),Vu=(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),Qe(u,{timeout:l,ordered:r,studio:n,fos:i,bridge:c,destinationAddress:d});const y=await s(o||t,u);if(!y.ok){let b;try{b=await y.json()}catch{}throw new ne(`There was a problem retrieving the model; returned status ${y.status}`,b)}return await y.json()},Yu=(e,t,s)=>async({urlOverride:o,ordered:r,studio:n,fos:i,bridge:c,tracker:l,timeout:d,destinationAddress:u})=>{const g={method:"GET"};e&&(g.destinationAddress=e),l&&(g.tracker=l),Qe(g,{timeout:d,ordered:r,studio:n,fos:i,bridge:c,destinationAddress:u});const y=o||t;Gu.debug(`resolvedUrl: ${y}`);const v=await s(y,g);if(!v.ok){let E;try{E=await v.json()}catch{}throw new ne(`There was a problem retrieving the model; returned status ${v.status}`,E)}return await v.json()},zu=(e,t,s)=>async({urlOverride:o,id:r,ordered:n,studio:i,fos:c,bridge:l,timeout:d,destinationAddress:u})=>{const g={method:"GET"};e&&(g.destinationAddress=e),Qe(g,{timeout:d,ordered:n,studio:i,fos:c,bridge:l,destinationAddress:u});const y=o||`${t}/${r}`,v=await s(y,g);if(!v.ok){let E;try{E=await v.json()}catch{}throw new ne(`There was a problem retrieving the model; returned status ${v.status}`,E)}return await v.json()};class ne extends Error{constructor(s,o){super(s);a(this,"payload");this.name="FetchException",this.payload=o}}const Vr=(e,t,s)=>async({model:o,urlOverride:r,ordered:n,tracker:i,studio:c,fos:l,bridge:d,timeout:u,destinationAddress:g})=>{const y={method:"POST",body:typeof o=="string"?o:JSON.stringify(o)};e&&(y.destinationAddress=e),i&&(y.tracker=i),Qe(y,{timeout:u,ordered:n,studio:c,fos:l,bridge:d,destinationAddress:g});const v=await s(r||t,y);if(!v.ok){let E;try{E=await v.json()}catch{}throw new ne(`There was a problem sending the POST data; returned status ${v.status}`,E)}return await v.json()},Yr=(e="POST",t,s,o)=>async({model:r,id:n,urlOverride:i,ordered:c,studio:l,fos:d,bridge:u,timeout:g,destinationAddress:y})=>{const v={method:e};r&&(v.body=JSON.stringify(r)),t&&(v.destinationAddress=t),Qe(v,{timeout:g,ordered:c,studio:l,fos:d,bridge:u,destinationAddress:y});const b=await o(i||`${s}/${n}`,v);if(!b.ok){let $;try{$=await b.json()}catch{}throw new ne(`There was a problem modifying the model; returned status ${b.status}`,$)}return await b.json()},V={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:Vu(e,s||t,l),getModelById:zu(e,o||t,l),getOne:Yu(e,o||t,l),addModel:Vr(e,n||t,l),deleteModel:Hu(e,r||t,l),modifyModel:Yr("POST",e,i||t,l),putModel:Yr("PUT",e,i||t,l),postModel:Vr(e,n||t,l)}}},qu=jt(),xi=()=>`kos-${qu}`,Wu=e=>!!e&&!e.includes("VM_SERVICE")&&e.startsWith(xi()),Go=async(e,t=6e4)=>new Promise((s,o)=>{const{unsubscribe:r}=U(e,i=>{I.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)}),Zu=async(e,t,s)=>{const o=Go(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)},Ju=async({topic:e,msg:t,requestId:s})=>{const o=s??jt(),r=Go(o);j(e,t,{sync:o});const n=await r;if(n.error)throw Error(n.error);return n},de=new Map;class Ni{constructor(t){a(this,"_context");a(this,"_parent");a(this,"_id");this._id=t,this._context=new w.ObservableMap({}),this._parent="",w.makeAutoObservable(this)}setParent(t){Y(()=>{this._parent=t})}get id(){return this._id}get context(){return this._context}get parentModel(){var t;if(this._parent)return(t=Ze(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=de.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 P={createContext:(e,t)=>{const s=de.get(e)??new Ni(e);if(t){if(!de.has(t))throw new Error(`Parent context ${t} does not exist`);s.setParent(t)}else e!=="root"&&s.setParent("root");return de.set(e,s),s},getContext:e=>de.get(e),deleteContext:e=>{de.delete(e)},setParentContext:(e,t)=>{var s;if(!de.has(t))throw new Error(`Parent context ${t} does not exist`);(s=de.get(e))==null||s.setParent(t)},rootContext:()=>de.get("root")};P.createContext("root");const Qu=e=>P.getContext(e.id);function Xu(e,t){return e.length!==t.length?!1:e.every(s=>t.includes(s))}class Ho{constructor({container:t,key:s}){a(this,"_container");a(this,"_map");a(this,"_key");a(this,"data");this._container=t,this._map=w.observable.map(new Map),this._key=s,this.data=pe(),this.generateIndex(),w.autorun(()=>{this._container.revision&&this.generateIndex()}),w.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(Xu(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(){w.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 eh(e,t,s=[]){const o=Object.getOwnPropertyDescriptors(e);return Object.keys(o).filter(i=>w.isComputedProp(e,i)).filter(i=>s.includes(i)).map(i=>w.reaction(()=>e[i],(c,l)=>{t({name:i,newValue:c,oldValue:l})}))}const ot=f.createLogger({name:"kos-container-model"});class fe{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=w.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=w.observable.map(r),this.idx=pe(),this._parentId=t==null?void 0:t.parentId,w.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],o=new Ho({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(){w.runInAction(()=>{this._revision=this._revision+1})}addAll(t){w.runInAction(()=>{t.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(t){w.runInAction(()=>{t.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(t,s){this._data.set(t.id||"",t),t.id&&this._parentId&&P.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,g])=>[g,u])),c=u=>{var y,v;n.includes(u.name)&&((y=this.index.get(i.get(u.name)))==null||y.refresh());const g=r.filter(([,b])=>typeof b=="function");for(const[b]of g)(v=this.index.get(b))==null||v.refresh()},l=eh(t,c,n.filter(u=>typeof u=="string")),d=w.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??[]:(ot.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):(ot.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return ot.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(t=>{const s=t.id;Oe(t).then(()=>{ot.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(o=>ot.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 ro=f.createLogger({name:"kos-data-container"});class Fi{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=w.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=w.observable.map(s),this.idx=pe(),w.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],o=new Ho({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){w.runInAction(()=>{t.forEach(s=>this.addModel(s))})}removeAll(t){w.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(){w.runInAction(()=>{this._revision=this._revision+1})}addModel(t,s){const o=w.isObservable(t)?t:w.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=w.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=w.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??[]:(ro.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):(ro.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return ro.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 th{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 ee(this.type)}}class sh{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 ee(this.type)}}class Ui{constructor(){a(this,"_token");w.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 ji{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 g=async()=>{if(u<l.middlewares.length){const y=l.middlewares[u++];await y(i,s,g)}};await g();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{unsubscribe:oh}=U("kos.intent",e=>{if(e){const t=e.body,s=t.type;Bi(s,t.options)}}),hs=new Map,rh=(e,t)=>{const s=hs.get(e)||[];s.push(t),hs.set(e,s)},Bi=(e,t)=>{hs.has(e)&&hs.get(e)[0].call(void 0,t)};var Ki=(e=>(e.GET="GET",e.PUT="PUT",e.POST="POST",e.DELETE="DELETE",e))(Ki||{});const po=w.when,Vo=w.computed,Y=w.runInAction,x=w.autorun,Gi=w.reaction,Yo=w.observable,zo="Not Assigned",nh="kos.trouble.added",ih="kos.trouble.removed";var oe=(e=>(e.TroubleRank="kos.trouble.rank.mapper",e.TroubleColor="kos.trouble.color.mapper",e.TroubleRole="kos.trouble.role.mapper",e))(oe||{}),It=(e=>(e.TIME_CHANGE="/kos/internal/time/time",e.DAY_CHANGE="/kos/internal/time/day",e.TIMEZONE_CHANGE="/kos/internal/time/timezone",e))(It||{});const Hi=f.createLogger({name:"config-bean-service",group:"Services"}),qo=exports.BASE_URL,Vi=e=>(e==null?void 0:e.decimals)!==void 0,{postModel:ah,getOne:ch}=V.build({destinationAddress:"",basePath:`${qo}/kos/config/`}),Yi=async(e,t,s="/api/kos/config")=>(Hi.debug(`sending modify request for ConfigBean: ${e}`),ah({model:t,urlOverride:`${qo}${s}/${e}`})),zi=async(e,t="/api/kos/config")=>(Hi.debug(`sending get request for ConfigBean: ${e}`),await ch({urlOverride:`${qo}${t}/details/${e}/15`})),Wo=e=>e.toLowerCase()==="true"||e.toLowerCase()==="false",Ns=e=>{try{const t=Number(e);return!isNaN(t)}catch{return!1}};function qi(e=[]){return e.reverse().reduce((t,s)=>{const{overrides:o}=s;return o&&(t={...t,...o}),t},{})}function Wi(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])?Wi(e[o],r,s):s[r]=e[o]}return s}const Zi=(e,t)=>{const s=e.details[0].bean||qi(e.details[0].scopes),o=Wi(s);w.runInAction(()=>{const r={...o};t.props.setValues(r)})},Ji=(e,t)=>{w.runInAction(()=>{e.changes.forEach(s=>{const o=s.attr;let r=s.currentValue,n=s.previousValue;typeof r=="string"&&Wo(r)&&(r=r.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof r=="string"&&Ns(r)&&(r=Number(r),n=Number(n)),t.props[o]=r,t.prevProps[o]=n})})},Qi=e=>Object.fromEntries(e.props.entries),lh=e=>t=>s=>e.build(t,s);var dh=Object.defineProperty,uh=Object.getOwnPropertyDescriptor,Xi=(e,t,s,o)=>{for(var r=o>1?void 0:o?uh(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&&dh(t,s,r),r};function hh(e,t){for(const s of e)if(new RegExp(`^${s}$`).test(t))return s}const Zo="config-bean-model",Zt=f.getLogger(Zo),gh=Se("path");let gs=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=Yi,getConfigBean:o=zi}=t;this._modifyConfigBean=s,this._getConfigBean=o,this.props=pe(),this.prevProps=pe()}get values(){return this.props.values}async ready(){Zt.debug(`readying config bean ${this.path}`),Zt.debug(`complete readying config bean ${this.path}`)}async load(){Zt.debug(`loading config bean ${this.path}`);const e=await this._getConfigBean(this.path,this.serviceBasePath);if(e!=null&&e.data){const t=e.data;Zi(t,this),Zt.debug(this.values);const s=e==null?void 0:e.data.details[0].schema;Y(()=>{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=hh(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=Qi(this);await this._modifyConfigBean(this.path,e,this.serviceBasePath)}handleConfigBeanUpdated(e){Ji(e,this)}};Xi([R({topic:`/kos/config/${gh}`,websocket:!0})],gs.prototype,"handleConfigBeanUpdated",1);gs=Xi([D(Zo)],gs);const Ot=new le({class:gs,type:Zo}),Fs=({path:e,lazy:t,serviceBasePath:s})=>(o,r)=>{o[L]=o[L]||{},o[L][r]={modelType:Ot.type,id:`${Ot.type}-${e}`,options:{path:e,serviceBasePath:s},lifecycle:F.INIT,lazy:t}},{URL:ea}=q(),{getOne:fh,getAll:mh}=V.build({basePath:`${ea}/api/kos/regions/info`}),ta=async()=>await fh({}),sa=async()=>await mh({urlOverride:`${ea}/api/kos/regions`}),ph=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:ta,getRegions:sa},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 oa={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 yh(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},{...oa});return{...e,...o}}function bh(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]:{...oa}}});return Object.keys(o).forEach(r=>{e[r]={...e[r],...o[r]}}),e}function wh(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 vh=Object.defineProperty,Mh=Object.getOwnPropertyDescriptor,Jo=(e,t,s,o)=>{for(var r=o>1?void 0:o?Mh(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};const is="region-info-model",rt=f.createLogger({name:"region-info-model"});let Dt=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||rt.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||rt.info("Could not find default unit for measure",t.measure)}return!n||!i?(rt.warn("Could not find unit to convert to or from. Return value as is"),String(e)):this.convertByUnit(e,n,i)}async init(){rt.debug("initializing region info")}async load(){rt.debug("loading region info");const e=await sa();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 ta();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(yh,{}),this.measureMap=t.data.unitSystems.reduce(bh,{}),this.defaultMeasureMap=t.data.unitSystems.reduce(wh,{}),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))}};Jo([Fs({path:"kos:service:region:settings"})],Dt.prototype,"regionSource",2);Jo([Fs({path:"kos:service:region"})],Dt.prototype,"region",2);Dt=Jo([D(is)],Dt);const z={registration:{[is]:{class:Dt,singleton:!0}},type:is,factory:H.Singleton.create(is)},zr=({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},ra=(e,t,s)=>{const{model:o}=Ze(z.type);if(!o)throw new Error("RegionInfo model not found");if(!us(o))throw new Error("RegionInfo model not ready");const r={system:o.defaultUnitSystem},n=zr({source:t}),i=zr({source:s||r,defaultMeasure:o.getUnitMeasure(n.unit||"")});return o.convert(e,n,i)};function qr({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 Wr({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 Le=(e,t)=>s=>!e||!t?s:Ns(s)?ra(Number(s),e,t):s,Eh=(e,t,s,o)=>{if((e==null?void 0:e.type)==="enum"||!(e!=null&&e.options))return[];if(e.options.type==="rangeCount")return qr(e.options).map(Le(s,o));if(e.options.type==="rangeInterval")return Wr(e.options).map(Le(s,o));if(e.options.type==="list"){const{list:r}=e.options;return r.map(Le(s,o))}else{if(e.options.type==="unitSystemRangeCount"&&t)return qr(e.options.unitSystems[t]).map(Le(s,o));if(e.options.type==="unitSystemRangeInterval"&&t)return Wr(e.options.unitSystems[t]).map(Le(s,o));if(e.options.type==="unitSystemList"&&t){const{list:r}=e.options.unitSystems[t];return r.map(Le(s,o))}}return[]},_h=(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 Ih=Object.defineProperty,Th=Object.getOwnPropertyDescriptor,Qo=(e,t,s,o)=>{for(var r=o>1?void 0:o?Th(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&&Ih(t,s,r),r};function $h(e){return(e==null?void 0:e.type)==="enum"}function Oh(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 Dh(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 as="config-bean-prop-model",ke=f.createLogger({name:"config-bean-prop-model"}),Sh=Se("path"),Ah=Se("serviceBasePath");let St=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 Vi(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?Oh(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=$h(o)?o.values:Eh(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){ke.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(){ke.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 Dh(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){ke.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 _h(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(g){ke.error(`error creating formatter ${u}. Returning the raw value`,g)}}else ke.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,g,y,v;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,E=(n=(r=this.converter)==null?void 0:r.to)==null?void 0:n.measure,$=(c=(i=this.converter)==null?void 0:i.from)==null?void 0:c.measure,S=b||E||$||t,te=((d=(l=this.converter)==null?void 0:l.to)==null?void 0:d.unit)||this.regionInfo.getDefaultUnitForMeasure(S,((g=(u=this.converter)==null?void 0:u.to)==null?void 0:g.system)??this.regionInfo.defaultUnitSystem),ve=((v=(y=this.converter)==null?void 0:y.to)==null?void 0:v.system)??this.regionInfo.getUnitSystem(te),tt=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:tt,...this.converter.from},to:{...this.converter.to,unit:te,system:ve},measure:S}}if(s&&t){const b=this.regionInfo.getDefaultUnitForMeasure(t,this.regionInfo.defaultUnitSystem),E=this.regionInfo.getUnitSystem(s),$=this.regionInfo.getUnitSystem(b);return{measure:t,to:{unit:E===$?s:b}}}}async updateProperty(e){ke.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)}};Qo([Bt({modelType:z.type})],St.prototype,"regionInfo",2);Qo([Fs({path:Sh,serviceBasePath:Ah})],St.prototype,"bean",2);St=Qo([D(as)],St);const Ae={registration:{[as]:{class:St,singleton:!1}},type:as,factory:H.Factory.create(as)};function Ch(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[L]=d[L]||{},d[L][u]={modelType:Ae.type,id:`${t}-${s}`,options:{path:t,attribute:s,serviceBasePath:c,converter:l,formatter:r,optionsExpander:i},lifecycle:F.INIT,lazy:n}}}class Rh{constructor(t,s){a(this,"futures");a(this,"defaultContext");a(this,"context");a(this,"disposers",new Map);a(this,"container");this.futures=Yo.map(new Map),this.context="",this.defaultContext=s||"",this.container=t,w.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=x(()=>{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)}}class Xo{constructor(t){a(this,"disposer");a(this,"_future");a(this,"container");a(this,"onFutureUpdate");this._future=void 0,this.container=t,w.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=x(()=>{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 na="future-model",Xe=Je(na),Us=f.createLogger({name:"future-service",group:"Services"}),{isMock:Lh,URL:Kt}=q();var Ke=(e=>(e.Success="SUCCESS",e.Fail="FAIL",e.Aborted="ABORT",e.Canceled="CANCEL",e))(Ke||{});const{getAll:kh,modifyModel:Ph,addModel:xh,deleteModel:Nh,postModel:Fh}=V.build({destinationAddress:"",basePath:`${Kt}/api/future`,mock:Lh}),Uh=async()=>await kh({}),ia=async(e,t="/api/kos/future")=>(Us.info(`sending delete request for Future: ${e}`),await Nh({id:e,urlOverride:`${Kt}${t}/${e}`})),aa=async(e,t="/api/kos/future")=>(Us.info("sending add request for Future"),await xh({model:e,urlOverride:`${Kt}${t}`})),jh=async(e,t,s="/api/kos/future")=>(Us.info(`sending modify request for Future: ${e}`),Ph({model:t,id:e,urlOverride:`${Kt}${s}/${e}`})),ca=async(e,t="/api/kos/future")=>(Us.info(`sending cancel request for Future: ${e}`),Fh({urlOverride:`${Kt}${t}/${e}/cancel`,ordered:!0,model:{}})),er=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}),tr=(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}`),w.runInAction(()=>{const s=er(e);Y(()=>{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]})})}))},la=e=>t=>s=>e.build(String(t),s),sr=e=>t=>Pi(er,la(e)(t.tracker||t.id))(t);var Bh=Object.defineProperty,Kh=Object.getOwnPropertyDescriptor,da=(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 no=f.getLogger(Xe.type);let fs=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=ca,po(()=>this.status===Ke.Success||this.status===Ke.Fail,()=>{no.info(`Future ${this.id} has completed with status ${this.status}`),Oe(this)})}async load(){no.debug(`loading Future ${this.id}`)}unload(){no.info(`unloading Future ${this.id}`)}async cancelFuture(){const e=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await po(()=>this.futureId!==zo),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}`),tr(e,this)}};da([R({topic:`kos.future/${ls}`})],fs.prototype,"handleFutureUpdated",1);fs=da([D(Xe.type)],fs);const ua=fs,ha=Ko();var Gh=Object.defineProperty,Hh=Object.getOwnPropertyDescriptor,ga=(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&&Gh(t,s,r),r};const fa="browser-router-model",Vh="kos.http.request",Yh="kos.http.response";let ms=class{constructor(e,t,s){a(this,"_id");a(this,"logger");a(this,"router");this._id=e,this.logger=s.logger,this.router=new ji}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};let l=200;const d={send:u=>{this.logger.debug(`sending response to ${o}`),this.logger.debug(u),yi({msg:u,options:{responseId:i,destinationAddress:s,type:Yh,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}`)}};ga([R({topic:Vh})],ms.prototype,"handleRequest",1);ms=ga([D(fa)],ms);const ma=new we({class:ms,type:fa}),pa="future-container-model",ye=Je(pa),ya=e=>sr(Xe)(e),zh=e=>{const t=ya(e);return ye.build(ye.type,{}).addFutureModel(t),t},qh=e=>ye.build(ye.type,{}).getFuture(String(e)),De={buildFutureModel:ya,initiateFuture:zh,getFuture:qh};var Wh=Object.defineProperty,Zh=Object.getOwnPropertyDescriptor,or=(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&&Wh(t,s,r),r};const Jt=f.getLogger(ye.type);let At=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=ia,addFuture:r=aa}=t;this.logger=s.logger,this._deleteFuture=o,this._addFuture=r,this.id=e,this._futures=new fe,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){Jt.error("error deleting a Future"),Jt.error(t)}}async createFuture(e){try{const t=await this._addFuture(e),s=t==null?void 0:t.data;if(s){const o=sr(Xe)(s);return this.addFutureModel(o),o}}catch(t){throw Jt.error("error creating a Future"),Jt.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}`),j(o,t.body,t.headers)}};or([ce],At.prototype,"_futures",2);or([R({topic:"kos.future"})],At.prototype,"handleFutureUpdated",1);At=or([D(ye.type)],At);const ba=At,{URL:Gt}=q(),{getOne:Jh,postModel:Qh,deleteModel:wa}=V.build({basePath:`${Gt}/api/keyVal`}),yo=f.createLogger({name:"key-value-service",group:"Services"}),va=async(e,t)=>{await wa({urlOverride:`${Gt}/api/keyVal/${e}/${t}`,id:t})},Ma=async(e,t,s)=>{const o=await Qh({urlOverride:`${Gt}/api/keyVal/${e}/${t}`,model:s.toString()});if((o==null?void 0:o.status)!==200)throw yo.error("Failed to update studio-state data",o),new Error(`Failed to update studio-state data for namespace ${e}`);return o.data},Ea=async(e="studio")=>{yo.debug("sending GET for studio-state");const t=await Jh({urlOverride:`${Gt}/api/keyVal/${e}`});if((t==null?void 0:t.status)!==200)throw yo.error("Failed to retrieve studio-state data",t),new Error(`Failed to retrieve studio-state data for namespace ${e}`);return t.data},Xh=async e=>{await wa({urlOverride:`${Gt}/api/keyVal/${e}}`,id:""})},eg=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:va,deleteKeyValueNamespace:Xh,getKeyValue:Ea,updateKeyValue:Ma},Symbol.toStringTag,{value:"Module"}));var tg=Object.defineProperty,sg=Object.getOwnPropertyDescriptor,rr=(e,t,s,o)=>{for(var r=o>1?void 0:o?sg(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 _a="key-value-model";let Ct=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=pe(),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 Ma(this.namespace,e,t),this.data[e]=t):(await va(this.namespace,e),this.data[e]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const e=await Ea(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)}};rr([R({topic:"/keyVal/set"})],Ct.prototype,"handleStateUpdate",1);rr([R({topic:"/keyVal/remove"})],Ct.prototype,"handleStateDelete",1);Ct=rr([D(_a)],Ct);const nr=new le({class:Ct,type:_a}),{URL:Ht}=q(),{postModel:ir,getOne:og}=V.build({basePath:`${Ht}/api/kos-time`});f.createLogger({name:"kos-time-service",group:"Services"});const Ia=async e=>{const t=await ir({model:e,urlOverride:`${Ht}/api/kos/time/time`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},Ta=async e=>{const t=await ir({model:e,urlOverride:`${Ht}/api/kos/time/date`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},$a=async e=>{const t=await ir({model:{},urlOverride:`${Ht}/api/kos/time/timezone?tz=${e}`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data},Oa=async()=>{const e=await og({urlOverride:`${Ht}/api/kos/time/timezone`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data.timeZone},rg=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:Oa,setDate:Ta,setTime:Ia,setTimezone:$a},Symbol.toStringTag,{value:"Module"}));var ng=Object.defineProperty,ig=Object.getOwnPropertyDescriptor,js=(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&&ng(t,s,r),r};const it="kos-time-model",ag="/kos/time/time",cg="/kos/time/day",lg="/kos/time/timezone";let Ge=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 Ia(e)}async updateSystemDate(e){await Ta(e)}async updateSystemTimezone(e){await $a(e)}handleTimeChange(){j(It.TIME_CHANGE,{})}handleDayChange(){j(It.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),j(It.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const e=await Oa();this.setTimezone(e)}setTimezone(e){this.timezone=e}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};js([R({topic:ag,websocket:!0})],Ge.prototype,"handleTimeChange",1);js([R({topic:cg,websocket:!0})],Ge.prototype,"handleDayChange",1);js([R({topic:lg,websocket:!0})],Ge.prototype,"handleTimeZoneChange",1);Ge=js([D(it)],Ge);const ps={registration:{[it]:{class:Ge,singleton:!0}},type:it,predicate:ee(it),factory:H.Singleton.create(it)};var dg=Object.defineProperty,ug=Object.getOwnPropertyDescriptor,Da=(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&&dg(t,s,r),r};const Sa="log-block-container-model";let ys=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new fe({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}`)}};Da([ce],ys.prototype,"_models",2);ys=Da([D(Sa)],ys);const Ce=Ko(),hg=f.createLogger({name:"log-stream-container-service",group:"Services"}),Aa=()=>{var o;const e=ae(),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},et=Aa(),gg="/api/kos/logs/node/{nodeId}/streams",Ca=async()=>(hg.debug("sending GET for log-stream-container"),await Ce.get(gg,{path:{nodeId:"primary"}},{destinationAddress:et})),Ra=async(e,t="primary")=>{await Ce.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:t,stream:e}},void 0,{destinationAddress:et})},La=async e=>{await Ce.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:e}},void 0,{destinationAddress:et})},fg=async()=>{await Ce.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:et})},ka=async e=>await Ce.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:e}},{destinationAddress:et}),Pa=async(e,t)=>await Ce.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:e,blockId:t}},{destinationAddress:et}),mg=Object.freeze(Object.defineProperty({__proto__:null,createOverride:fg,getKosConnectionId:Aa,getLogStreamBlock:Pa,getLogStreamBlocks:ka,getLogStreams:Ca,subscribeToLogStream:Ra,unsubscribeFromLogStream:La},Symbol.toStringTag,{value:"Module"}));var pg=Object.defineProperty,yg=Object.getOwnPropertyDescriptor,bg=(e,t,s,o)=>{for(var r=o>1?void 0:o?yg(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 xa="log-block-model";let bo=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 Pa(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}`)}};bo=bg([D(xa)],bo);const Rt=new le({class:bo,type:xa}),Bs=new le({class:ys,type:Sa});Bs.addRelatedModel(Rt);var wg=Object.defineProperty,vg=Object.getOwnPropertyDescriptor,Na=(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&&wg(t,s,r),r};const Fa="log-stream-model";let bs=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=Bs.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=Rt.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=Rt.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 Ra(this.name)}async unsubscribe(){await La(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 ka(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=Gi(()=>{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()}}};Na([ce],bs.prototype,"_blocks",2);bs=Na([D(Fa)],bs);const Tt=new le({class:bs,type:Fa});var Mg=Object.defineProperty,Eg=Object.getOwnPropertyDescriptor,Re=(e,t,s,o)=>{for(var r=o>1?void 0:o?Eg(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 Ua="log-stream-container-model",_g="/kos/logs/subscription/addBlock/*",Ig="/kos/logs/subscription/updateBlock/*",Tg="/kos/logs/subscription/removeBlock/*",$g="/kos/logs/subscription/lines/*",ja="/kos/logs/streams/add/*";let ue=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 fe({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: ${ja}`);const t=e.stream,s=Tt.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=Tt.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 Ca();if(e){this.logger.error(`Error loading log-streams: ${e}`);return}t&&t.forEach(s=>{const o=Tt.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(o)})}};Re([ce],ue.prototype,"_models",2);Re([R({topic:[ja],websocket:!0})],ue.prototype,"handleStreamAdded",1);Re([R({topic:[_g],websocket:!0})],ue.prototype,"handleAddBlock",1);Re([R({topic:[Tg],websocket:!0})],ue.prototype,"handleRemoveBlock",1);Re([R({topic:[Ig],websocket:!0})],ue.prototype,"handleUpdateBlock",1);Re([R({topic:[$g],websocket:!0})],ue.prototype,"handleLogLine",1);ue=Re([D(Ua)],ue);const Vt=new we({class:ue,type:Ua});Vt.addRelatedModel(Tt);Vt.addRelatedModel(Bs);Vt.addRelatedModel(Rt);const Og=e=>e.rank!==void 0,Dg=e=>e.visibleRole!==void 0,Sg=e=>e.color!==void 0,Ag=e=>{const t=e.info;return Og(t)?t.rank:0},Cg=e=>{const t=e.info;return Sg(t)?t.color:"orange"},Rg=e=>{const t=e.info;return Dg(t)?t.visibleRole:"TECHNICIAN"},{URL:ar}=q(),{getAll:Lg,postModel:Ba}=V.build({basePath:`${ar}/api/kos/troubles`}),Ka=async()=>await Lg({}),Ga=async(e,t)=>{try{const s=await Ba({model:{},urlOverride:`${ar}/api/kos/troubles/resolve/${e}`,tracker:t});return s!=null&&s.data&&De.initiateFuture(s.data),s.data}catch{const o={id:t||"",endState:Ke.Fail,tracker:t,reason:"Failed to resolve trouble"};return De.initiateFuture(o),o}},kg=async(e,t)=>{try{const s=await Ba({model:e,urlOverride:`${ar}/api/kos/troubles/resolve/`,tracker:t});return s!=null&&s.data&&De.initiateFuture(s.data),s.data}catch{const o={id:t||"",endState:Ke.Fail,tracker:t,reason:"Failed to resolve troubles"};return De.initiateFuture(o),o}},Pg=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:kg,getTroubles:Ka,resolveTrouble:Ga},Symbol.toStringTag,{value:"Module"})),ws="troubleDataMapper",Qt=new Map;Fo(ws,{register:(e,t)=>{var s;Qt.has(e)||Qt.set(e,[]),(s=Qt.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Qt.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 Yt="troubleMapper",Xt=new Map;Fo(Yt,{register:(e,t)=>{var s;Xt.has(e)||Xt.set(e,[]),(s=Xt.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Xt.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[Yt].register("nozzle",async e=>[e.data.nozzlePath]);C[Yt].register("path",async e=>[e.data.path]);const xg=async e=>{const t=new Set,s=e.ifaces,o=s==null?void 0:s.map(n=>C[Yt].execute(n,e));return(await Promise.allSettled(o)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>t.add(i))}),Array.from(t)},Ha=async e=>{const t=e.ifaces,s=t==null?void 0:t.map(i=>C[ws].execute(i,e)),o=C[ws].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 Ng{constructor(){a(this,"type","ResolvableTrouble");a(this,"title","Resolvable Trouble");a(this,"subtitle","Trouble")}}class Fg{constructor(){a(this,"type","BlockPumpTrouble");a(this,"title","Block Pump Trouble");a(this,"subtitle","Trouble")}}class Pe{static getHandler(t){switch(t){case"ResolvableTrouble":return new Ng;case"BlockPumpTrouble":return new Fg;default:return}}}var Ug=Object.defineProperty,jg=Object.getOwnPropertyDescriptor,Va=(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 at="trouble-model";function es(e){return typeof e.shouldDefer=="boolean"}let vs=class{constructor(e,{resolvable:t,tags:s,info:o,id:r,clientData:n,rank:i,ifaces:c,type:l,group:d,createTime:u,role:g,color:y,...v},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=g,this.color=y,this.tags=s,this.info=o,this.group=d,this.createTime=u,this.clientData=n,this.data={},Object.assign(this.data,v),this.futureHandler=new Xo(this)}getTitleWithContext(e){var s,o;const t=e?(o=(s=Pe.getHandler(this.type))==null?void 0:s.context)==null?void 0:o[e]:Pe.getHandler(this.type);return(t==null?void 0:t.title)||"Trouble"}getSubtitleWithContext(e){var s,o;const t=e?(o=(s=Pe.getHandler(this.type))==null?void 0:s.context)==null?void 0:o[e]:Pe.getHandler(this.type);return(t==null?void 0:t.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var e;return((e=Pe.getHandler(this.type))==null?void 0:e.title)||"Trouble"}get subtitle(){var e;return((e=Pe.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 Ha(this)}get deferredCompanion(){const e=mo(this.id,t=>es(t));if(e&&es(e.modelData))return e.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const e=mo(this.id,t=>es(t));return e&&es(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 Ga(this._troubleId,e)}};Va([vr()],vs.prototype,"resolve",1);vs=Va([D(at)],vs);const Lt={registration:{[at]:{class:vs,singleton:!1}},type:at,predicate:ee(at),factory:H.Factory.create(at)};var Bg=Object.defineProperty,Kg=Object.getOwnPropertyDescriptor,Ks=(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 Zr=f.createLogger({name:"trouble-container-model"});function Jr(e){return C.propertyMapper.hasMapper(oe.TroubleRank)?C.propertyMapper.executeMapper(oe.TroubleRank,e):Ag(e)}function Qr(e){return(C.propertyMapper.hasMapper(oe.TroubleColor)?C.propertyMapper.executeMapper(oe.TroubleColor,e):Cg(e)).toLowerCase()}function Xr(e){return(C.propertyMapper.hasMapper(oe.TroubleRole)?C.propertyMapper.executeMapper(oe.TroubleRole,e):Rg(e)).toLowerCase()}const Gg="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 He=class{constructor(e){a(this,"id");a(this,"troubles");this.id=e,this.troubles=new fe({indexMap:{[X.INDEX_TROUBLES_BY_IFACE]:xg,[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(){Zr.debug("loading trouble container");const e=await Ka();try{e==null||e.data.forEach(t=>{const s={...t,rank:Jr(t),color:Qr(t),role:Xr(t),id:String(t.id)},o=Lt.factory(`trouble-${t.id}`)(s);this.troubles.addModel(o)})}catch(t){throw Zr.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:Jr(e),color:Qr(e),role:Xr(e),id:String(e.id)};if(t.role==="NONE")return;const s=Lt.factory(`trouble-${e.id}`)(t);this.troubles.addModel(s)}};Ks([ce],He.prototype,"troubles",2);Ks([R({topic:"/kos/trouble/remove",websocket:!0,lifecycle:F.INIT})],He.prototype,"handleTroubleRemoved",1);Ks([R({topic:"/kos/trouble/add",websocket:!0})],He.prototype,"handleTroubleAdded",1);He=Ks([D(Gg)],He);const ts="trouble-container-model",Ve={registration:{[ts]:{class:He,singleton:!0}},type:ts,predicate:ee(ts),factory:H.Singleton.create(ts)},{URL:Ya}=q(),{getAll:Hg}=V.build({basePath:`${Ya}/api/kos/ota`}),en=f.createLogger({name:"ota-service",group:"Services"}),Vg=async()=>{en.debug("sending GET request to /api/kos/ota/artifacts");const e=await Hg({urlOverride:`${Ya}/api/kos/ota/artifacts`});return en.debug("getArtifacts - response:",e),e==null?void 0:e.data};var Yg=Object.defineProperty,zg=Object.getOwnPropertyDescriptor,Gs=(e,t,s,o)=>{for(var r=o>1?void 0:o?zg(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 za="ota-model",qg=e=>{let t=null;for(const s in e){const o=e[s],r=o.lastUpdateTime;(!t||t.lastUpdateTime<r)&&(t=o)}return t},io=e=>{const t=e.artifactInfo,s=qg(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 Ye=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"data",new Fi);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 Vg();e&&e.forEach(t=>{const s=io(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=io(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=io(t);s&&this.data.updateModel(s)})}catch(t){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,t)}}};Gs([Bt({modelType:Ve.type})],Ye.prototype,"troubleContainer",2);Gs([R({topic:"/kos/ota/artifacts/all",websocket:!0})],Ye.prototype,"handleAllArtifacts",1);Gs([R({topic:"/kos/ota/artifacts/changed",websocket:!0})],Ye.prototype,"handleChangedArtifacts",1);Ye=Gs([D(za)],Ye);const Ms=new we({class:Ye,type:za}),tn=f.createLogger({name:"software-info-service",group:"Services"}),qa=async()=>{tn.debug("sending GET for software-info");const[e,t]=await ha.get("/api/kos/manifest/info");if(!t)throw tn.error("Failed to fetch software-info",e),new ne("Failed to fetch software-info");return t},Wg=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:qa},Symbol.toStringTag,{value:"Module"}));var Zg=Object.defineProperty,Jg=Object.getOwnPropertyDescriptor,Qg=(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&&Zg(t,s,r),r};const ct="software-info-model";let wo=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 qa(),t=(e==null?void 0:e.nodes)||{};Y(()=>{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 ne&&this.logger.error("Failed to fetch software-info",e)}}};wo=Qg([D(ct)],wo);const Es={registration:{[ct]:{class:wo,singleton:!1}},type:ct,predicate:ee(ct),factory:H.Factory.create(ct)},{URL:Wa}=q(),{getOne:Xg}=V.build({basePath:`${Wa}/api/kos/state`}),ef=f.createLogger({name:"state-bean-service",group:"Services"}),Za=async({path:e})=>(ef.debug("sending GET for state-bean"),await Xg({urlOverride:`${Wa}/api/kos/state/${e}`})),tf=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:Za},Symbol.toStringTag,{value:"Module"}));var sf=Object.defineProperty,of=Object.getOwnPropertyDescriptor,Ja=(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&&sf(t,s,r),r};const lt="state-bean-model",rf=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=Yo.map(new Map),lo(t,this)}updateModel(e){lo(e,this)}handleConfigBeanUpdated(e){Object.entries(e).forEach(([t,s])=>{let o=s;typeof o=="string"&&Wo(o)&&(o=o.toLowerCase()=="true"),typeof o=="string"&&Ns(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 Za({path:this.path});e!=null&&e.data&&this.updateProps(e.data)}};Ja([R({topic:`/kos/state/${rf}`,websocket:!0})],_s.prototype,"handleConfigBeanUpdated",1);_s=Ja([D(lt)],_s);const kt={registration:{[lt]:{class:_s,singleton:!1}},type:lt,predicate:ee(lt),factory:H.Factory.create(lt)};var nf=Object.defineProperty,af=Object.getOwnPropertyDescriptor,Qa=(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="state-prop-model",sn=Se("path");let Is=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())??""}};Qa([Bt({modelType:kt.type,id:`state-bean-${sn}`,options:{path:sn}})],Is.prototype,"stateBean",2);Is=Qa([D(dt)],Is);const cr={registration:{[dt]:{class:Is,singleton:!1}},type:dt,predicate:ee(dt),factory:H.Factory.create(dt)},{URL:cf}=q(),{getAll:lf}=V.build({basePath:`${cf}/api/state-prop`}),df=f.createLogger({name:"state-prop-service",group:"Services"}),uf=async()=>(df.debug("sending GET for state-prop"),await lf({})),hf=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:uf},Symbol.toStringTag,{value:"Module"})),{URL:lr}=q(),{getOne:Xa}=V.build({basePath:`${lr}/api/translation`}),$t=f.createLogger({name:"translation-service",group:"Services"}),gf=()=>{const e=window.location.origin,t=ae();return(t==null?void 0:t.host)||e},ec=async(e,t)=>{$t.debug("sending GET for translation");const s=t??gf();try{const o=await fetch(`${s}${e}`);return o.status!==200?($t.warn(`Failed to fetch translations at ${e}: ${o.status}`),{}):await o.json()}catch(o){throw $t.error("Error fetching translations",o),o}},ff=async()=>{$t.debug("getting localization descriptor");const e=await Xa({urlOverride:`${lr}/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},tc=e=>async()=>{$t.debug("getting kos localization descriptor");const t=await Xa({urlOverride:`${lr}/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]},sc="langResolver";var mf=Object.defineProperty,pf=Object.getOwnPropertyDescriptor,yf=(e,t,s,o)=>{for(var r=o>1?void 0:o?pf(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&&mf(t,s,r),r};const ut="translation-model";function bf(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 oc(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=oc(e[o],r);return{...s,...n}}else return{...s,[r]:e[o]}},{})}function rc(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]=rc(e[o],t[o]):s[o]=t[o]);return s}const vo=(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)?vo(o,t):o},ss=(e,t,s)=>{const o=/{{(.*?)}}/g,n=vo(e,t).replace(o,(c,l)=>Object.prototype.hasOwnProperty.call(s||{},l.trim())?s==null?void 0:s[l.trim()]:c);return vo(n,t)},on=(e,t)=>{if(t.includes(":")){const[s,o]=t.split(":");return{namespace:s,key:o}}else return{namespace:e,key:t}};let Mo=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(sc),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=P.getContext(this.id);return this.bundleResolver(this.namespace,o,r)}try{const r=this.resolver(this.namespace,o);return ec(r,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(t);Y(()=>{const o=s.reduce((r,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${e[i]}`,n.value),n.value&&(r=rc(r,n.value))):this.logger.error(`failed to load translation ${this.id} for ${e[i]}`),r),{});this.data=oc(o)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(e){const{namespace:t,key:s}=on(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}=bf(t),{namespace:n,key:i}=on(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=>ss(d,this.data,r)):ss(this.data[c],this.data,r)}if(this.data[i]){const l=this.data[c];return Array.isArray(l)?l.map(d=>ss(d,this.data,r)):ss(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=w.reaction(()=>this.currentLocale,(e,t)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${t} to ${e}`),this.loadTranslations()})}};Mo=yf([Ps(),D(ut)],Mo);const Ts={registration:{[ut]:{class:Mo,singleton:!1}},type:ut,predicate:ee(ut),factory:H.Factory.create(ut)};var wf=Object.defineProperty,vf=Object.getOwnPropertyDescriptor,nc=(e,t,s,o)=>{for(var r=o>1?void 0:o?vf(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&&wf(t,s,r),r};const ht="translation-container-model",Mf=(e,t="/")=>e.join(t).replace(new RegExp(t+"{1,}","g"),t);function Ef(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 Mf([o,r])}let $s=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||Ef.bind(this),s.kosContext.set(sc,this.resolver),this.logger=s.logger,this._models=new fe({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 _i(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=Ts.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)||Y(()=>{this.namespaces.push(e)}),n}else{this.logger.warn(`namespace ${e} not found in descriptor`);const o=Ts.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}`)}};nc([ce],$s.prototype,"_models",2);$s=nc([D(ht)],$s);const he={registration:{[ht]:{class:$s,singleton:!0}},type:ht,predicate:ee(ht),factory:H.Singleton.create(ht)},_f={set(e,t){const s=P.getContext(he.type);s&&s.set(e,t)},get(e){const t=P.getContext(he.type);return t==null?void 0:t.get(e)}},ic={async init(e){const t=he.factory(e);return await J(t),{translations:t}}},If=(e,t)=>{const s=t.type;return e[s]||(e[s]=[]),e[s].push(t),e},ac="kos-ws-event",dr=Je(ac);var Tf=Object.defineProperty,$f=Object.getOwnPropertyDescriptor,ur=(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 Of=({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=w.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:Of({headers:r,body:o}),direction:s?"send":"receive",mocked:!!r.mocked};this.events.set(c,l),f.debug(`logged ${this.events.size} events`)}}};ur([R({topic:[Ut.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);ur([R({topic:[Ut.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=ur([D(dr.type)],exports.WsEventModel);const{URL:hr}=q(),{getOne:cc}=V.build({basePath:`${hr}/api/device`}),Os=f.createLogger({name:"device-service",group:"Services"}),lc=async()=>{Os.debug("sending GET for device serial number");try{const e=await cc({urlOverride:`${hr}/api/kos/device/serialNumber`});return[void 0,e==null?void 0:e.data.serialNumber]}catch(e){if(e instanceof ne)return Os.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},dc=async()=>{Os.debug("sending GET for device details");try{const e=await cc({urlOverride:`${hr}/api/kos/device`});return e?[void 0,e.data]:["unknownError",void 0]}catch(e){if(e instanceof ne)return Os.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Df=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:dc,getSerialNumber:lc},Symbol.toStringTag,{value:"Module"}));var Sf=Object.defineProperty,Af=Object.getOwnPropertyDescriptor,uc=(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&&Sf(t,s,r),r};const hc="device-model",Cf="/kos/criticalData/changed",Rf="/kos/criticalData/available";let Ds=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 lc();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()}};uc([R({topic:[Cf,Rf],websocket:!0})],Ds.prototype,"handleCriticalDataChanged",1);Ds=uc([D(hc)],Ds);const Ss=new we({class:Ds,type:hc});var Lf=Object.defineProperty,kf=Object.getOwnPropertyDescriptor,Pf=(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&&Lf(t,s,r),r};const gc="network-interface-model";let Eo=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}`)}};Eo=Pf([D(gc)],Eo);const gr=new le({class:Eo,type:gc}),{URL:xf}=q(),{getAll:Nf}=V.build({basePath:`${xf}/api/kos/network/interfaces`}),rn=f.createLogger({name:"network-interface-service",group:"Services"}),fc=async()=>{rn.debug("sending GET for copy-logs");try{const e=await Nf({});return[void 0,e==null?void 0:e.data]}catch(e){if(e instanceof ne)return rn.error(`Error fetching log file size: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Ff=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:fc},Symbol.toStringTag,{value:"Module"}));var Uf=Object.defineProperty,jf=Object.getOwnPropertyDescriptor,mc=(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 pc="network-interface-container-model";let As=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new fe({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 fc();if(e){this.logger.error(`Error loading network interfaces: ${e}`);return}t&&t.forEach(s=>{const o=gr.instance(s.name).forceUpdate.options(s).build();this.addModel(o)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};mc([ce],As.prototype,"_models",2);As=mc([D(pc)],As);const Pt=new we({class:As,type:pc});Pt.addRelatedModel(gr);const{URL:Bf}=q(),{getAll:Kf}=V.build({basePath:`${Bf}/api/kos/storage/devices`}),nn=f.createLogger({name:"storage-device-service",group:"Services"}),yc=async()=>{nn.debug("sending GET for storage-device");const e=await Kf({});return!(e!=null&&e.data)||e.status!==200?(nn.error("Failed to retrieve storage-device data",e),[]):e.data},Gf=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:yc},Symbol.toStringTag,{value:"Module"}));var Hf=Object.defineProperty,Vf=Object.getOwnPropertyDescriptor,Yf=(e,t,s,o)=>{for(var r=o>1?void 0:o?Vf(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 bc="storage-device-model";let _o=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}`)}};_o=Yf([Ps(),D(bc)],_o);const Cs=new le({class:_o,type:bc});var zf=Object.defineProperty,qf=Object.getOwnPropertyDescriptor,fr=(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 wc="storage-device-container-model",Wf="/kos/storage";let xt=class{constructor(e,t,s){a(this,"id");a(this,"logger");a(this,"_models");this.id=e,this.logger=s.logger,this._models=new fe({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=Cs.instance(s.id).options(r).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await yc()).forEach(t=>{const s={...t,kosParentId:this.id},o=Cs.instance(t.id).options(s).build();this.addModel(o)})}};fr([ce],xt.prototype,"_models",2);fr([R({topic:Wf,websocket:!0})],xt.prototype,"handleStorageAvailability",1);xt=fr([D(wc)],xt);const ze=new we({class:xt,type:wc});ze.addRelatedModel(Cs);const{URL:mr}=q(),{getAll:Zf,postModel:Jf}=V.build({basePath:`${mr}/api/kos/update/available`}),an=f.createLogger({name:"usb-update-service",group:"Services"}),vc=async()=>{an.debug("sending GET for usb-update");const e=await Zf({urlOverride:`${mr}/api/kos/update/available`});return!(e!=null&&e.data)||(e==null?void 0:e.status)!==200?(an.error("Failed to retrieve usb-update data",e),[]):e.data},Mc=async(e,t,s)=>{const o=await Jf({model:{manifestId:e,deviceId:t},tracker:s,urlOverride:`${mr}/api/kos/update/install`});if(!(o!=null&&o.data))throw new Error("No response from server");return o.data},Qf=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:vc,installUpdate:Mc},Symbol.toStringTag,{value:"Module"}));var Xf=Object.defineProperty,em=Object.getOwnPropertyDescriptor,Ec=(e,t,s,o)=>{for(var r=o>1?void 0:o?em(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="usb-update-model";let Rs=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 Xo(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}`),Mc(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}`)}};Ec([vr()],Rs.prototype,"install",1);Rs=Ec([D(_c)],Rs);const pr=new le({class:Rs,type:_c});var tm=Object.defineProperty,sm=Object.getOwnPropertyDescriptor,Hs=(e,t,s,o)=>{for(var r=o>1?void 0:o?sm(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&&tm(t,s,r),r};const Ic="usb-update-container-model";let qe=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 fe({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 vc();Y(()=>{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=pr.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}`)}};Hs([Bt({modelType:ze.type})],qe.prototype,"storageService",2);Hs([ce],qe.prototype,"_models",2);Hs([Wn({dependencies:e=>[e.isUsbInserted]})],qe.prototype,"usbInsertedEffect",1);qe=Hs([D(Ic)],qe);const Nt=new we({class:qe,type:Ic});Nt.addRelatedModel(pr);const om=()=>({...{[Xe.type]:{class:ua},[ye.type]:{class:ba,singleton:!0},...z.registration,...Ae.registration,...Ve.registration,...Ts.registration,...he.registration,[dr.type]:{class:exports.WsEventModel,singleton:!0},...kt.registration,...cr.registration,...ps.registration}}),yr=om(),rm={models:yr,preloadModels:[]},nm=!0,Tc=e=>()=>{const t=yr;return Oi(Io)(Lt).model(Ve).model(ze).model(Nt).model(Ss).model(Ms).model(Ot).model(Es).model(nr).model(Pt).model(ma,nm).model(Vt),Object.keys(t).forEach(s=>{const o=t[s];$i(Io)(s,o)}),{preload:T.model.preloadModel(e),model:T.model.register(e),companion:T.companion.register(e),legacy:T.model.registerLegacyModel(e)}},re={};re.core={models:Tc(re)};re.preload=T.model.preloadModel(re);re.model=T.model.register(re);re.companion=T.companion.register(re);re.legacy=T.model.registerLegacyModel(re);const Io=re;class im{registerTroubleRankMapper(t){return C.propertyMapper.registerPropertyMapper(oe.TroubleRank,t),this}registerTroubleRoleMapper(t){return C.propertyMapper.registerPropertyMapper(oe.TroubleRole,t),this}registerTroubleColorMapper(t){return C.propertyMapper.registerPropertyMapper(oe.TroubleColor,t),this}}const am=async(e,t)=>{const s=nr.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)}}},$c="kos:service:region",Oc="regionId",cm=`${$c}-${Oc}`,Dc=async e=>{const t=Ae.factory(cm)({path:$c,attribute:Oc});await J(t),t.updateProperty(e)},br="/kos-timer-event",wr="defaultTimerEnd",gt=f.createLogger({name:"timer-manager"}),lm=e=>e.updateProperty!==void 0;class Sc{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,lm(s)&&x(()=>{f.info(`Updating config value timer ${t} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:wr}),o&&o.forEach(n=>{this.addTimeoutAction(n)})}start(){if(this.state==="active"){gt.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&&(gt.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;gt.debug(`Executing timer action ${s.name} at ${t}`),(o=s.action)==null||o.call(s,s.name,t),this.notifyTimeoutAction(s),s.singleUse&&(gt.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))})}notifyTimeoutAction(t){j(br,{name:this.name,action:t.name,remainingTime:this.remainingTime})}}const ft=new Map,xe=(e,t)=>{const s=ft.get(e);if(!s){gt.error(`Timer ${e} not found`);return}t(s)},Ac={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(ft.has(e))return ft.get(e);const o=new Sc(e,t,s);return ft.set(e,o),o},getTimer(e){return ft.get(e)},clearTimer(e){xe(e,t=>t.pause())},restartTimer(e){xe(e,t=>t.restart())},resetTimer(e){xe(e,t=>t.reset())},addTimeoutAction(e,t){xe(e,s=>s.addTimeoutAction(t))},removeTimeoutAction(e,t){xe(e,s=>s.removeTimeoutAction(t))},startTimer(e){xe(e,t=>t.start())}},Cc="kos:service:region:settings",Rc="timeZone",dm=`${Cc}-${Rc}`,To=async e=>{const t=Ae.factory(dm)({path:Cc,attribute:Rc});await J(t),t.updateProperty(e)},um=e=>!e||!e.data;function vr(e={}){const{alias:t,namespace:s}=e;return(o,r,n)=>{o[yt]=o[yt]||{};const i=n.value,c=async function(...l){const d=jt();f.debug(`Calling future service ${r} with tracker ${d}`);const u=De.initiateFuture({tracker:d,id:zo});s&&(u.namespace=s),f.debug(`waiting for future ${u.id} to be ready`),await J(u),f.debug(`future ${u.id} is ready`),Y(()=>{f.debug(`Adding future ${u.id} to futureHandler`),this.futureHandler.addFuture(u,t)});try{const g=await i.apply(this,[...l,d]);f.debug(`received future response for ${d}`,g);const y=um(g)?g:g==null?void 0:g.data;return y?(y.progress=1,f.debug("mapping future response to future model"),u.endState?f.debug(`future ${u.id} has already completed. Not updating the model`):tr(y,u)):this.futureHandler.removeFuture(t),y}catch(g){throw f.error(g),g}};o[yt][r]={handler:c}}}const hm=({path:e})=>(t,s)=>{t[L]=t[L]||{},t[L][s]={modelType:kt.type,id:`${kt.type}-${e}`,options:{path:e},lifecycle:F.INIT}};function gm(e){const{path:t,attribute:s}=e;return(o,r)=>{o[L]=o[L]||{},o[L][r]={modelType:cr.type,id:`${t}-${s}`,options:{path:t,attribute:s},lifecycle:F.INIT}}}const Ue=f.createLogger({name:"services",group:"Services"}),fm=async(e,t)=>Lc(e,t,`${exports.BASE_URL}/api/server/login`),Lc=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()},mm=async e=>kc(e,`${exports.BASE_URL}/api/server/startPasswordReset`,""),kc=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()},pm=async(e,t)=>Pc(e,t,`${exports.BASE_URL}/api/server/resetPassword`),Pc=async(e,t,s=`${exports.BASE_URL}/api/resetPassword`)=>{Ue.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(Ue.debug(`password reset returned status ${o.status}`),!o.ok){Ue.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()},ym=async(e,t,s)=>xc(e,t,s,`${exports.BASE_URL}/api/server/acceptInvite`),xc=async(e,t,s,o=`${exports.BASE_URL}/api/server/acceptInvite`)=>{Ue.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(Ue.debug(`invitation accept returned status ${r.status}`),!r.ok){Ue.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()},bm=Ie.keyframes`
77
78
  0% {
78
79
  left: -90px;
79
80
  color: #eee;
@@ -85,13 +86,13 @@ ${l}topics:${t}
85
86
  left: 90px;
86
87
  color: #eee;
87
88
  }
88
- `,qf=Ie.css`
89
+ `,wm=Ie.css`
89
90
  font-size: 100px;
90
91
  margin-top: -80px;
91
92
  position: relative;
92
- animation: ${zf} ease-in-out infinite alternate;
93
+ animation: ${bm} ease-in-out infinite alternate;
93
94
  animation-duration: 1.2s;
94
- `,Wf=({children:e})=>Rl.createPortal(e,document.body);function Rc({message:e="Wait a moment while we load your app.",theme:t="light"}){return _.jsx(Wf,{children:_.jsxs(Zf,{theme:t,children:[e,_.jsx("div",{css:qf,children:"."})]})})}const Zf=Cl.div`
95
+ `,vm=({children:e})=>Nl.createPortal(e,document.body);function Nc({message:e="Wait a moment while we load your app.",theme:t="light"}){return M.jsx(vm,{children:M.jsxs(Mm,{theme:t,children:[e,M.jsx("div",{css:wm,children:"."})]})})}const Mm=xl.div`
95
96
  padding-inline: 20px;
96
97
  width: 100%;
97
98
  height: 100vh;
@@ -105,7 +106,7 @@ ${l}topics:${t}
105
106
  left: 0;
106
107
  color: ${({theme:e})=>e==="light"?"black":"white"};
107
108
  z-index: 10000;
108
- `;class Lc 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||_.jsxs("div",{children:[_.jsx("h2",{children:"Something went wrong."}),_.jsxs("details",{style:{whiteSpace:"pre-wrap"},children:[this.state.error&&this.state.error.toString(),_.jsx("br",{}),this.state.errorInfo.componentStack]})]}):this.props.children}}const Qf={normal:"#B5F7F6",warn:"#F3D78A",error:"#FC8486"},Xf=({value:e=0,title:t,status:s="normal",subtitle:o})=>{const r=Ie.css`
109
+ `;class Fc extends h.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 Em={normal:"#B5F7F6",warn:"#F3D78A",error:"#FC8486"},_m=({value:e=0,title:t,status:s="normal",subtitle:o})=>{const r=Ie.css`
109
110
  display: flex;
110
111
  flex-direction: column;
111
112
  `,n=Ie.css`
@@ -125,7 +126,7 @@ ${l}topics:${t}
125
126
  `,c=Ie.css`
126
127
  width: ${e}%;
127
128
  height: 35px;
128
- background-color: ${Qf[s]};
129
+ background-color: ${Em[s]};
129
130
  text-align: center;
130
131
  line-height: 32px;
131
132
  color: black;
@@ -143,5 +144,5 @@ ${l}topics:${t}
143
144
  transform: translateX(100%) scaleX(0.5);
144
145
  }
145
146
  }
146
- `;return _.jsxs("div",{css:r,children:[_.jsxs("div",{css:n,children:[_.jsx("div",{css:i,children:t}),_.jsx("div",{css:[c,e<0?l:""]})]}),_.jsx("div",{children:o})]})},Jf={setModel:()=>!1},Hs=g.createContext(Jf),em=()=>{const e=g.useContext(Hs);if(e==null)throw new Error("useModels must be used within a KosModelProvider");return e.model},Pc=({children:e})=>{const[t,s]=g.useState(),o=g.useCallback(r=>(s(r),!0),[s]);return _.jsx(Hs.Provider,{value:{model:t,setModel:o},children:e})},kc=f.createLogger({name:"kos-model-hierarchy-context"}),tm={models:[],addModel:()=>{kc.debug("Default implementation being used. Do Nothing.")}},Vs=g.createContext(tm),sm=({children:e})=>{const[t,s]=g.useState([]),o=g.useCallback(r=>{t.includes(r)||(kc.debug("adding to hierarchy context",r.id),s(n=>[...n,r]))},[t]);return _.jsx(Vs.Provider,{value:{models:t,addModel:o},children:e})},om=()=>!0,xc=e=>{const t=g.useContext(Vs);if(!t)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(e==null?void 0:e.filter)||om;return g.useMemo(()=>t.models.filter(s),[t.models,s])},rm=e=>xc({filter:s=>{const o=Ze(s.id);return(o==null?void 0:o.type)===e}})[0],nm=f.createLogger({name:"kos-model-loader"}),im=()=>_.jsx("div",{}),Nc=({fallback:e,children:t,...s})=>_.jsx(Pc,{children:_.jsx(Lc,{fallback:e,children:_.jsx(g.Suspense,{children:_.jsx(Fc,{...s,children:t})})})}),Fc=e=>{const[t,s]=g.useState(),[o,r]=g.useState(!1),{setModel:n}=g.useContext(Hs),i=g.useContext(Vs);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 nm.error(e.error),new Error(e.error);const c=e.loading||_.jsx(im,{});return _.jsx(_.Fragment,{children:t&&o?e.children:c})},as={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},Uc=g.createContext(as),am=({translations:e=as,children:t})=>{const s={header:{...as.header,...e.header},createModal:{...as.createModal,...e.createModal}};return _.jsx(Uc.Provider,{value:s,children:t})};function cm(e,t){const s=E.create(e,!1,t),o=s.whenReady().then(()=>s);return Co(o)}const jc=g.createContext(void 0),lm=(e={models:{},preloadModels:[]},t)=>{const s=cm(e,t),o=({children:r})=>{const n=s.read(),[i,c]=g.useState(n.isOnline);return g.useEffect(()=>{const l=x(()=>{c(n.isOnline)});return()=>{l()}},[n]),_.jsx(jc.Provider,{value:{kosCore:n,online:i},children:r})};return{KosCoreContextProvider:an.observer(o)}},Bc=()=>{const e=g.useContext(jc);if(e===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return e},dm=8,um=(e=0)=>new Promise(t=>{setTimeout(()=>{t(!0)},2**e*10)}),Te=new Map;function hm(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 gm(e,t){return hm(e,t)}async function fm(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>dm)throw Error(`KOS Model ${s} has not been found`);await um(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 j=e=>{const{modelId:t,modelType:s,activate:o,destroyOnUnmount:r}=e,n=Bc(),[i,c]=g.useState(!1),[l,d]=g.useState(),{kosModel:u,model:h}=gm(t||s||"",()=>fm(n.kosCore,e));return g.useEffect(()=>{async function y(){try{return await n.kosCore.whenReady(),o&&await(u==null?void 0:u.transition(D.GO_ACTIVE,p.ACTIVE)),c(!0),u}catch(b){d(b.message)}}let v;return n.kosCore&&t&&y().then(b=>{v=x(()=>{const M=(b==null?void 0:b.status)===p.READY;c(M)})}).catch(b=>{console.error(b)}),()=>{if(o){if(h!=null&&h.id){const b=n.kosCore.modelManager.getModelById(h.id);b==null||b.transition(D.GO_INACTIVE,p.INACTIVE).then(()=>{if(r){const M=h.id;$e(h).then(()=>{Te.delete(M),v==null||v()})}})}}else r&&h&&$e(h).then(()=>{Te.delete(t),v==null||v()})}},[o,r,n.kosCore,u,h,t]),{model:h,ready:i,error:l,status:{model:h,ready:i,error:l},KosModelLoader:Nc}},br=()=>{const e=ms.type;return j({modelId:e,modelType:ms.type,options:{}})},wr=g.createContext(void 0),mm=({children:e})=>{const{model:t,ready:s}=br(),o=g.useMemo(()=>s&&t?{model:t}:{},[s,t]);return _.jsx(wr.Provider,{value:o,children:e})},pm=()=>{const e=g.useContext(wr);if(!e)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return e},vr=()=>{const e=Ms.type;return j({modelId:e,modelType:Ms.type,options:{}})};function ym(e){return()=>t=>{const{model:s,status:o,KosModelLoader:r}=vr();return _.jsx(r,{...o,children:_.jsx(e,{...t,softwareInfo:s})})}}const Mr=g.createContext(void 0),bm=({children:e})=>{const{model:t,ready:s}=vr(),o=g.useMemo(()=>s&&t?{model:t}:{},[s,t]);return _.jsx(Mr.Provider,{value:o,children:e})},wm=()=>{const e=g.useContext(Mr);if(!e)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return e},Kc=new Pi,Gc=g.createContext(Kc);function vm({children:e}){return _.jsx(Gc.Provider,{value:Kc,children:e})}const _r=g.createContext(void 0),Mm=()=>{const e=window.location.origin,t=ae();return(t==null?void 0:t.host)||e},_m=({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(),y=r||Mm(),v=g.useMemo(()=>t??"app/system",[t]);g.useEffect(()=>{async function O(){const te=(Array.isArray(v)?v:[v]).map(Q=>(n||Za(Q))()),Ys=(await Promise.allSettled(te)).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 zs=Me.path;return Object.keys(Me.namespaces).forEach(qs=>{const Ws=Me.namespaces[qs];Ws.basePath=zs}),{...Q,namespaces:{...Q.namespaces,...Me.namespaces}}},{});d(Ys)}O()},[v,n]),g.useEffect(()=>{async function O(){if(l){const A=y,{translations:te}=await tc.init({lang:s,descriptor:l,defaultNamespace:"common",resolver:o,rootUrl:A});h(te),c(!0)}}O()},[s,l,o,y]);const b=g.useMemo(()=>i?{setLocale:O=>{u&&(u.currentLocale=O)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,u]),M=i?e:null;return _.jsx(_r.Provider,{value:b,children:M})},Em=()=>{const e=g.useContext(_r);if(!e)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return e},Hc=()=>{const e=Ds.type;return j({modelId:e,modelType:Ds.type,options:{}})};function Im(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Hc();return _.jsx(r,{...o,children:_.jsx(e,{...t,device:s})})}}function Tm(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 Co(o)}function $m(e){return t=>{const{model:s,status:o,KosModelLoader:r}=br();return _.jsx(r,{...o,children:_.jsx(e,{...t,kosTime:s})})}}const Vc=()=>{const e=Lt.type;return j({modelId:e,modelType:Lt.type,options:{}})};function Om(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Vc();return _.jsx(r,{...o,children:_.jsx(e,{...t,networkInterfaceContainer:s})})}}const Yc=()=>{const e=vs.type;return j({modelId:e,modelType:vs.type,options:{}})};function Dm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Yc();return _.jsx(r,{...o,children:_.jsx(e,{...t,oTA:s})})}}function Sm(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 Am(e){const t=g.useRef(null),s=e.onAlert;return Sm(t,s),_.jsx("div",{ref:t,style:{width:"100%"},children:e.children})}const Cm=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 Z(h),n(!0))}catch(y){c(y.message)}}u(t)},[t]),g.useEffect(()=>{const u=x(()=>{t&&r&&o(t.value)});return()=>{u()}},[r,t]),[s,{ready:r,error:i}]},zc=()=>{const[e,t]=g.useState(!1),[s,o]=g.useState([]),r=ze.type,n=j({modelId:r,modelType:ze.type,options:{}});return g.useEffect(()=>{const i=x(()=>{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 Rm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=zc();return _.jsx(r,{...o,children:_.jsx(e,{...t,storageDeviceContainer:s})})}}const Lm=({timerName:e,onTimerExpired:t,timerEventActions:s,autoStart:o})=>{const r=Tc.getTimer(e);return g.useEffect(()=>{const n=F(mr,i=>{const{name:c,action:l,remainingTime:d}=i==null?void 0:i.body;c===e&&r&&(l===pr?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)}},Pm=e=>{const t=/[\\^$.*+?()[\]{}|]/g;return RegExp(t.source).test(e)?e.replace(t,"\\$&"):e},km=e=>e instanceof RegExp,xm=e=>typeof e=="string",Nm=(e,t,s)=>{if(e===""||t==="")return e;let o=t;km(o)||(o=new RegExp("("+Pm(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},qc=(e,t,s)=>{let o=e;return Array.isArray(o)||(o=[o]),o.flatMap(r=>xm(r)?Nm(r,t,s):r)};function Fm(e,t){let s=e;return Object.entries(t).forEach(([o,r])=>{const n=new RegExp(`<${o}>(.*?)</${o}>|<${o}/>`,"g");s=qc(s,n,(i,c)=>r.type==="br"?_.jsx("br",{}):g.cloneElement(r,{key:`${o}-${c}`},i))}),s}const Um=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=Fm(c,r||{});return _.jsx("span",{className:e.className,children:l})},Ne=new Map;function jm(e,t){if(Ne.has(e)){const s=Ne.get(e);if(s.status==="finished")return s.result;throw s.promise}else{const s=t().then(r=>{Ne.set(e,{status:"finished",result:r})},r=>{throw Ne.set(e,{status:"error",error:r}),r}),o={status:"pending",promise:s};throw Ne.set(e,o),s}}function To(e,t){return jm(e,t)}const Bm=async()=>{const e=await wi(he.type);return await Z(e.model),e.model},Km=async(e,t,s)=>{const o=e.resolveNamespace(t);await Z(o);for(const r of s){const n=e.resolveNamespace(r);await Z(n),Ne.set(r,{status:"finished",result:n})}return o},Gm=(e,t)=>{const s=[e].flat(),[o,...r]=s,n=To(he.type,Bm),i=s.join("__"),c=To(i,()=>Km(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 y=t!=null&&t.keyPrefix?`${t.keyPrefix}.${u}`:u;return c?c.resolveKey(y,h):(f.debug(`Translation model ${e} not ready for key: ${y}`),y)},[t==null?void 0:t.keyPrefix,e,c]),i18n:l}},Wc=()=>{const e=he.type;return j({modelId:e,modelType:he.type,options:{}})};function Hm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Wc();return _.jsx(r,{...o,children:_.jsx(e,{...t,translationContainer:s})})}}const Vm=e=>j({modelId:e,modelType:Ct.type}),Er=()=>j({modelId:Ve.type,modelType:Ve.type,options:{}}),Ym=({troubleType:e,condition:t})=>{const{model:s}=Er(),[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(()=>x(()=>{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 zm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Er();return _.jsx(r,{...o,children:_.jsx(e,{...t,troubleContainer:s})})}}const Zc=()=>{const e=kt.type,t=j({modelId:e,modelType:kt.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=x(()=>{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 qm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Zc();return _.jsx(r,{...o,children:_.jsx(e,{...t,usbUpdateContainer:s})})}}const Wm=({path:e,propKey:t})=>{const{status:s}=j({modelType:Tt.type,modelId:e,options:{path:e}}),[o,r]=g.useState(!1),[n,i]=g.useState(),[c,l]=g.useState(""),[d,u]=g.useState(),h=y=>{n&&t&&n.updateProperty(t,y)};return g.useEffect(()=>{var y;s.model&&i(s.model),s.model&&t&&((y=s.model)!=null&&y.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&&w.autorun(()=>{const y=n==null?void 0:n.props[t];l(y||"")})},[n,t]),{config:n,ready:o,value:c,error:d,updateValue:h}},Zm=(e,t)=>{switch(t.type){case"UPDATE":return t.payload;default:return e}},Qc=({configProperty:e,optionsTransformer:t})=>{const[s,o]=g.useState(!1),[r,n]=g.useState(""),[i,c]=g.useReducer(Zm,{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 Z(u),o(!0))}catch(h){n(h.message)}}d(e)},[e]),g.useEffect(()=>{const d=x(()=>{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 Qm(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 Xm(e,t){return new Date(e,t,0).getDate()}function Xc(e,t){const s=Qm(t,e),o=[];for(let r=1;r<=s;r++)o.push(r);return o}function Jc(){return[...Array(12).keys()].map(t=>new Date(0,t).getMonth())}function el(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=el(t);return e==="long"?s:s.map(o=>Number(o.toString().substring(2)))}function Ir(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 Jm({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 se(e){return e.toString().length===2?new Date(Date.parse(`01 Jan 20${e}`)).getFullYear():e}function ep(e){return typeof e=="string"?new Date(Date.parse(`01 ${e.substring(0,3)} 2023`)).getMonth()+1:e}function sl(e,t,s){const o=se(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 ft(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 mt(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 rl({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=Tr(n,o),d=nl(n,o,e),u=il(i,e),h=al(i,e),y=$r(t,s),v=cl(t,s,e,r),b=ul(s,t,v),M=ll(e,c);return{daysArray:y,monthsArray:u,yearsArray:l,yearsOptionsArray:d,monthsOptionsArray:h,daysOptionsArray:v,calendarDayArray:b,dayNamesArray:M}}function Tr(e="long",t=[2018,2028]){return g.useMemo(()=>tl(e,t),[e,t])}function nl(e="long",t=[2018,2028],s="en-US"){const o=Tr(e,t);return g.useMemo(()=>o.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,o])}function il(e,t="en-US"){return g.useMemo(()=>Ir(e,t),[e,t])}function al(e,t="en-US"){const s=g.useMemo(()=>Jc(),[]),o=g.useMemo(()=>Ir(e,t),[e,t]);return g.useMemo(()=>[...Array(12).keys()].map(n=>({label:o[n],value:Number(s[n])})),[o,s])}function $r(e,t){const s=se(e);return g.useMemo(()=>Xc(s,t),[t,s])}const tp=(e,t,s,o=[])=>{const r=new Date(e,t,s).getDay();return o.length>0&&o.includes(r)};function cl(e,t,s="en-US",o=[]){const r=$r(e,t);return g.useMemo(()=>r.map(i=>({label:i.toLocaleString(s),value:i,disabled:tp(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 dl({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 ul(e,t,s){return g.useMemo(()=>sl(e,t,s),[e,t,s])}var hl=(e=>(e.MMDDYY="MMDDYY",e.DDMMYY="DDMMYY",e.YYMMDD="YYMMDD",e.YYDDMM="YYDDMM",e))(hl||{});function sp({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),[y,v]=g.useState(l),[b,M]=g.useState(s),[O,A]=g.useState(o);g.useEffect(()=>{h(t)},[t]),g.useEffect(()=>{M(s)},[s]),g.useEffect(()=>{A(o)},[o]);const{yearsArray:te,yearsOptionsArray:ve,monthsArray:tt,monthsOptionsArray:Ys,daysArray:Q,daysOptionsArray:Me,calendarDayArray:zs,dayNamesArray:qs}=rl({locale:e,year:u,yearRange:y,month:b,formatOptions:{yearFormat:r,monthFormat:n,dayFormat:i},daysOfWeekFilter:d}),{formattedDate:Ws}=dl({year:u,month:b,day:O,formatString:c});return{dateActions:{setYear:h,setYearRange:v,setMonth:M,setDay:A,nextMonth:()=>{const B=b<11?se(u):se(u+1),q=b<11?b+1:0;if(!ft(B,q,O)){const _e=mt(B,q);A(_e)}q===0&&h(B),M(q)},previousMonth:()=>{const B=se(b===0?u-1:u),q=b===0?11:b-1;if(!ft(B,q,O)){const _e=mt(B,q);A(_e)}q===11&&h(B),M(q)},nextYear:()=>{const B=u<y[1]?u+1:y[0],q=se(B);if(ft(q,b,O))h(B);else{const _e=mt(se(u+1),b);A(_e),h(B)}},previousYear:()=>{const B=u>y[0]?u-1:y[0],q=se(B);if(ft(q,b,O))h(B);else{const _e=mt(se(u-1),b);A(_e),h(B)}}},dateState:{year:u,yearRange:y,month:b,day:O,yearsArray:te,yearsOptionsArray:ve,monthsArray:tt,monthsOptionsArray:Ys,daysArray:Q,daysOptionsArray:Me,calendarDayNames:qs,calendarDayArray:zs,formattedDate:Ws}}}function gl({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}=j({modelId:Y.type,modelType:Y.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 fl=({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}=gl({date:c,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const u=Number(e),h=Math.floor(u/3600),y=Math.floor(u%3600/60),v=u%60;s(h),r(y),i(v);const b=new Date;b.setHours(0,0,0,0);const M=new Date(b.getTime()+u*1e3);l(new Date(M))},[e]),{hours:t,minutes:o,seconds:n,formattedTime:d,timeActions:{setHours:s,setMinutes:r,setSeconds:i}}},op=({configProperty:e})=>{const{value:t}=Qc({configProperty:e}),s=parseInt(t||"0",10),{hours:o,minutes:r,seconds:n,formattedTime:i,timeActions:c}=fl({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 rp(e){g.useEffect(()=>{const t=()=>{try{e({__warmup:!0})}catch{}};"requestIdleCallback"in window?requestIdleCallback(t):setTimeout(t,1)},[e])}const np=e=>_.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),ip=(e=np)=>{const[t,s]=g.useState([]),[o,r]=g.useState(),{model:n,ready:i}=j({modelType:Y.type,modelId:Y.type,options:{}});g.useEffect(()=>{const l=x(()=>{s((n==null?void 0:n.dateFormatOptions.map(e))||[])});return()=>{l()}},[n,i,e]),g.useEffect(()=>{const l=x(()=>{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}}},ap=e=>_.jsx("option",{title:e,value:e,children:e},e),ml="kos:service:region:settings",pl="timeZone",cp=`${ml}-${pl}`,lp=(e=ap)=>{const[t,s]=g.useState([]),[o,r]=g.useState(""),{model:n,ready:i}=j({modelType:Y.type,modelId:Y.type,options:{}}),c=Se.factory(cp)({path:ml,attribute:pl});g.useEffect(()=>{const d=x(()=>{s((n==null?void 0:n.timeZones.map(e))||[]),n!=null&&n.timeZones.length&&Io(n==null?void 0:n.timeZones[0])});return()=>{d()}},[n,i,e]),g.useEffect(()=>{const d=x(()=>{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&&Io(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}}},yl="kos:service:region",bl="regionId",dp=`${yl}-${bl}`,up=e=>_.jsx("option",{title:e,value:e,children:e},e),wl=(e=up)=>{const[t,s]=g.useState([]),[o,r]=g.useState("factory"),{model:n,ready:i}=j({modelType:Y.type,modelId:Y.type,options:{}}),c=Se.factory(dp)({path:yl,attribute:bl});g.useEffect(()=>{const d=x(()=>{s((n==null?void 0:n.availableRegions.map(e))||[])});return()=>{d()}},[n,i,e]),g.useEffect(()=>{const d=x(()=>{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&&Ec(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}}},hp=e=>_.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),gp=(e=hp)=>{const[t,s]=g.useState([]),[o,r]=g.useState(),{model:n,ready:i}=j({modelType:Y.type,modelId:Y.type,options:{}});g.useEffect(()=>{const l=x(()=>{s((n==null?void 0:n.timeFormatOptions.map(e))||[])});return()=>{l()}},[n,i,e]),g.useEffect(()=>{const l=x(()=>{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}}},fp=(e,t)=>g.useMemo(()=>Ko(e),t),mp={config:{attributes:!0,childList:!0,subtree:!0}};function pp(e,t,s=mp){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}},io=f.createLogger({name:"usePressGesture",group:"kos-hooks"});function yp({onPressed:e,onRelease:t,intersectionStrategy:s=vl}){const o=g.useRef(!1),r=Ll.useGesture({onDragStart:l=>{io.info("onDragStart",l.type),s.validateStart(l)&&(e&&e(),o.current=!0)},onDrag:l=>{io.info("onDrag",l.type),o.current&&s.validateStop(l)&&(t&&t(),o.current=!1)},onDragEnd:l=>{io.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 Ml=()=>{const[e,t]=g.useState(!1),s=E.getInstance();return g.useEffect(()=>{const o=x(()=>{s&&s.reloading!==e&&t(s.reloading)});return()=>{o()}},[s,e]),[e]};function _l(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 $o(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 El(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 Il({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=_l(e,t),i=$o(60,s),c=$o(60,o),l=El(r);return{hourOptions:n,minuteOptions:i,secondOptions:c,amPmOptions:l}}function Tl(e,t){return me.format(e,t)}function $l({formatOptions:e,initialDate:t=new Date,locale:s="en-US",format:o="HH:mm"}){const[r,n]=g.useState(t),i=g.useCallback(M=>{n(O=>{const A=new Date(O);return A.setHours(Number(M)),A})},[]),c=g.useCallback(M=>{n(O=>{const A=new Date(O);return A.setMinutes(Number(M)),A})},[]),l=g.useCallback(M=>{n(O=>{const A=new Date(O);return A.setSeconds(Number(M)),A})},[]),d=g.useCallback(M=>{const O=new Date(M);n(O)},[]),u=Tl(r,o),{hourOptions:h,minuteOptions:y,secondOptions:v,amPmOptions:b}=Il({formatOptions:e,locale:s});return{amPmOptions:b,formattedTime:u,hourOptions:h,minuteOptions:y,secondOptions:v,setHours:i,setMinutes:c,setSeconds:l,setTime:d,time:new Date(r)}}const bp=e=>{const{regionModel:t}=wl(),s=g.useMemo(()=>({hour12:t==null?void 0:t.is12HourTimeFormat}),[t==null?void 0:t.is12HourTimeFormat]);return $l({...e,locale:t==null?void 0:t.regionId,format:t==null?void 0:t.selectedTimeFormat,formatOptions:s})};function wp(e){return t=>{const[s]=Ml();return s?_.jsx(Rc,{message:"Wait a moment while your project reloads..."}):_.jsx(e,{...t})}}const on=f.createLogger({name:"studio-properties-service",group:"Services"}),vp="/api/kos/studio/properties",Ol=async e=>{if(on.debug("sending GET for studio-properties"),!e)throw on.error("connectionId is undefined"),new Error("connectionId is undefined");return await Ae.get(vp,{},{destinationAddress:e,timeout:500})},Mp=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:Ol},Symbol.toStringTag,{value:"Module"}));var _p=Object.defineProperty,Ep=Object.getOwnPropertyDescriptor,Ip=(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&&_p(t,s,r),r};const Dl="studio-properties-model",rn={"kos.studio.tool.legacy":1};let Oo=class{constructor(e,t,s){a(this,"id");a(this,"connectionId");a(this,"logger");a(this,"data");this.id=e,this.logger=s.logger,this.data=pe(),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 activate(){const[e,t]=await Ol(this.connectionId);if(e){this.logger.error(`Error loading studio-properties: ${e}`),this.data.setValues(rn);return}if(t){const s=Object.keys(t).reduce((o,r)=>(o[r]=t[r]??r,o),{});this.data.setValues(s??rn),f.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(e){return this.data[e]}createObservableProperty(e){return Ko(()=>this.get(e))}};Oo=Ip([S(Dl)],Oo);const Tp=new le({class:Oo,type:Dl});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>w.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>w.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>an.observer});exports.AuthState=Ti;exports.BrowserKosRouter=ki;exports.BrowserRouter=da;exports.ChildModels=pt;exports.ConfigBean=Tt;exports.CoreExtensionManager=kf;exports.CoreModels=fr;exports.CreateModelTranslationsContext=Uc;exports.CreateModelTranslationsProvider=am;exports.DateDisplayFormat=hl;exports.DateHelpers=Hl;exports.DependencyLifecycle=U;exports.DependencyModels=k;exports.Device=Ds;exports.DeviceServices=sf;exports.DomIntersectionStrategy=vl;exports.EVENT_TROUBLE_ADDED=Pu;exports.EVENT_TROUBLE_REMOVED=ku;exports.EXTENSION_TROUBLE_DATA_MAPPER=bs;exports.EXTENSION_TROUBLE_MAPPER=Ht;exports.ErrorBoundaryWithFallback=Lc;exports.EventBus=Nl;exports.ExtensionManager=C;exports.FUTURE_CONTAINER_MODEL_TYPE=ua;exports.FUTURE_MODEL_TYPE=ea;exports.FUTURE_NOT_ASSIGNED=Ho;exports.FeatureFlagService=Tn;exports.FetchError=ne;exports.FutureContainerFactory=ye;exports.FutureContainerModel=ga;exports.FutureEndState=Ke;exports.FutureFactory=Je;exports.FutureHandler=Zo;exports.FutureManager=Oe;exports.FutureModel=ia;exports.FutureService=Fe;exports.HEADER_CACHE_CONTROL=un;exports.HEADER_CONTENT_TYPE=dn;exports.HEADER_DESTINATION_ADDR=ge;exports.HEADER_FOS_REQUEST_ID=hn;exports.HEADER_METHOD=Rs;exports.HEADER_ORDERED=So;exports.HEADER_REQUEST_ID=xt;exports.HEADER_REQUEST_TYPE=ie;exports.HEADER_RESPONSE_ID=Ls;exports.HEADER_SOURCE_ADDR=ln;exports.HEADER_TOPIC=cn;exports.HEADER_URL=We;exports.HEADER_WORK_TRACKER=Ao;exports.KOS_MODEL_ID=cs;exports.KeyValue=sr;exports.KeyValueServices=Sh;exports.Kos=G;exports.KosConfigPropertySpec=Se;exports.KosContainerIndex=Bo;exports.KosContextBean=Ri;exports.KosContextManager=P;exports.KosCore=E;exports.KosCoreModelPropertyMapper=oe;exports.KosDataContainer=Li;exports.KosDependencyTypes=id;exports.KosExtensionUtils=Bd;exports.KosFeatureFlags=Vl;exports.KosFetchMethods=Ni;exports.KosGlobalConfig=ko;exports.KosLog=f;exports.KosMockEvents=mn;exports.KosModel=fi;exports.KosModelCollectionProvider=sm;exports.KosModelContainer=fe;exports.KosModelContext=Hs;exports.KosModelEvents=D;exports.KosModelFactory=Mt;exports.KosModelLoader=Nc;exports.KosModelLoaderDisplay=Fc;exports.KosModelManager=yi;exports.KosModelProvider=Pc;exports.KosModelRegistrationFactory=le;exports.KosModelRegistry=Eo;exports.KosModelState=p;exports.KosModelSymbol=Bn;exports.KosModelVisitor=du;exports.KosObservableData=Di;exports.KosRegistration=Au;exports.KosSingletonRegistration=Cu;exports.KosTime=ms;exports.KosTimeContext=wr;exports.KosTimeProvider=mm;exports.KosTimeServices=Lh;exports.KosTimer=Ic;exports.KosToken=Pi;exports.KosTranslationProvider=_m;exports.KosTranslations=tc;exports.KosWSTransportStatus=gi;exports.KosWsEvents=Nt;exports.LOGIN_HOST=gn;exports.LOGIN_URL=Pl;exports.LoadingMessage=Rc;exports.LogBlock=At;exports.LogBlockContainer=js;exports.LogConfig=bt;exports.LogStream=Et;exports.LogStreamContainer=Gt;exports.LogStreamServices=Hh;exports.MODEL_DELETION_DELAY=pi;exports.MiddlewareChain=Oi;exports.ModelEffects=wt;exports.MultipleFutureHandler=ah;exports.NestedModelContext=Vs;exports.NetworkInterface=dr;exports.NetworkInterfaceContainer=Lt;exports.NetworkInterfaceServices=gf;exports.ObservableData=pe;exports.Ota=vs;exports.OutsideAlerter=Am;exports.PLUGIN_EXTENSION_NAME=Kd;exports.PORT=fn;exports.PROFILE_LOG_DEBUG=An;exports.PROFILE_LOG_INFO=Cn;exports.PROFILE_RELAX_STORE_VALIDATION=zl;exports.PROFILE_TOOLS_PREVIEW=Sn;exports.ParentModel=yt;exports.PluginExtensionManager=Gd;exports.ProgressBar=Xf;exports.ReferenceConfig=ts;exports.RegionInfo=Y;exports.RegionServices=Vu;exports.RegistrationManager=$;exports.Registry=Lf;exports.STATUS=Do;exports.ServiceFactory=H;exports.SingletonKosModelRegistrationFactory=we;exports.SoftwareInfo=Ms;exports.SoftwareInfoContext=Mr;exports.SoftwareInfoProvider=bm;exports.SoftwareInfoServices=Ig;exports.StateBean=Rt;exports.StateBeanServices=Ag;exports.StateProp=nr;exports.StatePropServices=jg;exports.StorageDevice=As;exports.StorageDeviceContainer=ze;exports.StorageDeviceServices=bf;exports.StudioProperties=Tp;exports.StudioPropertiesServices=Mp;exports.SubscriptionHandlers=J;exports.TIMER_END=pr;exports.TIMER_EVENT=mr;exports.TimerManager=Tc;exports.TokenContext=Gc;exports.TokenProvider=vm;exports.Topics=_t;exports.Trans=Um;exports.TransitionMap=ss;exports.Transitions=No;exports.Translation=Is;exports.TranslationContainer=he;exports.TranslationContainerContext=_r;exports.TranslationContext=Qg;exports.TransportFactory=go;exports.Trouble=Ct;exports.TroubleContainer=Ve;exports.TroubleServices=dg;exports.Troubles=X;exports.UsbUpdate=gr;exports.UsbUpdateContainer=kt;exports.UsbUpdateServices=Of;exports.WS_EVENT_TYPE=sc;exports.WebSocketEvents=vt;exports.WebSocketTransport=ks;exports.WsEventFactory=ar;exports.acceptOrgInvitation=Cc;exports.addDaysToDate=bn;exports.addFuture=sa;exports.addMonthsToDate=yn;exports.api=aa;exports.applyMixins=Ul;exports.buildConfigBeanModel=Fu;exports.buildFuture=Jo;exports.buildFutureModel=ra;exports.cancelFuture=oa;exports.convert=Ji;exports.convertFileSizeRaw=Fl;exports.createBaseMessage=Vn;exports.createBroadcastMessageResponse=Wn;exports.createClient=Uo;exports.createFosBaseMessage=Hn;exports.createHeaders=lo;exports.createKosHtpMessageResponse=Zn;exports.createKosMessage=zn;exports.createKosMessageResponse=Qn;exports.createMessageBody=be;exports.createModelDependency=ai;exports.createOptionKey=ud;exports.createPropKey=De;exports.createReadableStream=uo;exports.createStudioMessage=Gn;exports.createStudioMessageRequest=Yn;exports.createStudioMessageResponse=qn;exports.debounce=In;exports.deleteFuture=ta;exports.destroyKosModel=$e;exports.evaluateScopes=Gi;exports.executeChildrenModelLifecycle=di;exports.executeDependentModelLifecycle=rt;exports.executeListLifecycle=li;exports.fetchModel=Tm;exports.findModel=zd;exports.findModels=vi;exports.fireIntent=xi;exports.formatDate=Mn;exports.formatDateSince=pn;exports.formatDateTime=En;exports.formatTime=_n;exports.getAllKosCompanionModels=Wd;exports.getCalendarMonthArray=sl;exports.getConfigBean=Ki;exports.getDayStrings=ol;exports.getDays=Xm;exports.getDaysArray=Xc;exports.getDaysInMonth=Po;exports.getDependenciesByLifecycle=ci;exports.getFormattedDate=Jm;exports.getFormattedMonth=ep;exports.getFormattedMonthsArray=Ir;exports.getFormattedYear=se;exports.getFormattedYearsArray=tl;exports.getFutures=fh;exports.getKosCompanionModel=qd;exports.getKosLocalizationDescriptor=Za;exports.getKosMessageLogging=xn;exports.getKosModel=wi;exports.getKosModelSync=Ze;exports.getKosModelType=Yd;exports.getKosSessionKey=Ci;exports.getLastDayOfMonth=mt;exports.getLocalizationDescriptor=Kg;exports.getLogLevel=kn;exports.getLogMessageToStudio=Nn;exports.getMessageBody=ho;exports.getMonthsArray=Jc;exports.getQueryParams=ae;exports.getTranslations=Wa;exports.getYearsArray=el;exports.hasDecimals=ji;exports.hasKosProfile=ao;exports.hslStringToHex=On;exports.hslToHex=$n;exports.initKosProvider=lm;exports.isBoolean=Yo;exports.isKosCompanionTypeFactory=mi;exports.isKosDataModel=os;exports.isKosLoggingEnabled=Zl;exports.isKosModel=ee;exports.isKosModelContainer=ui;exports.isKosModelReady=ds;exports.isLeapYear=Lo;exports.isLocalRefId=Iu;exports.isNumber=xs;exports.isValidDate=ft;exports.kosAction=V;exports.kosAutoEffect=x;exports.kosChild=ce;exports.kosCompanion=fd;exports.kosComputed=Ko;exports.kosConfigBean=Ns;exports.kosConfigProperty=ih;exports.kosContext=md;exports.kosDependency=Ut;exports.kosEffect=Fi;exports.kosFuture=yr;exports.kosLogger=pd;exports.kosModel=S;exports.kosModelEffect=ei;exports.kosObservable=Go;exports.kosParentAware=Ps;exports.kosReference=yd;exports.kosStateBean=Bf;exports.kosStateProp=Kf;exports.kosSubscribe=bd;exports.kosTopicHandler=R;exports.kosWhen=mo;exports.login=Dc;exports.mapConfigBeanModelToDto=zi;exports.mapDataToModel=co;exports.mapDtoToConfigBeanModel=Vi;exports.mapDtoToFutureModel=Xo;exports.mapDtoToFutureOptions=Qo;exports.mapUpdateDtoToConfigBeanModel=Yi;exports.modelFactory=Qe;exports.modifyConfigBean=Bi;exports.modifyFuture=mh;exports.pairedClientHeartbeat=pu;exports.pipe=Ai;exports.preloadKosModel=Xd;exports.processId=Gl;exports.processMiddleware=hu;exports.registerCompanionModel=Qd;exports.registerCoreModels=vc;exports.registerExtensionPoint=xo;exports.registerIntentHandler=Lu;exports.registerKosModel=_i;exports.registerLegacyModel=Mi;exports.resetKosModel=bi;exports.resetPassword=Ac;exports.resolveBaseUrl=$i;exports.resolveChild=hi;exports.resolveContainerDeltas=jl;exports.resolveItemListDeltas=Kl;exports.resolveKosCompanion=fo;exports.resolveKosContext=Ou;exports.resolveKosProfiles=Ln;exports.resolveListDeltas=Bl;exports.resolveServiceUrl=z;exports.resolveVariable=Dn;exports.retryWithExponentialBackoff=bu;exports.sendBroadcastMessage=dd;exports.sendKosHttpMessageResponse=Jn;exports.sendKosMessage=ad;exports.sendKosMessageResponse=Xn;exports.sendRequest=Tu;exports.sendStudioMessage=ld;exports.sendStudioMessageRequest=cd;exports.startPasswordReset=Sc;exports.stringComponentInsert=qc;exports.studioAcceptOrgInvitation=Yf;exports.studioLogin=Gf;exports.studioResetPassword=Vf;exports.studioStartPasswordReset=Hf;exports.subscribeStore=xf;exports.syncPublish=$u;exports.transitionToActive=oi;exports.transitionToInit=ii;exports.transitionToLoad=ni;exports.transitionToReady=ri;exports.transitionToUnload=vd;exports.troubleByTypeReducer=Xg;exports.troubleDataFactory=Ua;exports.unloadKosModel=Vd;exports.unsubscribeIntentService=Ru;exports.updateCompanionModelRegistration=fu;exports.updateModelRegistration=gu;exports.updateRegion=Ec;exports.updateTimeZone=Io;exports.useAmPmValues=El;exports.useCalendarDayArray=ul;exports.useConfigBean=Wm;exports.useConfigProperty=Qc;exports.useContextModel=em;exports.useContextModelHierarchy=xc;exports.useDateArrays=rl;exports.useDateProps=sp;exports.useDateRelativeConfig=op;exports.useDateRelativeData=fl;exports.useDayNames=ll;exports.useDayOptions=cl;exports.useDays=$r;exports.useDevice=Hc;exports.useFormattedDate=dl;exports.useFormattedTime=Tl;exports.useFunctionWarmup=rp;exports.useHourValues=_l;exports.useKosCore=Bc;exports.useKosDateFormats=ip;exports.useKosModel=j;exports.useKosRegions=wl;exports.useKosTime=br;exports.useKosTimeContext=pm;exports.useKosTimeFormats=gp;exports.useKosTimeZones=lp;exports.useKosTranslation=Gm;exports.useKosTranslationContext=Em;exports.useLocalComputed=fp;exports.useModelFromHierarchy=rm;exports.useMonths=il;exports.useMonthsOptions=al;exports.useMutationObserver=pp;exports.useNetworkInterfaceContainer=Vc;exports.useOta=Yc;exports.usePressGesture=yp;exports.useProjectReload=Ml;exports.useRegionTimeProps=bp;exports.useRegionalTimeDate=gl;exports.useSoftwareInfo=vr;exports.useSoftwareInfoContext=wm;exports.useStateProperty=Cm;exports.useStorageDeviceContainer=zc;exports.useSuspenseData=To;exports.useTimeOptions=Il;exports.useTimeProps=$l;exports.useTimeValues=$o;exports.useTimer=Lm;exports.useTranslationContainer=Wc;exports.useTroubleContainerModel=Er;exports.useTroubleModel=Vm;exports.useTroublePresence=Ym;exports.useUsbUpdateContainer=Zc;exports.useYears=Tr;exports.useYearsOptions=nl;exports.uuid=Ft;exports.variableToHex=Yl;exports.waitForRequest=jo;exports.whenReady=Z;exports.withDevice=Im;exports.withKosTime=$m;exports.withNetworkInterfaceContainer=Om;exports.withOta=Dm;exports.withProjectReloading=wp;exports.withSoftwareInfo=ym;exports.withStorageDeviceContainer=Rm;exports.withTranslationContainer=Hm;exports.withTroubleContainer=zm;exports.withUsbUpdateContainer=qm;exports.wrapPromise=Co;
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},Vs=h.createContext(Im),Tm=()=>{const e=h.useContext(Vs);if(e==null)throw new Error("useModels must be used within a KosModelProvider");return e.model},Uc=({children:e})=>{const[t,s]=h.useState(),o=h.useCallback(r=>(s(r),!0),[s]);return M.jsx(Vs.Provider,{value:{model:t,setModel:o},children:e})},jc=f.createLogger({name:"kos-model-hierarchy-context"}),$m={models:[],addModel:()=>{jc.debug("Default implementation being used. Do Nothing.")}},Ys=h.createContext($m),Om=({children:e})=>{const[t,s]=h.useState([]),o=h.useCallback(r=>{t.includes(r)||(jc.debug("adding to hierarchy context",r.id),s(n=>[...n,r]))},[t]);return M.jsx(Ys.Provider,{value:{models:t,addModel:o},children:e})},Dm=()=>!0,Bc=e=>{const t=h.useContext(Ys);if(!t)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(e==null?void 0:e.filter)||Dm;return h.useMemo(()=>t.models.filter(s),[t.models,s])},Sm=e=>Bc({filter:s=>{const o=Ze(s.id);return(o==null?void 0:o.type)===e}})[0],Am=f.createLogger({name:"kos-model-loader"}),Cm=()=>M.jsx("div",{}),Kc=({fallback:e,children:t,...s})=>M.jsx(Uc,{children:M.jsx(Fc,{fallback:e,children:M.jsx(h.Suspense,{children:M.jsx(Gc,{...s,children:t})})})}),Gc=e=>{const[t,s]=h.useState(),[o,r]=h.useState(!1),{setModel:n}=h.useContext(Vs),i=h.useContext(Ys);if(h.useEffect(()=>{e.model&&(s(e.model),n(e.model),r(!0),i&&i.addModel(e.model))},[i,e.model,n]),e.error)throw Am.error(e.error),new Error(e.error);const c=e.loading||M.jsx(Cm,{});return M.jsx(M.Fragment,{children:t&&o?e.children:c})},cs={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},Hc=h.createContext(cs),Rm=({translations:e=cs,children:t})=>{const s={header:{...cs.header,...e.header},createModal:{...cs.createModal,...e.createModal}};return M.jsx(Hc.Provider,{value:s,children:t})};function Lm(e,t){const s=_.create(e,!1,t),o=s.whenReady().then(()=>s);return Lo(o)}const Vc=h.createContext(void 0),km=(e={models:{},preloadModels:[]},t)=>{const s=Lm(e,t),o=({children:r})=>{const n=s.read(),[i,c]=h.useState(n.isOnline);return h.useEffect(()=>{const l=x(()=>{c(n.isOnline)});return()=>{l()}},[n]),M.jsx(Vc.Provider,{value:{kosCore:n,online:i},children:r})};return{KosCoreContextProvider:un.observer(o)}},Yc=()=>{const e=h.useContext(Vc);if(e===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return e},Pm=8,xm=(e=0)=>new Promise(t=>{setTimeout(()=>{t(!0)},2**e*10)}),Te=new Map;function Nm(e,t){if(Te.has(e)){const s=Te.get(e);if(s.status==="finished"){const o=_.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 Fm(e,t){return Nm(e,t)}async function Um(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>Pm)throw Error(`KOS Model ${s} has not been found`);await xm(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=Yc(),[i,c]=h.useState(!1),[l,d]=h.useState(),{kosModel:u,model:g}=Fm(t||s||"",()=>Um(n.kosCore,e));return h.useEffect(()=>{async function y(){try{return await n.kosCore.whenReady(),o&&await(u==null?void 0:u.fsm.transitionTo(O.GO_ACTIVE,p.ACTIVE)),c(!0),u}catch(b){d(b.message)}}let v;return n.kosCore&&t&&y().then(b=>{v=x(()=>{const E=(b==null?void 0:b.status)===p.READY;c(E)})}).catch(b=>{console.error(b)}),()=>{if(o){if(g!=null&&g.id){const b=n.kosCore.modelManager.getModelById(g.id);b==null||b.fsm.transitionTo(O.GO_INACTIVE,p.INACTIVE).then(()=>{if(r){const E=g.id;Oe(g).then(()=>{Te.delete(E),v==null||v()})}})}}else r&&g&&Oe(g).then(()=>{Te.delete(t),v==null||v()})}},[o,r,n.kosCore,u,g,t]),{model:g,ready:i,error:l,status:{model:g,ready:i,error:l},KosModelLoader:Kc}},Mr=()=>{const e=ps.type;return B({modelId:e,modelType:ps.type,options:{}})},Er=h.createContext(void 0),jm=({children:e})=>{const{model:t,ready:s}=Mr(),o=h.useMemo(()=>s&&t?{model:t}:{},[s,t]);return M.jsx(Er.Provider,{value:o,children:e})},Bm=()=>{const e=h.useContext(Er);if(!e)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return e},_r=()=>{const e=Es.type;return B({modelId:e,modelType:Es.type,options:{}})};function Km(e){return()=>t=>{const{model:s,status:o,KosModelLoader:r}=_r();return M.jsx(r,{...o,children:M.jsx(e,{...t,softwareInfo:s})})}}const Ir=h.createContext(void 0),Gm=({children:e})=>{const{model:t,ready:s}=_r(),o=h.useMemo(()=>s&&t?{model:t}:{},[s,t]);return M.jsx(Ir.Provider,{value:o,children:e})},Hm=()=>{const e=h.useContext(Ir);if(!e)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return e},zc=new Ui,qc=h.createContext(zc);function Vm({children:e}){return M.jsx(qc.Provider,{value:zc,children:e})}const Tr=h.createContext(void 0),Ym=()=>{const e=window.location.origin,t=ae();return(t==null?void 0:t.host)||e},zm=({children:e,appContext:t,locale:s="en",resolver:o,rootUrl:r,descriptorResolver:n})=>{const[i,c]=h.useState(!1),[l,d]=h.useState(),[u,g]=h.useState(),y=r||Ym(),v=h.useMemo(()=>t??"app/system",[t]);h.useEffect(()=>{async function $(){const te=(Array.isArray(v)?v:[v]).map(Q=>(n||tc(Q))()),zs=(await Promise.allSettled(te)).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(Ws=>{const Zs=Me.namespaces[Ws];Zs.basePath=qs}),{...Q,namespaces:{...Q.namespaces,...Me.namespaces}}},{});d(zs)}$()},[v,n]),h.useEffect(()=>{async function $(){if(l){const S=y,{translations:te}=await ic.init({lang:s,descriptor:l,defaultNamespace:"common",resolver:o,rootUrl:S});g(te),c(!0)}}$()},[s,l,o,y]);const b=h.useMemo(()=>i?{setLocale:$=>{u&&(u.currentLocale=$)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,u]),E=i?e:null;return M.jsx(Tr.Provider,{value:b,children:E})},qm=()=>{const e=h.useContext(Tr);if(!e)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return e},Wc=()=>{const e=Ss.type;return B({modelId:e,modelType:Ss.type,options:{}})};function Wm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Wc();return M.jsx(r,{...o,children:M.jsx(e,{...t,device:s})})}}function Zm(e,t,s){const o=new Promise(r=>{_.getInstance().whenReady().then(()=>{const{model:n}=_.getInstance().modelManager.createModelInstance(e,t??e,s);return n.whenReady().then(()=>{r(n.modelData)})})});return Lo(o)}function Jm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Mr();return M.jsx(r,{...o,children:M.jsx(e,{...t,kosTime:s})})}}const Zc=()=>{const e=Pt.type;return B({modelId:e,modelType:Pt.type,options:{}})};function Qm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Zc();return M.jsx(r,{...o,children:M.jsx(e,{...t,networkInterfaceContainer:s})})}}const Jc=()=>{const e=Ms.type;return B({modelId:e,modelType:Ms.type,options:{}})};function Xm(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Jc();return M.jsx(r,{...o,children:M.jsx(e,{...t,oTA:s})})}}function ep(e,t){h.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 tp(e){const t=h.useRef(null),s=e.onAlert;return ep(t,s),M.jsx("div",{ref:t,style:{width:"100%"},children:e.children})}const sp=e=>{var d;const{stateProp:t}=e,[s,o]=h.useState((d=e.stateProp)==null?void 0:d.value),[r,n]=h.useState(!1),[i,c]=h.useState(void 0);return h.useEffect(()=>{async function u(g){try{g&&(await J(g),n(!0))}catch(y){c(y.message)}}u(t)},[t]),h.useEffect(()=>{const u=x(()=>{t&&r&&o(t.value)});return()=>{u()}},[r,t]),[s,{ready:r,error:i}]},Qc=()=>{const[e,t]=h.useState(!1),[s,o]=h.useState([]),r=ze.type,n=B({modelId:r,modelType:ze.type,options:{}});return h.useEffect(()=>{const i=x(()=>{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 op(e){return t=>{const{model:s,status:o,KosModelLoader:r}=Qc();return M.jsx(r,{...o,children:M.jsx(e,{...t,storageDeviceContainer:s})})}}const rp=({timerName:e,onTimerExpired:t,timerEventActions:s,autoStart:o})=>{const r=Ac.getTimer(e);return h.useEffect(()=>{const n=U(br,i=>{const{name:c,action:l,remainingTime:d}=i==null?void 0:i.body;c===e&&r&&(l===wr?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)}},np=e=>{const t=/[\\^$.*+?()[\]{}|]/g;return RegExp(t.source).test(e)?e.replace(t,"\\$&"):e},ip=e=>e instanceof RegExp,ap=e=>typeof e=="string",cp=(e,t,s)=>{if(e===""||t==="")return e;let o=t;ip(o)||(o=new RegExp("("+np(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},Xc=(e,t,s)=>{let o=e;return Array.isArray(o)||(o=[o]),o.flatMap(r=>ap(r)?cp(r,t,s):r)};function lp(e,t){let s=e;return Object.entries(t).forEach(([o,r])=>{const n=new RegExp(`<${o}>(.*?)</${o}>|<${o}/>`,"g");s=Xc(s,n,(i,c)=>r.type==="br"?M.jsx("br",{}):h.cloneElement(r,{key:`${o}-${c}`},i))}),s}const dp=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=lp(c,r||{});return M.jsx("span",{className:e.className,children:l})},Fe=new Map;function up(e,t){if(Fe.has(e)){const s=Fe.get(e);if(s.status==="finished")return s.result;throw s.promise}else{const s=t().then(r=>{Fe.set(e,{status:"finished",result:r})},r=>{throw Fe.set(e,{status:"error",error:r}),r}),o={status:"pending",promise:s};throw Fe.set(e,o),s}}function $o(e,t){return up(e,t)}const hp=async()=>{const e=await Ii(he.type);return await J(e.model),e.model},gp=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),Fe.set(r,{status:"finished",result:n})}return o},fp=(e,t)=>{const s=[e].flat(),[o,...r]=s,n=$o(he.type,hp),i=s.join("__"),c=$o(i,()=>gp(n,o,r)),l=h.useMemo(()=>({exists:u=>{const g=t!=null&&t.keyPrefix?`${t.keyPrefix}.${u}`:u;return c?c.exists(g):!1}}),[t==null?void 0:t.keyPrefix,c]);return{t:h.useCallback((u,g)=>{const y=t!=null&&t.keyPrefix?`${t.keyPrefix}.${u}`:u;return c?c.resolveKey(y,g):(f.debug(`Translation model ${e} not ready for key: ${y}`),y)},[t==null?void 0:t.keyPrefix,e,c]),i18n:l}},el=()=>{const e=he.type;return B({modelId:e,modelType:he.type,options:{}})};function mp(e){return t=>{const{model:s,status:o,KosModelLoader:r}=el();return M.jsx(r,{...o,children:M.jsx(e,{...t,translationContainer:s})})}}const pp=e=>B({modelId:e,modelType:Lt.type}),$r=()=>B({modelId:Ve.type,modelType:Ve.type,options:{}}),yp=({troubleType:e,condition:t})=>{const{model:s}=$r(),[o,r]=h.useState(!1),[n,i]=h.useState([]),c=h.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 h.useEffect(()=>x(()=>{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 bp(e){return t=>{const{model:s,status:o,KosModelLoader:r}=$r();return M.jsx(r,{...o,children:M.jsx(e,{...t,troubleContainer:s})})}}const tl=()=>{const e=Nt.type,t=B({modelId:e,modelType:Nt.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,o]=h.useState(!1),[r,n]=h.useState(!1),[i,c]=h.useState([]);return h.useEffect(()=>{const l=x(()=>{var d,u,g;o(((d=t.model)==null?void 0:d.isUsbInserted)??!1),n(((u=t.model)==null?void 0:u.hasAvailableUpdates)??!1),c(((g=t.model)==null?void 0:g.data)??[])});return()=>{l()}},[t.model]),{...t,inserted:s,updateAvailable:r,updates:i}};function wp(e){return t=>{const{model:s,status:o,KosModelLoader:r}=tl();return M.jsx(r,{...o,children:M.jsx(e,{...t,usbUpdateContainer:s})})}}const vp=({path:e,propKey:t})=>{const{status:s}=B({modelType:Ot.type,modelId:e,options:{path:e}}),[o,r]=h.useState(!1),[n,i]=h.useState(),[c,l]=h.useState(""),[d,u]=h.useState(),g=y=>{n&&t&&n.updateProperty(t,y)};return h.useEffect(()=>{var y;s.model&&i(s.model),s.model&&t&&((y=s.model)!=null&&y.props.has(t)?l(s.model.props[t]):u(`property ${t} not found`)),s.ready&&r(s.ready)},[s.ready,s.model,t]),h.useEffect(()=>{t&&w.autorun(()=>{const y=n==null?void 0:n.props[t];l(y||"")})},[n,t]),{config:n,ready:o,value:c,error:d,updateValue:g}},Mp=(e,t)=>{switch(t.type){case"UPDATE":return t.payload;default:return e}},sl=({configProperty:e,optionsTransformer:t})=>{const[s,o]=h.useState(!1),[r,n]=h.useState(""),[i,c]=h.useReducer(Mp,{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=h.useCallback(d=>{var g;let u="factory";typeof d=="string"?u=d:(g=d==null?void 0:d.target)!=null&&g.value&&(u=d.target.value),u&&(e==null||e.updateProperty(u))},[e]);return h.useEffect(()=>{async function d(u){try{u&&(await J(u),o(!0))}catch(g){n(g.message)}}d(e)},[e]),h.useEffect(()=>{const d=x(()=>{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 Ep(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 _p(e,t){return new Date(e,t,0).getDate()}function ol(e,t){const s=Ep(t,e),o=[];for(let r=1;r<=s;r++)o.push(r);return o}function rl(){return[...Array(12).keys()].map(t=>new Date(0,t).getMonth())}function nl(e=[2018,2028]){const t=[];for(let s=e[0];s<=e[1];s++)t.push(s);return t}function il(e,t=[2018,2028]){const s=nl(t);return e==="long"?s:s.map(o=>Number(o.toString().substring(2)))}function Or(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 Ip({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 se(e){return e.toString().length===2?new Date(Date.parse(`01 Jan 20${e}`)).getFullYear():e}function Tp(e){return typeof e=="string"?new Date(Date.parse(`01 ${e.substring(0,3)} 2023`)).getMonth()+1:e}function al(e,t,s){const o=se(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 mt(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 pt(e,t){return new Date(e,t,0).getDate()}function cl(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 ll({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=Dr(n,o),d=dl(n,o,e),u=ul(i,e),g=hl(i,e),y=Sr(t,s),v=gl(t,s,e,r),b=pl(s,t,v),E=fl(e,c);return{daysArray:y,monthsArray:u,yearsArray:l,yearsOptionsArray:d,monthsOptionsArray:g,daysOptionsArray:v,calendarDayArray:b,dayNamesArray:E}}function Dr(e="long",t=[2018,2028]){return h.useMemo(()=>il(e,t),[e,t])}function dl(e="long",t=[2018,2028],s="en-US"){const o=Dr(e,t);return h.useMemo(()=>o.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,o])}function ul(e,t="en-US"){return h.useMemo(()=>Or(e,t),[e,t])}function hl(e,t="en-US"){const s=h.useMemo(()=>rl(),[]),o=h.useMemo(()=>Or(e,t),[e,t]);return h.useMemo(()=>[...Array(12).keys()].map(n=>({label:o[n],value:Number(s[n])})),[o,s])}function Sr(e,t){const s=se(e);return h.useMemo(()=>ol(s,t),[t,s])}const $p=(e,t,s,o=[])=>{const r=new Date(e,t,s).getDay();return o.length>0&&o.includes(r)};function gl(e,t,s="en-US",o=[]){const r=Sr(e,t);return h.useMemo(()=>r.map(i=>({label:i.toLocaleString(s),value:i,disabled:$p(e,t,i,o)})),[o,s,t,r,e])}function fl(e="en-US",t="short"){return h.useMemo(()=>cl(e,t),[e,t])}function ml({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 pl(e,t,s){return h.useMemo(()=>al(e,t,s),[e,t,s])}var yl=(e=>(e.MMDDYY="MMDDYY",e.DDMMYY="DDMMYY",e.YYMMDD="YYMMDD",e.YYDDMM="YYDDMM",e))(yl||{});function Op({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,g]=h.useState(t),[y,v]=h.useState(l),[b,E]=h.useState(s),[$,S]=h.useState(o);h.useEffect(()=>{g(t)},[t]),h.useEffect(()=>{E(s)},[s]),h.useEffect(()=>{S(o)},[o]);const{yearsArray:te,yearsOptionsArray:ve,monthsArray:tt,monthsOptionsArray:zs,daysArray:Q,daysOptionsArray:Me,calendarDayArray:qs,dayNamesArray:Ws}=ll({locale:e,year:u,yearRange:y,month:b,formatOptions:{yearFormat:r,monthFormat:n,dayFormat:i},daysOfWeekFilter:d}),{formattedDate:Zs}=ml({year:u,month:b,day:$,formatString:c});return{dateActions:{setYear:g,setYearRange:v,setMonth:E,setDay:S,nextMonth:()=>{const K=b<11?se(u):se(u+1),W=b<11?b+1:0;if(!mt(K,W,$)){const Ee=pt(K,W);S(Ee)}W===0&&g(K),E(W)},previousMonth:()=>{const K=se(b===0?u-1:u),W=b===0?11:b-1;if(!mt(K,W,$)){const Ee=pt(K,W);S(Ee)}W===11&&g(K),E(W)},nextYear:()=>{const K=u<y[1]?u+1:y[0],W=se(K);if(mt(W,b,$))g(K);else{const Ee=pt(se(u+1),b);S(Ee),g(K)}},previousYear:()=>{const K=u>y[0]?u-1:y[0],W=se(K);if(mt(W,b,$))g(K);else{const Ee=pt(se(u-1),b);S(Ee),g(K)}}},dateState:{year:u,yearRange:y,month:b,day:$,yearsArray:te,yearsOptionsArray:ve,monthsArray:tt,monthsOptionsArray:zs,daysArray:Q,daysOptionsArray:Me,calendarDayNames:Ws,calendarDayArray:qs,formattedDate:Zs}}}function bl({date:e=new Date,dateFormat:t,timeFormat:s,options:o={}}){const[r,n]=h.useState("Formatting Time..."),[i,c]=h.useState("Formatting Date..."),l=!!o.ignoreDateFormat,{model:d,ready:u}=B({modelId:z.type,modelType:z.type,options:{}}),g=typeof e=="string"?me.parseISO(e):e;return h.useEffect(()=>{l?c(""):t?c(me.format(g,t)):u&&c(me.format(g,d!=null&&d.selectedDateFormat?d==null?void 0:d.selectedDateFormat:""))},[l,e,t,g,d,u]),h.useEffect(()=>{s?n(me.format(g,s)):u&&n(me.format(g,d!=null&&d.selectedTimeFormat?d==null?void 0:d.selectedTimeFormat:""))},[e,s,g,d,u]),{formattedDate:i,formattedTime:r}}const wl=({secondsFromMidnight:e=0})=>{const[t,s]=h.useState(0),[o,r]=h.useState(0),[n,i]=h.useState(0),[c,l]=h.useState(new Date),{formattedTime:d}=bl({date:c,options:{ignoreDateFormat:!0}});return h.useEffect(()=>{const u=Number(e),g=Math.floor(u/3600),y=Math.floor(u%3600/60),v=u%60;s(g),r(y),i(v);const b=new Date;b.setHours(0,0,0,0);const E=new Date(b.getTime()+u*1e3);l(new Date(E))},[e]),{hours:t,minutes:o,seconds:n,formattedTime:d,timeActions:{setHours:s,setMinutes:r,setSeconds:i}}},Dp=({configProperty:e})=>{const{value:t}=sl({configProperty:e}),s=parseInt(t||"0",10),{hours:o,minutes:r,seconds:n,formattedTime:i,timeActions:c}=wl({secondsFromMidnight:s}),l=h.useRef();return h.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 Sp(e,t={}){const{intervalMs:s=5*60*1e3,immediate:o=!0}=t;h.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 Ap=e=>M.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),Cp=(e=Ap)=>{const[t,s]=h.useState([]),[o,r]=h.useState(),{model:n,ready:i}=B({modelType:z.type,modelId:z.type,options:{}});h.useEffect(()=>{const l=x(()=>{s((n==null?void 0:n.dateFormatOptions.map(e))||[])});return()=>{l()}},[n,i,e]),h.useEffect(()=>{const l=x(()=>{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=h.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}}},Rp=e=>M.jsx("option",{title:e,value:e,children:e},e),vl="kos:service:region:settings",Ml="timeZone",Lp=`${vl}-${Ml}`,kp=(e=Rp)=>{const[t,s]=h.useState([]),[o,r]=h.useState(""),{model:n,ready:i}=B({modelType:z.type,modelId:z.type,options:{}}),c=Ae.factory(Lp)({path:vl,attribute:Ml});h.useEffect(()=>{const d=x(()=>{s((n==null?void 0:n.timeZones.map(e))||[]),n!=null&&n.timeZones.length&&To(n==null?void 0:n.timeZones[0])});return()=>{d()}},[n,i,e]),h.useEffect(()=>{const d=x(()=>{r(c.value||"")});return()=>{d()}},[c.value]);const l=h.useCallback(d=>{var g;let u="factory";typeof d=="string"?u=d:(g=d==null?void 0:d.target)!=null&&g.value&&(u=d.target.value),u&&To(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}}},El="kos:service:region",_l="regionId",Pp=`${El}-${_l}`,xp=e=>M.jsx("option",{title:e,value:e,children:e},e),Il=(e=xp)=>{const[t,s]=h.useState([]),[o,r]=h.useState("factory"),{model:n,ready:i}=B({modelType:z.type,modelId:z.type,options:{}}),c=Ae.factory(Pp)({path:El,attribute:_l});h.useEffect(()=>{const d=x(()=>{s((n==null?void 0:n.availableRegions.map(e))||[])});return()=>{d()}},[n,i,e]),h.useEffect(()=>{const d=x(()=>{r(c.value||"factory")});return()=>{d()}},[c.value]);const l=h.useCallback(d=>{var g;let u="factory";typeof d=="string"?u=d:(g=d==null?void 0:d.target)!=null&&g.value&&(u=d.target.value),u&&Dc(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}}},Np=e=>M.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),Fp=(e=Np)=>{const[t,s]=h.useState([]),[o,r]=h.useState(),{model:n,ready:i}=B({modelType:z.type,modelId:z.type,options:{}});h.useEffect(()=>{const l=x(()=>{s((n==null?void 0:n.timeFormatOptions.map(e))||[])});return()=>{l()}},[n,i,e]),h.useEffect(()=>{const l=x(()=>{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=h.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}}},Up=(e,t)=>h.useMemo(()=>Vo(e),t),jp={config:{attributes:!0,childList:!0,subtree:!0}};function Bp(e,t,s=jp){const[o,r]=h.useState(null);h.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]),h.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 Tl={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}},ao=f.createLogger({name:"usePressGesture",group:"kos-hooks"});function Kp({onPressed:e,onRelease:t,intersectionStrategy:s=Tl}){const o=h.useRef(!1),r=Fl.useGesture({onDragStart:l=>{ao.info("onDragStart",l.type),s.validateStart(l)&&(e&&e(),o.current=!0)},onDrag:l=>{ao.info("onDrag",l.type),o.current&&s.validateStop(l)&&(t&&t(),o.current=!1)},onDragEnd:l=>{ao.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 $l=()=>{const[e,t]=h.useState(!1),s=_.getInstance();return h.useEffect(()=>{const o=x(()=>{s&&s.reloading!==e&&t(s.reloading)});return()=>{o()}},[s,e]),[e]};function Ol(e=!1,t="2-digit"){return h.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 Oo(e,t="2-digit",s=0,o=0){return h.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 Dl(e="en-US"){return h.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 Sl({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=Ol(e,t),i=Oo(60,s),c=Oo(60,o),l=Dl(r);return{hourOptions:n,minuteOptions:i,secondOptions:c,amPmOptions:l}}function Al(e,t){return me.format(e,t)}function Cl({formatOptions:e,initialDate:t=new Date,locale:s="en-US",format:o="HH:mm"}){const[r,n]=h.useState(t),i=h.useCallback(E=>{n($=>{const S=new Date($);return S.setHours(Number(E)),S})},[]),c=h.useCallback(E=>{n($=>{const S=new Date($);return S.setMinutes(Number(E)),S})},[]),l=h.useCallback(E=>{n($=>{const S=new Date($);return S.setSeconds(Number(E)),S})},[]),d=h.useCallback(E=>{const $=new Date(E);n($)},[]),u=Al(r,o),{hourOptions:g,minuteOptions:y,secondOptions:v,amPmOptions:b}=Sl({formatOptions:e,locale:s});return{amPmOptions:b,formattedTime:u,hourOptions:g,minuteOptions:y,secondOptions:v,setHours:i,setMinutes:c,setSeconds:l,setTime:d,time:new Date(r)}}const Gp=e=>{const{regionModel:t}=Il(),s=h.useMemo(()=>({hour12:t==null?void 0:t.is12HourTimeFormat}),[t==null?void 0:t.is12HourTimeFormat]);return Cl({...e,locale:t==null?void 0:t.regionId,format:t==null?void 0:t.selectedTimeFormat,formatOptions:s})};function Hp(e){return t=>{const[s]=$l();return s?M.jsx(Nc,{message:"Wait a moment while your project reloads..."}):M.jsx(e,{...t})}}const cn=f.createLogger({name:"studio-properties-service",group:"Services"}),Vp="/api/kos/studio/properties",Rl=async e=>{if(cn.debug("sending GET for studio-properties"),!e)throw cn.error("connectionId is undefined"),new Error("connectionId is undefined");return await Ce.get(Vp,{},{destinationAddress:e,timeout:500})},Yp=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:Rl},Symbol.toStringTag,{value:"Module"}));var zp=Object.defineProperty,qp=Object.getOwnPropertyDescriptor,Wp=(e,t,s,o)=>{for(var r=o>1?void 0:o?qp(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&&zp(t,s,r),r};const Ll="studio-properties-model",ln={"kos.studio.tool.legacy":1};let Do=class{constructor(e,t,s){a(this,"id");a(this,"connectionId");a(this,"logger");a(this,"data");this.id=e,this.logger=s.logger,this.data=pe(),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 activate(){const[e,t]=await Rl(this.connectionId);if(e){this.logger.error(`Error loading studio-properties: ${e}`),this.data.setValues(ln);return}if(t){const s=Object.keys(t).reduce((o,r)=>(o[r]=t[r]??r,o),{});this.data.setValues(s??ln),f.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(e){return this.data[e]}createObservableProperty(e){return Vo(()=>this.get(e))}};Do=Wp([D(Ll)],Do);const Zp=new le({class:Do,type:Ll});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>w.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>w.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>un.observer});exports.AuthState=Ai;exports.BrowserKosRouter=ji;exports.BrowserRouter=ma;exports.ChildModels=bt;exports.ConfigBean=Ot;exports.CoreExtensionManager=im;exports.CoreModels=yr;exports.CreateModelTranslationsContext=Hc;exports.CreateModelTranslationsProvider=Rm;exports.DateDisplayFormat=yl;exports.DateHelpers=Zl;exports.DependencyLifecycle=F;exports.DependencyModels=L;exports.Device=Ss;exports.DeviceServices=Df;exports.DomIntersectionStrategy=Tl;exports.EVENT_KOS_MODEL_READY=Ro;exports.EVENT_TROUBLE_ADDED=nh;exports.EVENT_TROUBLE_REMOVED=ih;exports.EXTENSION_TROUBLE_DATA_MAPPER=ws;exports.EXTENSION_TROUBLE_MAPPER=Yt;exports.ErrorBoundaryWithFallback=Fc;exports.EventBus=Kl;exports.ExtensionManager=C;exports.FUTURE_CONTAINER_MODEL_TYPE=pa;exports.FUTURE_MODEL_TYPE=na;exports.FUTURE_NOT_ASSIGNED=zo;exports.FeatureFlagService=Sn;exports.FetchError=ne;exports.FutureContainerFactory=ye;exports.FutureContainerModel=ba;exports.FutureEndState=Ke;exports.FutureFactory=Xe;exports.FutureHandler=Xo;exports.FutureManager=De;exports.FutureModel=ua;exports.FutureService=yt;exports.HEADER_CACHE_CONTROL=mn;exports.HEADER_CONTENT_TYPE=fn;exports.HEADER_DESTINATION_ADDR=ge;exports.HEADER_FOS_REQUEST_ID=pn;exports.HEADER_METHOD=Ls;exports.HEADER_ORDERED=Ao;exports.HEADER_REQUEST_ID=Ft;exports.HEADER_REQUEST_TYPE=ie;exports.HEADER_RESPONSE_ID=ks;exports.HEADER_SOURCE_ADDR=gn;exports.HEADER_TOPIC=hn;exports.HEADER_URL=We;exports.HEADER_WORK_TRACKER=Co;exports.KOS_MODEL_ID=ls;exports.KeyValue=nr;exports.KeyValueServices=eg;exports.Kos=H;exports.KosConfigPropertySpec=Ae;exports.KosContainerIndex=Ho;exports.KosContextBean=Ni;exports.KosContextManager=P;exports.KosCore=_;exports.KosCoreModelPropertyMapper=oe;exports.KosDataContainer=Fi;exports.KosDependencyTypes=hd;exports.KosExtensionUtils=du;exports.KosFeatureFlags=Jl;exports.KosFetchMethods=Ki;exports.KosGlobalConfig=No;exports.KosLog=f;exports.KosMockEvents=wn;exports.KosModel=wi;exports.KosModelCollectionProvider=Om;exports.KosModelContainer=fe;exports.KosModelContext=Vs;exports.KosModelEvents=O;exports.KosModelFactory=_t;exports.KosModelLoader=Kc;exports.KosModelLoaderDisplay=Gc;exports.KosModelManager=Ei;exports.KosModelProvider=Uc;exports.KosModelRegistrationFactory=le;exports.KosModelRegistry=Io;exports.KosModelState=p;exports.KosModelSymbol=qn;exports.KosModelVisitor=Lu;exports.KosObservableData=Li;exports.KosRegistration=th;exports.KosSingletonRegistration=sh;exports.KosTime=ps;exports.KosTimeContext=Er;exports.KosTimeProvider=jm;exports.KosTimeServices=rg;exports.KosTimer=Sc;exports.KosToken=Ui;exports.KosTranslationProvider=zm;exports.KosTranslations=ic;exports.KosWSTransportStatus=bi;exports.KosWsEvents=Ut;exports.LOGIN_HOST=yn;exports.LOGIN_URL=Ul;exports.LoadingMessage=Nc;exports.LogBlock=Rt;exports.LogBlockContainer=Bs;exports.LogConfig=vt;exports.LogStream=Tt;exports.LogStreamContainer=Vt;exports.LogStreamServices=mg;exports.MODEL_DELETION_DELAY=Mi;exports.MiddlewareChain=Ri;exports.ModelEffects=$e;exports.MultipleFutureHandler=Rh;exports.NestedModelContext=Ys;exports.NetworkInterface=gr;exports.NetworkInterfaceContainer=Pt;exports.NetworkInterfaceServices=Ff;exports.ObservableData=pe;exports.Ota=Ms;exports.OutsideAlerter=tp;exports.PLUGIN_EXTENSION_NAME=uu;exports.PORT=bn;exports.PROFILE_LOG_DEBUG=kn;exports.PROFILE_LOG_INFO=Pn;exports.PROFILE_RELAX_STORE_VALIDATION=Xl;exports.PROFILE_TOOLS_PREVIEW=Ln;exports.ParentModel=wt;exports.PluginExtensionManager=hu;exports.ProgressBar=_m;exports.ReferenceConfig=os;exports.RegionInfo=z;exports.RegionServices=ph;exports.RegistrationManager=T;exports.Registry=rm;exports.STATUS=So;exports.ServiceFactory=V;exports.SingletonKosModelRegistrationFactory=we;exports.SoftwareInfo=Es;exports.SoftwareInfoContext=Ir;exports.SoftwareInfoProvider=Gm;exports.SoftwareInfoServices=Wg;exports.StateBean=kt;exports.StateBeanServices=tf;exports.StateProp=cr;exports.StatePropServices=hf;exports.StorageDevice=Cs;exports.StorageDeviceContainer=ze;exports.StorageDeviceServices=Gf;exports.StudioProperties=Zp;exports.StudioPropertiesServices=Yp;exports.SubscriptionHandlers=G;exports.TIMER_END=wr;exports.TIMER_EVENT=br;exports.TimerManager=Ac;exports.TokenContext=qc;exports.TokenProvider=Vm;exports.Topics=It;exports.Trans=dp;exports.TransitionMap=rs;exports.Transitions=Uo;exports.Translation=Ts;exports.TranslationContainer=he;exports.TranslationContainerContext=Tr;exports.TranslationContext=_f;exports.TransportFactory=fo;exports.Trouble=Lt;exports.TroubleContainer=Ve;exports.TroubleServices=Pg;exports.Troubles=X;exports.UsbUpdate=pr;exports.UsbUpdateContainer=Nt;exports.UsbUpdateServices=Qf;exports.WS_EVENT_TYPE=ac;exports.WebSocketEvents=Et;exports.WebSocketTransport=xs;exports.WsEventFactory=dr;exports.acceptOrgInvitation=xc;exports.addDaysToDate=En;exports.addFuture=aa;exports.addMonthsToDate=Mn;exports.api=ha;exports.applyMixins=Hl;exports.arraysEqual=Vl;exports.buildConfigBeanModel=lh;exports.buildFuture=sr;exports.buildFutureModel=la;exports.cancelFuture=ca;exports.convert=ra;exports.convertFileSizeRaw=Gl;exports.createBaseMessage=li;exports.createBroadcastMessageResponse=gi;exports.createClient=Ko;exports.createFosBaseMessage=ci;exports.createHeaders=uo;exports.createKosHtpMessageResponse=fi;exports.createKosMessage=ui;exports.createKosMessageResponse=mi;exports.createMessageBody=be;exports.createModelDependency=si;exports.createOptionKey=gd;exports.createPropKey=Se;exports.createReadableStream=ho;exports.createStudioMessage=ai;exports.createStudioMessageRequest=di;exports.createStudioMessageResponse=hi;exports.debounce=Dn;exports.deleteFuture=ia;exports.destroyKosModel=Oe;exports.evaluateScopes=qi;exports.executeChildrenModelLifecycle=ni;exports.executeDependentModelLifecycle=nt;exports.executeListLifecycle=ri;exports.fetchModel=Zm;exports.findModel=pu;exports.findModels=Ti;exports.fireIntent=Bi;exports.formatDate=Tn;exports.formatDateSince=vn;exports.formatDateTime=On;exports.formatTime=$n;exports.getAllKosCompanionModels=bu;exports.getCalendarMonthArray=al;exports.getConfigBean=zi;exports.getDayStrings=cl;exports.getDays=_p;exports.getDaysArray=ol;exports.getDaysInMonth=xo;exports.getDependenciesByLifecycle=oi;exports.getFormattedDate=Ip;exports.getFormattedMonth=Tp;exports.getFormattedMonthsArray=Or;exports.getFormattedYear=se;exports.getFormattedYearsArray=il;exports.getFutures=Uh;exports.getKosCompanionModel=yu;exports.getKosLocalizationDescriptor=tc;exports.getKosMessageLogging=jn;exports.getKosModel=Ii;exports.getKosModelSync=Ze;exports.getKosModelType=mu;exports.getKosSessionKey=xi;exports.getLastDayOfMonth=pt;exports.getLocalizationDescriptor=ff;exports.getLogLevel=Un;exports.getLogMessageToStudio=Bn;exports.getMessageBody=go;exports.getMonthsArray=rl;exports.getObservableCompanions=wu;exports.getQueryParams=ae;exports.getTranslations=ec;exports.getYearsArray=nl;exports.hasDecimals=Vi;exports.hasKosProfile=co;exports.hslStringToHex=Cn;exports.hslToHex=An;exports.initKosProvider=km;exports.isBoolean=Wo;exports.isKosCompanionTypeFactory=vi;exports.isKosDataModel=Mt;exports.isKosLoggingEnabled=sd;exports.isKosModel=ee;exports.isKosModelContainer=jo;exports.isKosModelReady=us;exports.isLeapYear=Po;exports.isLocalRefId=Wu;exports.isNumber=Ns;exports.isPrintable=Dd;exports.isValidDate=mt;exports.kosAction=Y;exports.kosAutoEffect=x;exports.kosChild=ce;exports.kosCompanion=Md;exports.kosComputed=Vo;exports.kosConfigBean=Fs;exports.kosConfigProperty=Ch;exports.kosContext=Ed;exports.kosDependency=Bt;exports.kosEffect=Gi;exports.kosFuture=vr;exports.kosLogger=_d;exports.kosModel=D;exports.kosModelEffect=Wn;exports.kosObservable=Yo;exports.kosParentAware=Ps;exports.kosReference=Id;exports.kosStateBean=hm;exports.kosStateProp=gm;exports.kosSubscribe=Td;exports.kosTopicHandler=R;exports.kosWhen=po;exports.login=Lc;exports.mapConfigBeanModelToDto=Qi;exports.mapDataToModel=lo;exports.mapDtoToConfigBeanModel=Zi;exports.mapDtoToFutureModel=tr;exports.mapDtoToFutureOptions=er;exports.mapUpdateDtoToConfigBeanModel=Ji;exports.modelEventTopicFactory=Yn;exports.modelFactory=Je;exports.modelTypeEventTopicFactory=zn;exports.modifyConfigBean=Yi;exports.modifyFuture=jh;exports.pairedClientHeartbeat=ju;exports.pipe=Pi;exports.preloadKosModel=Eu;exports.processId=Wl;exports.processMiddleware=xu;exports.registerCompanionModel=Mu;exports.registerCoreModels=Tc;exports.registerExtensionPoint=Fo;exports.registerIntentHandler=rh;exports.registerKosModel=Oi;exports.registerLegacyModel=$i;exports.resetKosModel=_i;exports.resetPassword=Pc;exports.resolveBaseUrl=Ci;exports.resolveChild=ii;exports.resolveContainerDeltas=Yl;exports.resolveItemListDeltas=ql;exports.resolveKosCompanion=mo;exports.resolveKosContext=Qu;exports.resolveKosProfiles=Nn;exports.resolveListDeltas=zl;exports.resolveServiceUrl=q;exports.resolveVariable=Rn;exports.retryWithExponentialBackoff=Ku;exports.sendBroadcastMessage=zd;exports.sendKosHttpMessageResponse=yi;exports.sendKosMessage=Hd;exports.sendKosMessageResponse=pi;exports.sendRequest=Zu;exports.sendStudioMessage=Yd;exports.sendStudioMessageRequest=Vd;exports.startPasswordReset=kc;exports.stringComponentInsert=Xc;exports.studioAcceptOrgInvitation=ym;exports.studioLogin=fm;exports.studioResetPassword=pm;exports.studioStartPasswordReset=mm;exports.subscribeStore=am;exports.syncPublish=Ju;exports.transitionToActive=Qn;exports.transitionToInit=ti;exports.transitionToLoad=ei;exports.transitionToReady=Xn;exports.transitionToUnload=Od;exports.troubleByTypeReducer=If;exports.troubleDataFactory=Ha;exports.unloadKosModel=fu;exports.unsubscribeIntentService=oh;exports.updateCompanionModelRegistration=Fu;exports.updateModelRegistration=Nu;exports.updateRegion=Dc;exports.updateTimeZone=To;exports.useAmPmValues=Dl;exports.useCalendarDayArray=pl;exports.useConfigBean=vp;exports.useConfigProperty=sl;exports.useContextModel=Tm;exports.useContextModelHierarchy=Bc;exports.useDateArrays=ll;exports.useDateProps=Op;exports.useDateRelativeConfig=Dp;exports.useDateRelativeData=wl;exports.useDayNames=fl;exports.useDayOptions=gl;exports.useDays=Sr;exports.useDevice=Wc;exports.useFormattedDate=ml;exports.useFormattedTime=Al;exports.useFunctionWarmup=Sp;exports.useHourValues=Ol;exports.useKosCore=Yc;exports.useKosDateFormats=Cp;exports.useKosModel=B;exports.useKosRegions=Il;exports.useKosTime=Mr;exports.useKosTimeContext=Bm;exports.useKosTimeFormats=Fp;exports.useKosTimeZones=kp;exports.useKosTranslation=fp;exports.useKosTranslationContext=qm;exports.useLocalComputed=Up;exports.useModelFromHierarchy=Sm;exports.useMonths=ul;exports.useMonthsOptions=hl;exports.useMutationObserver=Bp;exports.useNetworkInterfaceContainer=Zc;exports.useOta=Jc;exports.usePressGesture=Kp;exports.useProjectReload=$l;exports.useRegionTimeProps=Gp;exports.useRegionalTimeDate=bl;exports.useSoftwareInfo=_r;exports.useSoftwareInfoContext=Hm;exports.useStateProperty=sp;exports.useStorageDeviceContainer=Qc;exports.useSuspenseData=$o;exports.useTimeOptions=Sl;exports.useTimeProps=Cl;exports.useTimeValues=Oo;exports.useTimer=rp;exports.useTranslationContainer=el;exports.useTroubleContainerModel=$r;exports.useTroubleModel=pp;exports.useTroublePresence=yp;exports.useUsbUpdateContainer=tl;exports.useYears=Dr;exports.useYearsOptions=dl;exports.uuid=jt;exports.variableToHex=Ql;exports.waitForRequest=Go;exports.whenReady=J;exports.withDevice=Wm;exports.withKosTime=Jm;exports.withNetworkInterfaceContainer=Qm;exports.withOta=Xm;exports.withProjectReloading=Hp;exports.withSoftwareInfo=Km;exports.withStorageDeviceContainer=op;exports.withTranslationContainer=mp;exports.withTroubleContainer=bp;exports.withUsbUpdateContainer=wp;exports.wrapPromise=Lo;
147
148
  //# sourceMappingURL=index.cjs.map