@kosdev-code/kos-ui-sdk 2.0.20 → 2.0.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.cjs +1 -1
- package/index.cjs.map +1 -1
- package/index.js +3 -0
- package/index.js.map +1 -1
- package/models/utils/timer-manager.d.ts +1 -0
- package/models/utils/timer-manager.d.ts.map +1 -1
- package/package.json +2 -2
package/index.cjs
CHANGED
|
@@ -74,7 +74,7 @@ cmd:${s}
|
|
|
74
74
|
${d}topics:${t}
|
|
75
75
|
`:`${d}type:kos.broker.${s}
|
|
76
76
|
|
|
77
|
-
["${t}"]`;if(o?(v=this.fosSocket)==null?void 0:v.connectionEstablished:(b=this.socket)==null?void 0:b.connectionEstablished){const I=o?this.fosSocket:this.socket;(E=I==null?void 0:I.socket)==null||E.send(u)}else{_e.debug("no connection adding to offline messages");const I=o?this.fosSocket:this.socket;I==null||I.addOfflineMessage(u)}}subscribeTopic({topic:t,callback:s,fos:o,bridge:r,destinationAddress:n}){const{unsubscribe:i,count:c}=j(t,s);return _e.debug(`Topic ${t} currently has ${c} subscribers`),this._sendSubscriptionMessage(t,"subscribe",o,r,n),()=>{const{count:l}=i();_e.debug(`Topic ${t} currently has ${l} subscribers`),l===0&&this._sendSubscriptionMessage(t,"unsubscribe",o,r,n)}}async whenReady(){const t=this;return this.webSocketSupported?(await 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(Kt,"_instance");class tu{constructor(t,s,o,r,n){a(this,"disposers",[]);a(this,"activatableDisposers",[]);this.model=t,this.modelData=s,this.modelId=o,this.offlineQueue=r,this.log=n}registerAll(t){var r;const s=((r=this.modelData)==null?void 0:r[G])||{},o=Object.keys(s);this.log.debug(`Found ${o.length} subscriptions in ${this.modelId} (lifecycle: ${t??"any"})`),o.forEach(n=>{const i=s[n],c=i.lifecycle;if(t&&t!==c)return;const l=this.resolvePropKey(n);this.log.debug(`Resolved topic: ${n} → ${l}`);const d=this.createHandler(l,i);this.subscribe(i,l,d,c===x.ACTIVATE)})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const t of this.activatableDisposers)try{t()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const t=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${t.length} subscriptions for ${this.modelId}`);for(const s of t)try{s()}catch(o){this.log.error("Error during subscription disposal",o)}this.disposers=[],this.activatableDisposers=[]}subscribe(t,s,o,r){const n=t.destinationAddress?this.resolvePropKey(t.destinationAddress):null;if(t.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=Kt.getInstance().subscribeTopic({topic:s,callback:o,fos:t.fos,bridge:t.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=j(s,o);r?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(t,s){return async o=>{var r;try{const n=(r=o==null?void 0:o.headers)==null?void 0:r["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),c=i?n===i:!0;if(this.model.isReady()){const l=ho(o,s.skipParse),d=s.transform(l);if(c&&s.condition(d,this.modelData,o))return s.handler.call(this.modelData,d,o,this.modelData)}else{this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${t}`);const l=()=>{const d=ho(o,s.skipParse),u=s.transform(d);if(c&&s.condition(u,this.modelData,o))return s.handler.call(this.modelData,u,o,this.modelData)};this.offlineQueue.enqueue(l)}}catch(n){this.log.error(`Error handling subscription for ${t}`,n)}}}resolvePropKey(t){const s=/.*({PROP_(.+)})/;let o=t.includes("{MODEL_ID}")?t.replace("{MODEL_ID}",this.modelId):t;const r=o.match(s);return r&&r[2]in this.modelData&&(o=o.replace(r[1],this.modelData[r[2]])),o}}function ot(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,ot(n,"fsm")),c=new Kd(ot(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,ot(n,"effect"))),ou(r)){const g=ot(n,"subscription");u.subscriptionManager=new tu(t,r,s,c,g),u.onlineLifecycleManager=new Gd(t,ot(n,"online"))}return u}}const S=T.getLogger("kos-model"),Fr="kos.extension.model.loader";class vi{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,o;S.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const r=P.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.deactivate)==null?void 0:s.call(t,r)),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(o=this.subscriptionManager)==null||o.deactivate()}catch(r){throw S.debug(`Model ${this.modelId} failed to deactivated`),r}}async activate(){var t,s,o;S.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await it(this,x.ACTIVATE);try{const r=P.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.activate)==null?void 0:s.call(t,r)),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(x.ACTIVATE),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(r){throw S.debug(`Model ${this.modelId} failed to activate`),r}}async whenInitialized(){await kr([{condition:()=>this.status===p.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{S.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await kr([{condition:()=>this.status===p.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===p.READY,onMatch:()=>{S.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var t,s,o;if(this.fsm.current===p.READY){S.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{S.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await it(this,x.READY),await ni(this,Uo.READY,x.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(x.READY),S.debug(`Model ${this.modelId} is ready`);const n={modelId:this.modelId,modelType:this.modelTypeName};F(Yn(this.modelTypeName,this.modelId),n),F(zn(this.modelTypeName),n)}catch(r){throw S.error(r),Error(r)}}async load(){var o,r,n,i;const{modelTypeName:t,modelId:s}=this;if(this.fsm.current===p.LOADED||this.fsm.current===p.LOADING){S.debug(`Model ${t} with id ${s} already loaded or loading`);return}S.debug(`Loading model ${t} with id ${s}`),await it(this,x.LOAD);try{const c=P.getContext(s),l=await C.loader.executeLoader(Fr,{});l&&(S.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,S.debug(`Model ${t} with id ${s} successfully loaded`),(n=this.subscriptionManager)==null||n.registerAll(x.LOAD),(i=this.effectManager)==null||i.setup()}catch(c){throw S.error(`Model ${s} failed to load`,c),c}}async unload(){var t,s,o,r,n;S.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const i=this.getChildren().map(l=>{var d;return(d=l.unload)==null?void 0:d.call(l)}).filter(l=>!!l);await Promise.allSettled(i);const c=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(),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(r=this.effectManager)==null||r.disposeAll(),(n=this.subscriptionManager)==null||n.disposeAll()}catch(i){throw S.debug(`Model ${this.modelId} failed to unload`),i}}async init(){var r,n,i;const{modelId:t,modelTypeName:s}=this,o=P.getContext(t);S.debug(`Initializing model ${s} with id ${t}`),await it(this,x.INIT);try{await((n=(r=this.modelData)==null?void 0:r.init)==null?void 0:n.call(r,o)),this.initialized=!0,S.debug(`Model ${s} with id ${t} initialized`),(i=this.onlineLifecycleManager)==null||i.register(),this.registerSubscribers(x.INIT)}catch(c){throw S.error(`Model ${t} failed to initialize`,c),c}}async registerSubscribers(t){var s;S.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(t)}async online(){var s,o;S.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const t=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;S.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 Mi=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 vi({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=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 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 Qe(t)}};const Ei=10,jr=f.createLogger({name:"kos-model-manager"});class _i{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 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.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),Ei)))}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 is=(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))(is||{}),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=>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}},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)},Ii=async e=>{await _.getInstance().whenReady(),await _.getInstance().modelManager.reloadModel(e),f.debug(`reload model initiated for model ${e.id}, model ready: ${hs(e)} - ${Date.now()} `),await J(e),f.debug(`reload model complete for model ${e.id}, model ready: ${hs(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},Ti=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}},Je=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}},$i=(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)=>$i(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},fo=(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,hs=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"}),It={byModelType:e=>_.getInstance().modelManager.getModelFactory(e),getModelInstance:(e,t,s)=>{const o=It.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),It.getModelInstance(t,e,s))},Singleton:{create:e=>(t,s)=>(s&&P.setParentContext(e,s),It.getModelInstance(e,e,t))},Model:{instance:e=>t=>It.getModelInstance(t,e)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const Br=window.KosRegistry.coreModels,eo=window.KosRegistry.preloadModels,to=window.KosRegistry.companionModels,Wt=window.KosRegistry.models,$={model:{registerLegacyModel:e=>(t,s)=>(Br.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 Wt.set(o.type,o),so(t)&&t.relatedModels.forEach(r=>Wt.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],so(t)&&t.relatedModels.forEach(r=>_.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=>Wt.get(e),getAll:()=>Array.from(Wt.entries()),getPreloadModels:()=>eo,getLegacyModels:()=>Array.from(Br.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())}},Oi=$.model.registerLegacyModel,Di=$.model.register,Mu=$.companion.register,Eu=$.model.preloadModel,Si=e=>typeof e.updateModel=="function",so=e=>e.registration!==void 0&&typeof e.registration=="function";class Ai{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 Ai{constructor(t){super({...t,singleton:!1,factory:H.Factory.create(t.type)})}instance(t){const s=this.factory(t);return{get:()=>{const o=Je(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(Si(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 Ai{constructor(t){super({...t,singleton:!0,factory:H.Singleton.create(t.type)})}instance(){const t=this.factory;return{get:()=>{const o=Je(this.type);if(!o)throw new Error("Model not found with id "+this.type);if(this.guard(o))return o;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)},forceUpdate:{options:o=>({build:()=>{const r=t(o);if(this.guard(r)){if(Si(r))r.updateModel(o);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return r}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)}})},options:o=>({build:()=>{const r=t(o);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const U=f.createLogger({name:"kos-core"}),_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 Ci=(e=>(e.LOGGED_IN="logged_in",e.LOGGED_OUT="logged_out",e))(Ci||{});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=is.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,w.makeAutoObservable(this),j("token",c=>{c&&(this.transport.token=c.body)}),j(_t.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(Ne.GO_ONLINE)}),j(_t.DISCONNECTED,async()=>{this.fsmService.service.send(Ne.GO_OFFLINE)}),j("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),j("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),j(_t.RELOAD,()=>{this.fsmService.service.send(Ne.RELOAD)}),j("/studio/project/reload",()=>{this.fsmService.service.send(Ne.RELOAD)});const s=Kt.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,i,c;const t=Date.now();if(this._reloading){U.info("reload already in progress");return}this._reloading=!0,U.warn("reloading KOS Core"),U.warn("reloading preloaded models");const s=this.modelManager;for(const l of s.preloadedModels)Kr(l.modelData)&&(U.info(`reloading model ${l.modelId}`),(r=l.unload)==null||r.call(l),await l.modelData.reload(),(n=l.registerSubscribers)==null||n.call(l),U.info(`reloading model ${l.modelId} complete`));for(const l of s.models)!s.preloadedModels.includes(l)&&Kr(l.modelData)&&((i=l.unload)==null||i.call(l),await l.modelData.reload(),(c=l.registerSubscribers)==null||c.call(l));const o=Date.now()-t;setTimeout(()=>{w.runInAction(()=>{U.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-o)}async online(){U.debug("KOS Core going online"),await this._transport.whenReady(),U.debug("KOS Transport Ready. Calling online() for models"),F("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){U.debug("KOS Core going offline"),F("/kosCore/offline","/kosCore/offline")}async unload(){var r;U.debug("Unloading KOS Core");const t=Date.now();this._unloading=!0,U.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)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===is.READY)}async ready(){U.debug("Readying KOS Core"),await this._transport.whenReady();const t=this.modelManager.preloadedModels.map(r=>({modelId:r.modelId,model:r,promise:r.whenReady()})),o=(await Promise.allSettled(t.map(r=>{const{promise:n,cancel:i}=$u(5e3,r.model);Promise.race([r.promise.then(()=>{i()}),n])}))).filter(r=>r.status==="rejected");if(o.length)throw U.error(`There were ${o.length} failed models on model preloading`),Error(`There were ${o.length} failed models on model preloading`);U.debug("leaving kos-core ready() ")}get isReady(){return this.status===is.READY}set transport(t){this._transport=t}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){U.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,U.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){U.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,U.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(t,s,o){var i,c,l;const r=this.getInstance({reset:s,connectionAlias:o});(i=t.extensions)!=null&&i.dataMapper&&Object.keys(t.extensions.dataMapper).forEach(d=>{var 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)}),$.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 g of u)t.companionModels[d].push({type:g})}),$.model.getPreloadModels().forEach(d=>{t.preloadModels.includes(d)||t.preloadModels.push(d)});const n=_i.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?ci:e!=null&&e.fos?li:di,Cu=async(e,t)=>{const s=_.getInstance().transport;await s.whenReady();const o=Ze(),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: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}=j(o,b=>{var I,A,te;clearTimeout(g);const E={headers:lo((b==null?void 0:b.headers)||{}),status:((I=b==null?void 0:b.headers)==null?void 0:I.status)&&parseInt((A=b==null?void 0:b.headers)==null?void 0:A.status)||200,ok:((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(),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 Ri=()=>({isMock:!1,URL:exports.BASE_URL}),ku=f.createLogger({name:"kos-service-request"}),Pu="errUnknown";async function Zt(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=`${Ri().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)=>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 Li{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 Li;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)=>_.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)},ki=Symbol("KosObservableData");class Pi{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)}}Pi.prototype[ki]=!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(Pi,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(()=>{yi({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}},xi=(...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),Xe(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()},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()},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),Xe(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),Xe(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),Xe(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),Xe(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 I;try{I=await b.json()}catch{}throw new ne(`There was a problem modifying the model; returned status ${b.status}`,I)}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=Ze(),Ni=()=>`kos-${qu}`,Wu=e=>!!e&&!e.includes("VM_SERVICE")&&e.startsWith(Ni()),Go=async(e,t=6e4)=>new Promise((s,o)=>{const{unsubscribe:r}=j(e,i=>{T.debug(`recieved response for refId ${e}: ${i}`),r(),clearTimeout(n);try{const c=i!=null&&i.body?JSON.parse(i.body):{};s(c)}catch{const c=(i==null?void 0:i.body)||{};s(c)}}),n=setTimeout(()=>{r(),o(Error(`Request with ID ${e} timed out. Cancelling.`))},t)}),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??Ze(),r=Go(o);F(e,t,{sync:o});const n=await r;if(n.error)throw Error(n.error);return n},de=new Map;class Fi{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=Je(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 Fi(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 rt=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??[]:(rt.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):(rt.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return rt.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(t=>{const s=t.id;Oe(t).then(()=>{rt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(o=>rt.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 oo=f.createLogger({name:"kos-data-container"});class Ui{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??[]:(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)}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 ji{constructor(){a(this,"_token");w.makeAutoObservable(this),j("token",t=>{this.token=t==null?void 0:t.body})}get token(){return this._token}set token(t){this._token=t}}class Bi{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 Ki=f.createLogger({name:"intent-service"}),oh=e=>{Ro(`/kos/intent/${e.type}`)?F(`/kos/intent/${e.type}`,e.options,{"kos.intent.type":e.type}):Ki.info(`No subscribers for intent ${e.type}. Intent not sent.`)},rh=async e=>new Promise(t=>{const{type:s,options:o}=e;if(Ro(`/kos/intent/${e.type}`)){const r=Ze(),{unsubscribe:n}=j(r,c=>{clearTimeout(i),n(),c&&(c.headers=c.headers||{},c.headers["kos.intent.type"]=s,c.headers.responseId=r),t([null,{body:c==null?void 0:c.body,payload:c}])}),i=setTimeout(()=>{n(),t([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);F(`/kos/intent/${s}`,o,{"kos.intent.type":s,sync:r})}else Ki.info(`No subscribers for intent ${e.type}. Intent not sent.`),t([null,{body:void 0,payload:void 0}])}),mo=w.when,Vo=w.computed,Y=w.runInAction,N=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||{}),Tt=(e=>(e.TIME_CHANGE="/kos/internal/time/time",e.DAY_CHANGE="/kos/internal/time/day",e.TIMEZONE_CHANGE="/kos/internal/time/timezone",e))(Tt||{});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",xs=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"&&xs(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",Jt=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(){Jt.debug(`readying config bean ${this.path}`),Jt.debug(`complete readying config bean ${this.path}`)}async load(){Jt.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),Jt.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 Dt=new le({class:gs,type:Zo}),Ns=({path:e,lazy:t,serviceBasePath:s})=>(o,r)=>{o[k]=o[k]||{},o[k][r]={modelType:Dt.type,id:`${Dt.type}-${e}`,options:{path:e,serviceBasePath:s},lifecycle:x.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 as="region-info-model",nt=f.createLogger({name:"region-info-model"});let St=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||nt.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||nt.info("Could not find default unit for measure",t.measure)}return!n||!i?(nt.warn("Could not find unit to convert to or from. Return value as is"),String(e)):this.convertByUnit(e,n,i)}async init(){nt.debug("initializing region info")}async load(){nt.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([Ns({path:"kos:service:region:settings"})],St.prototype,"regionSource",2);Jo([Ns({path:"kos:service:region"})],St.prototype,"region",2);St=Jo([D(as)],St);const z={registration:{[as]:{class:St,singleton:!0}},type:as,factory:H.Singleton.create(as)},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}=Je(z.type);if(!o)throw new Error("RegionInfo model not found");if(!hs(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:xs(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 cs="config-bean-prop-model",ke=f.createLogger({name:"config-bean-prop-model"}),Sh=Se("path"),Ah=Se("serviceBasePath");let At=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,I=(c=(i=this.converter)==null?void 0:i.from)==null?void 0:c.measure,A=b||E||I||t,te=((d=(l=this.converter)==null?void 0:l.to)==null?void 0:d.unit)||this.regionInfo.getDefaultUnitForMeasure(A,((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),st=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:st,...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),E=this.regionInfo.getUnitSystem(s),I=this.regionInfo.getUnitSystem(b);return{measure:t,to:{unit:E===I?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})],At.prototype,"regionInfo",2);Qo([Ns({path:Sh,serviceBasePath:Ah})],At.prototype,"bean",2);At=Qo([D(cs)],At);const Ae={registration:{[cs]:{class:At,singleton:!1}},type:cs,factory:H.Factory.create(cs)};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[k]=d[k]||{},d[k][u]={modelType:Ae.type,id:`${t}-${s}`,options:{path:t,attribute:s,serviceBasePath:c,converter:l,formatter:r,optionsExpander:i},lifecycle:x.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=N(()=>{var r,n;(t.endState||t.progress)&&((n=(r=this.container)==null?void 0:r.onFutureUpdate)==null||n.call(r,t))});this.disposers.set(s||t.id,o)}removeFuture(t){var s;this.futures.delete(t||this.context),(s=this.disposers.get(t||this.context))==null||s(),this.disposers.delete(t||this.context)}getFuture(t){return this.futures.get(t||this.context)}get futureMap(){return this.futures}}class 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=N(()=>{var o,r;(t.endState||t.progress)&&((r=(o=this.container)==null?void 0:o.onFutureUpdate)==null||r.call(o,t))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var t;return((t=this._future)==null?void 0:t.timeRemaining)||""}get status(){var t;return((t=this._future)==null?void 0:t.status)||"NOT_RESOLVED"}get progress(){var t;return((t=this._future)==null?void 0:t.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(t){throw f.error(t),t}}}const na="future-model",et=Qe(na),Fs=f.createLogger({name:"future-service",group:"Services"}),{isMock:Lh,URL:Gt}=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:`${Gt}/api/future`,mock:Lh}),Uh=async()=>await kh({}),ia=async(e,t="/api/kos/future")=>(Fs.info(`sending delete request for Future: ${e}`),await Nh({id:e,urlOverride:`${Gt}${t}/${e}`})),aa=async(e,t="/api/kos/future")=>(Fs.info("sending add request for Future"),await xh({model:e,urlOverride:`${Gt}${t}`})),jh=async(e,t,s="/api/kos/future")=>(Fs.info(`sending modify request for Future: ${e}`),Ph({model:t,id:e,urlOverride:`${Gt}${s}/${e}`})),ca=async(e,t="/api/kos/future")=>(Fs.info(`sending cancel request for Future: ${e}`),Fh({urlOverride:`${Gt}${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=>xi(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 ro=f.getLogger(et.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,mo(()=>this.status===Ke.Success||this.status===Ke.Fail,()=>{ro.info(`Future ${this.id} has completed with status ${this.status}`),Oe(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!==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/${ds}`})],fs.prototype,"handleFutureUpdated",1);fs=da([D(et.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 Bi}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),bi({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=Qe(pa),ya=e=>sr(et)(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 Qt=f.getLogger(ye.type);let Ct=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){Qt.error("error deleting a Future"),Qt.error(t)}}async createFuture(e){try{const t=await this._addFuture(e),s=t==null?void 0:t.data;if(s){const o=sr(et)(s);return this.addFutureModel(o),o}}catch(t){throw Qt.error("error creating a Future"),Qt.error(t),t}}handleFutureUpdated(e,t){const s=De.buildFutureModel(e);this.addFutureModel(s);const o=`kos.future/${e.tracker||e.id}`;this.logger.debug(`publishing future update to ${o}`),F(o,t.body,t.headers)}};or([ce],Ct.prototype,"_futures",2);or([R({topic:"kos.future"})],Ct.prototype,"handleFutureUpdated",1);Ct=or([D(ye.type)],Ct);const ba=Ct,{URL:Ht}=q(),{getOne:Jh,postModel:Qh,deleteModel:wa}=V.build({basePath:`${Ht}/api/keyVal`}),po=f.createLogger({name:"key-value-service",group:"Services"}),va=async(e,t)=>{await wa({urlOverride:`${Ht}/api/keyVal/${e}/${t}`,id:t})},Ma=async(e,t,s)=>{const o=await Qh({urlOverride:`${Ht}/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},Ea=async(e="studio")=>{po.debug("sending GET for studio-state");const t=await Jh({urlOverride:`${Ht}/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},Xh=async e=>{await wa({urlOverride:`${Ht}/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 Rt=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"})],Rt.prototype,"handleStateUpdate",1);rr([R({topic:"/keyVal/remove"})],Rt.prototype,"handleStateDelete",1);Rt=rr([D(_a)],Rt);const nr=new le({class:Rt,type:_a}),{URL:Vt}=q(),{postModel:ir,getOne:og}=V.build({basePath:`${Vt}/api/kos-time`});f.createLogger({name:"kos-time-service",group:"Services"});const Ia=async e=>{const t=await ir({model:e,urlOverride:`${Vt}/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:`${Vt}/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:`${Vt}/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:`${Vt}/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,Us=(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 at="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(){F(Tt.TIME_CHANGE,{})}handleDayChange(){F(Tt.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),F(Tt.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()}};Us([R({topic:ag,websocket:!0})],Ge.prototype,"handleTimeChange",1);Us([R({topic:cg,websocket:!0})],Ge.prototype,"handleDayChange",1);Us([R({topic:lg,websocket:!0})],Ge.prototype,"handleTimeZoneChange",1);Ge=Us([D(at)],Ge);const ps={registration:{[at]:{class:Ge,singleton:!0}},type:at,predicate:ee(at),factory:H.Singleton.create(at)};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},tt=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:tt})),Ra=async(e,t="primary")=>{await Ce.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:t,stream:e}},void 0,{destinationAddress:tt})},La=async e=>{await Ce.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:e}},void 0,{destinationAddress:tt})},fg=async()=>{await Ce.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:tt})},ka=async e=>await Ce.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:e}},{destinationAddress:tt}),Pa=async(e,t)=>await Ce.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:e,blockId:t}},{destinationAddress:tt}),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 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 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}`)}};yo=bg([D(xa)],yo);const Lt=new le({class:yo,type:xa}),js=new le({class:ys,type:Sa});js.addRelatedModel(Lt);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=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=Lt.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=Lt.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 $t=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=$t.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=$t.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=$t.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 Yt=new we({class:ue,type:Ua});Yt.addRelatedModel($t);Yt.addRelatedModel(js);Yt.addRelatedModel(Lt);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",Xt=new Map;Fo(ws,{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{...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 zt="troubleMapper",es=new Map;Fo(zt,{register:(e,t)=>{var s;es.has(e)||es.set(e,[]),(s=es.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=es.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[zt].register("nozzle",async e=>[e.data.nozzlePath]);C[zt].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[zt].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 ct="trouble-model";function ts(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=fo(this.id,t=>ts(t));if(e&&ts(e.modelData))return e.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const e=fo(this.id,t=>ts(t));return e&&ts(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(ct)],vs);const kt={registration:{[ct]:{class:vs,singleton:!1}},type:ct,predicate:ee(ct),factory:H.Factory.create(ct)};var Bg=Object.defineProperty,Kg=Object.getOwnPropertyDescriptor,Bs=(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=kt.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=kt.factory(`trouble-${e.id}`)(t);this.troubles.addModel(s)}};Bs([ce],He.prototype,"troubles",2);Bs([R({topic:"/kos/trouble/remove",websocket:!0,lifecycle:x.INIT})],He.prototype,"handleTroubleRemoved",1);Bs([R({topic:"/kos/trouble/add",websocket:!0})],He.prototype,"handleTroubleAdded",1);He=Bs([D(Gg)],He);const ss="trouble-container-model",Ve={registration:{[ss]:{class:He,singleton:!0}},type:ss,predicate:ee(ss),factory:H.Singleton.create(ss)},{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,Ks=(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},no=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 Ui);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([Bt({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([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 lt="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 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)}}};bo=Qg([D(lt)],bo);const Es={registration:{[lt]:{class:bo,singleton:!1}},type:lt,predicate:ee(lt),factory:H.Factory.create(lt)},{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 dt="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),co(t,this)}updateModel(e){co(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"&&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 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(dt)],_s);const Pt={registration:{[dt]:{class:_s,singleton:!1}},type:dt,predicate:ee(dt),factory:H.Factory.create(dt)};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 ut="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:Pt.type,id:`state-bean-${sn}`,options:{path:sn}})],Is.prototype,"stateBean",2);Is=Qa([D(ut)],Is);const cr={registration:{[ut]:{class:Is,singleton:!1}},type:ut,predicate:ee(ut),factory:H.Factory.create(ut)},{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`}),Ot=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)=>{Ot.debug("sending GET for translation");const s=t??gf();try{const o=await fetch(`${s}${e}`);return o.status!==200?(Ot.warn(`Failed to fetch translations at ${e}: ${o.status}`),{}):await o.json()}catch(o){throw Ot.error("Error fetching translations",o),o}},ff=async()=>{Ot.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()=>{Ot.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 ht="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 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},os=(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)},on=(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(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=>os(d,this.data,r)):os(this.data[c],this.data,r)}if(this.data[i]){const l=this.data[c];return Array.isArray(l)?l.map(d=>os(d,this.data,r)):os(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=yf([Ps(),D(ht)],vo);const Ts={registration:{[ht]:{class:vo,singleton:!1}},type:ht,predicate:ee(ht),factory:H.Factory.create(ht)};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 gt="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 Ii(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(gt)],$s);const he={registration:{[gt]:{class:$s,singleton:!0}},type:gt,predicate:ee(gt),factory:H.Singleton.create(gt)},_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=Qe(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:[jt.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);ur([R({topic:[jt.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 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=Pf([D(gc)],Mo);const gr=new le({class:Mo,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 xt=new we({class:As,type:pc});xt.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 Eo=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}`)}};Eo=Yf([Ps(),D(bc)],Eo);const Cs=new le({class:Eo,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 Nt=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],Nt.prototype,"_models",2);fr([R({topic:Wf,websocket:!0})],Nt.prototype,"handleStorageAvailability",1);Nt=fr([D(wc)],Nt);const ze=new we({class:Nt,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,Gs=(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}`)}};Gs([Bt({modelType:ze.type})],qe.prototype,"storageService",2);Gs([ce],qe.prototype,"_models",2);Gs([Wn({dependencies:e=>[e.isUsbInserted]})],qe.prototype,"usbInsertedEffect",1);qe=Gs([D(Ic)],qe);const Ft=new we({class:qe,type:Ic});Ft.addRelatedModel(pr);const om=()=>({...{[et.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},...Pt.registration,...cr.registration,...ps.registration}}),yr=om(),rm={models:yr,preloadModels:[]},nm=!0,Tc=e=>()=>{const t=yr;return Di(_o)(kt).model(Ve).model(ze).model(Ft).model(Ss).model(Ms).model(Dt).model(Es).model(nr).model(xt).model(ma,nm).model(Yt),Object.keys(t).forEach(s=>{const o=t[s];Oi(_o)(s,o)}),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e)}},re={};re.core={models:Tc(re)};re.preload=$.model.preloadModel(re);re.model=$.model.register(re);re.companion=$.companion.register(re);re.legacy=$.model.registerLegacyModel(re);const _o=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",ft=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)&&N(()=>{f.info(`Updating config value timer ${t} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:wr}),o&&o.forEach(n=>{this.addTimeoutAction(n)})}start(){if(this.state==="active"){ft.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&&(ft.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;ft.debug(`Executing timer action ${s.name} at ${t}`),(o=s.action)==null||o.call(s,s.name,t),this.notifyTimeoutAction(s),s.singleUse&&(ft.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))})}notifyTimeoutAction(t){F(br,{name:this.name,action:t.name,remainingTime:this.remainingTime})}}const mt=new Map,xe=(e,t)=>{const s=mt.get(e);if(!s){ft.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(mt.has(e))return mt.get(e);const o=new Sc(e,t,s);return mt.set(e,o),o},getTimer(e){return mt.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}`,Io=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[bt]=o[bt]||{};const i=n.value,c=async function(...l){const d=Ze();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[bt][r]={handler:c}}}const hm=({path:e})=>(t,s)=>{t[k]=t[k]||{},t[k][s]={modelType:Pt.type,id:`${Pt.type}-${e}`,options:{path:e},lifecycle:x.INIT}};function gm(e){const{path:t,attribute:s}=e;return(o,r)=>{o[k]=o[k]||{},o[k][r]={modelType:cr.type,id:`${t}-${s}`,options:{path:t,attribute:s},lifecycle:x.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
|
+
["${t}"]`;if(o?(v=this.fosSocket)==null?void 0:v.connectionEstablished:(b=this.socket)==null?void 0:b.connectionEstablished){const I=o?this.fosSocket:this.socket;(E=I==null?void 0:I.socket)==null||E.send(u)}else{_e.debug("no connection adding to offline messages");const I=o?this.fosSocket:this.socket;I==null||I.addOfflineMessage(u)}}subscribeTopic({topic:t,callback:s,fos:o,bridge:r,destinationAddress:n}){const{unsubscribe:i,count:c}=j(t,s);return _e.debug(`Topic ${t} currently has ${c} subscribers`),this._sendSubscriptionMessage(t,"subscribe",o,r,n),()=>{const{count:l}=i();_e.debug(`Topic ${t} currently has ${l} subscribers`),l===0&&this._sendSubscriptionMessage(t,"unsubscribe",o,r,n)}}async whenReady(){const t=this;return this.webSocketSupported?(await 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(Kt,"_instance");class tu{constructor(t,s,o,r,n){a(this,"disposers",[]);a(this,"activatableDisposers",[]);this.model=t,this.modelData=s,this.modelId=o,this.offlineQueue=r,this.log=n}registerAll(t){var r;const s=((r=this.modelData)==null?void 0:r[G])||{},o=Object.keys(s);this.log.debug(`Found ${o.length} subscriptions in ${this.modelId} (lifecycle: ${t??"any"})`),o.forEach(n=>{const i=s[n],c=i.lifecycle;if(t&&t!==c)return;const l=this.resolvePropKey(n);this.log.debug(`Resolved topic: ${n} → ${l}`);const d=this.createHandler(l,i);this.subscribe(i,l,d,c===x.ACTIVATE)})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const t of this.activatableDisposers)try{t()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const t=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${t.length} subscriptions for ${this.modelId}`);for(const s of t)try{s()}catch(o){this.log.error("Error during subscription disposal",o)}this.disposers=[],this.activatableDisposers=[]}subscribe(t,s,o,r){const n=t.destinationAddress?this.resolvePropKey(t.destinationAddress):null;if(t.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=Kt.getInstance().subscribeTopic({topic:s,callback:o,fos:t.fos,bridge:t.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=j(s,o);r?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(t,s){return async o=>{var r;try{const n=(r=o==null?void 0:o.headers)==null?void 0:r["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),c=i?n===i:!0;if(this.model.isReady()){const l=ho(o,s.skipParse),d=s.transform(l);if(c&&s.condition(d,this.modelData,o))return s.handler.call(this.modelData,d,o,this.modelData)}else{this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${t}`);const l=()=>{const d=ho(o,s.skipParse),u=s.transform(d);if(c&&s.condition(u,this.modelData,o))return s.handler.call(this.modelData,u,o,this.modelData)};this.offlineQueue.enqueue(l)}}catch(n){this.log.error(`Error handling subscription for ${t}`,n)}}}resolvePropKey(t){const s=/.*({PROP_(.+)})/;let o=t.includes("{MODEL_ID}")?t.replace("{MODEL_ID}",this.modelId):t;const r=o.match(s);return r&&r[2]in this.modelData&&(o=o.replace(r[1],this.modelData[r[2]])),o}}function ot(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,ot(n,"fsm")),c=new Kd(ot(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,ot(n,"effect"))),ou(r)){const g=ot(n,"subscription");u.subscriptionManager=new tu(t,r,s,c,g),u.onlineLifecycleManager=new Gd(t,ot(n,"online"))}return u}}const S=T.getLogger("kos-model"),Fr="kos.extension.model.loader";class vi{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,o;S.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const r=P.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.deactivate)==null?void 0:s.call(t,r)),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(o=this.subscriptionManager)==null||o.deactivate()}catch(r){throw S.debug(`Model ${this.modelId} failed to deactivated`),r}}async activate(){var t,s,o;S.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await it(this,x.ACTIVATE);try{const r=P.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.activate)==null?void 0:s.call(t,r)),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(x.ACTIVATE),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(r){throw S.debug(`Model ${this.modelId} failed to activate`),r}}async whenInitialized(){await kr([{condition:()=>this.status===p.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{S.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await kr([{condition:()=>this.status===p.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===p.READY,onMatch:()=>{S.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var t,s,o;if(this.fsm.current===p.READY){S.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{S.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await it(this,x.READY),await ni(this,Uo.READY,x.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(x.READY),S.debug(`Model ${this.modelId} is ready`);const n={modelId:this.modelId,modelType:this.modelTypeName};F(Yn(this.modelTypeName,this.modelId),n),F(zn(this.modelTypeName),n)}catch(r){throw S.error(r),Error(r)}}async load(){var o,r,n,i;const{modelTypeName:t,modelId:s}=this;if(this.fsm.current===p.LOADED||this.fsm.current===p.LOADING){S.debug(`Model ${t} with id ${s} already loaded or loading`);return}S.debug(`Loading model ${t} with id ${s}`),await it(this,x.LOAD);try{const c=P.getContext(s),l=await C.loader.executeLoader(Fr,{});l&&(S.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,S.debug(`Model ${t} with id ${s} successfully loaded`),(n=this.subscriptionManager)==null||n.registerAll(x.LOAD),(i=this.effectManager)==null||i.setup()}catch(c){throw S.error(`Model ${s} failed to load`,c),c}}async unload(){var t,s,o,r,n;S.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const i=this.getChildren().map(l=>{var d;return(d=l.unload)==null?void 0:d.call(l)}).filter(l=>!!l);await Promise.allSettled(i);const c=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(),S.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(r=this.effectManager)==null||r.disposeAll(),(n=this.subscriptionManager)==null||n.disposeAll()}catch(i){throw S.debug(`Model ${this.modelId} failed to unload`),i}}async init(){var r,n,i;const{modelId:t,modelTypeName:s}=this,o=P.getContext(t);S.debug(`Initializing model ${s} with id ${t}`),await it(this,x.INIT);try{await((n=(r=this.modelData)==null?void 0:r.init)==null?void 0:n.call(r,o)),this.initialized=!0,S.debug(`Model ${s} with id ${t} initialized`),(i=this.onlineLifecycleManager)==null||i.register(),this.registerSubscribers(x.INIT)}catch(c){throw S.error(`Model ${t} failed to initialize`,c),c}}async registerSubscribers(t){var s;S.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(t)}async online(){var s,o;S.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const t=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;S.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 Mi=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 vi({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=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 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 Qe(t)}};const Ei=10,jr=f.createLogger({name:"kos-model-manager"});class _i{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 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.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),Ei)))}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 is=(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))(is||{}),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=>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}},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)},Ii=async e=>{await _.getInstance().whenReady(),await _.getInstance().modelManager.reloadModel(e),f.debug(`reload model initiated for model ${e.id}, model ready: ${hs(e)} - ${Date.now()} `),await J(e),f.debug(`reload model complete for model ${e.id}, model ready: ${hs(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},Ti=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}},Je=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}},$i=(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)=>$i(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},fo=(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,hs=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"}),It={byModelType:e=>_.getInstance().modelManager.getModelFactory(e),getModelInstance:(e,t,s)=>{const o=It.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),It.getModelInstance(t,e,s))},Singleton:{create:e=>(t,s)=>(s&&P.setParentContext(e,s),It.getModelInstance(e,e,t))},Model:{instance:e=>t=>It.getModelInstance(t,e)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const Br=window.KosRegistry.coreModels,eo=window.KosRegistry.preloadModels,to=window.KosRegistry.companionModels,Wt=window.KosRegistry.models,$={model:{registerLegacyModel:e=>(t,s)=>(Br.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 Wt.set(o.type,o),so(t)&&t.relatedModels.forEach(r=>Wt.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],so(t)&&t.relatedModels.forEach(r=>_.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=>Wt.get(e),getAll:()=>Array.from(Wt.entries()),getPreloadModels:()=>eo,getLegacyModels:()=>Array.from(Br.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())}},Oi=$.model.registerLegacyModel,Di=$.model.register,Mu=$.companion.register,Eu=$.model.preloadModel,Si=e=>typeof e.updateModel=="function",so=e=>e.registration!==void 0&&typeof e.registration=="function";class Ai{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 Ai{constructor(t){super({...t,singleton:!1,factory:H.Factory.create(t.type)})}instance(t){const s=this.factory(t);return{get:()=>{const o=Je(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(Si(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 Ai{constructor(t){super({...t,singleton:!0,factory:H.Singleton.create(t.type)})}instance(){const t=this.factory;return{get:()=>{const o=Je(this.type);if(!o)throw new Error("Model not found with id "+this.type);if(this.guard(o))return o;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)},forceUpdate:{options:o=>({build:()=>{const r=t(o);if(this.guard(r)){if(Si(r))r.updateModel(o);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return r}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)}})},options:o=>({build:()=>{const r=t(o);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const U=f.createLogger({name:"kos-core"}),_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 Ci=(e=>(e.LOGGED_IN="logged_in",e.LOGGED_OUT="logged_out",e))(Ci||{});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=is.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,w.makeAutoObservable(this),j("token",c=>{c&&(this.transport.token=c.body)}),j(_t.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(Ne.GO_ONLINE)}),j(_t.DISCONNECTED,async()=>{this.fsmService.service.send(Ne.GO_OFFLINE)}),j("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),j("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),j(_t.RELOAD,()=>{this.fsmService.service.send(Ne.RELOAD)}),j("/studio/project/reload",()=>{this.fsmService.service.send(Ne.RELOAD)});const s=Kt.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,i,c;const t=Date.now();if(this._reloading){U.info("reload already in progress");return}this._reloading=!0,U.warn("reloading KOS Core"),U.warn("reloading preloaded models");const s=this.modelManager;for(const l of s.preloadedModels)Kr(l.modelData)&&(U.info(`reloading model ${l.modelId}`),(r=l.unload)==null||r.call(l),await l.modelData.reload(),(n=l.registerSubscribers)==null||n.call(l),U.info(`reloading model ${l.modelId} complete`));for(const l of s.models)!s.preloadedModels.includes(l)&&Kr(l.modelData)&&((i=l.unload)==null||i.call(l),await l.modelData.reload(),(c=l.registerSubscribers)==null||c.call(l));const o=Date.now()-t;setTimeout(()=>{w.runInAction(()=>{U.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-o)}async online(){U.debug("KOS Core going online"),await this._transport.whenReady(),U.debug("KOS Transport Ready. Calling online() for models"),F("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){U.debug("KOS Core going offline"),F("/kosCore/offline","/kosCore/offline")}async unload(){var r;U.debug("Unloading KOS Core");const t=Date.now();this._unloading=!0,U.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)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===is.READY)}async ready(){U.debug("Readying KOS Core"),await this._transport.whenReady();const t=this.modelManager.preloadedModels.map(r=>({modelId:r.modelId,model:r,promise:r.whenReady()})),o=(await Promise.allSettled(t.map(r=>{const{promise:n,cancel:i}=$u(5e3,r.model);Promise.race([r.promise.then(()=>{i()}),n])}))).filter(r=>r.status==="rejected");if(o.length)throw U.error(`There were ${o.length} failed models on model preloading`),Error(`There were ${o.length} failed models on model preloading`);U.debug("leaving kos-core ready() ")}get isReady(){return this.status===is.READY}set transport(t){this._transport=t}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){U.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,U.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){U.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,U.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(t,s,o){var i,c,l;const r=this.getInstance({reset:s,connectionAlias:o});(i=t.extensions)!=null&&i.dataMapper&&Object.keys(t.extensions.dataMapper).forEach(d=>{var 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)}),$.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 g of u)t.companionModels[d].push({type:g})}),$.model.getPreloadModels().forEach(d=>{t.preloadModels.includes(d)||t.preloadModels.push(d)});const n=_i.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?ci:e!=null&&e.fos?li:di,Cu=async(e,t)=>{const s=_.getInstance().transport;await s.whenReady();const o=Ze(),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: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}=j(o,b=>{var I,A,te;clearTimeout(g);const E={headers:lo((b==null?void 0:b.headers)||{}),status:((I=b==null?void 0:b.headers)==null?void 0:I.status)&&parseInt((A=b==null?void 0:b.headers)==null?void 0:A.status)||200,ok:((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(),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 Ri=()=>({isMock:!1,URL:exports.BASE_URL}),ku=f.createLogger({name:"kos-service-request"}),Pu="errUnknown";async function Zt(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=`${Ri().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)=>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 Li{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 Li;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)=>_.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)},ki=Symbol("KosObservableData");class Pi{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)}}Pi.prototype[ki]=!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(Pi,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(()=>{yi({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}},xi=(...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),Xe(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()},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()},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),Xe(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),Xe(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),Xe(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),Xe(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 I;try{I=await b.json()}catch{}throw new ne(`There was a problem modifying the model; returned status ${b.status}`,I)}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=Ze(),Ni=()=>`kos-${qu}`,Wu=e=>!!e&&!e.includes("VM_SERVICE")&&e.startsWith(Ni()),Go=async(e,t=6e4)=>new Promise((s,o)=>{const{unsubscribe:r}=j(e,i=>{T.debug(`recieved response for refId ${e}: ${i}`),r(),clearTimeout(n);try{const c=i!=null&&i.body?JSON.parse(i.body):{};s(c)}catch{const c=(i==null?void 0:i.body)||{};s(c)}}),n=setTimeout(()=>{r(),o(Error(`Request with ID ${e} timed out. Cancelling.`))},t)}),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??Ze(),r=Go(o);F(e,t,{sync:o});const n=await r;if(n.error)throw Error(n.error);return n},de=new Map;class Fi{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=Je(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 Fi(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 rt=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??[]:(rt.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):(rt.info(`key ${s} not found in ${t} index: ${Array.from(o.index.keys())}`),[])}else return rt.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(t=>{const s=t.id;Oe(t).then(()=>{rt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(o=>rt.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 oo=f.createLogger({name:"kos-data-container"});class Ui{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??[]:(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)}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 ji{constructor(){a(this,"_token");w.makeAutoObservable(this),j("token",t=>{this.token=t==null?void 0:t.body})}get token(){return this._token}set token(t){this._token=t}}class Bi{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 Ki=f.createLogger({name:"intent-service"}),oh=e=>{Ro(`/kos/intent/${e.type}`)?F(`/kos/intent/${e.type}`,e.options,{"kos.intent.type":e.type}):Ki.info(`No subscribers for intent ${e.type}. Intent not sent.`)},rh=async e=>new Promise(t=>{const{type:s,options:o}=e;if(Ro(`/kos/intent/${e.type}`)){const r=Ze(),{unsubscribe:n}=j(r,c=>{clearTimeout(i),n(),c&&(c.headers=c.headers||{},c.headers["kos.intent.type"]=s,c.headers.responseId=r),t([null,{body:c==null?void 0:c.body,payload:c}])}),i=setTimeout(()=>{n(),t([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);F(`/kos/intent/${s}`,o,{"kos.intent.type":s,sync:r})}else Ki.info(`No subscribers for intent ${e.type}. Intent not sent.`),t([null,{body:void 0,payload:void 0}])}),mo=w.when,Vo=w.computed,Y=w.runInAction,N=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||{}),Tt=(e=>(e.TIME_CHANGE="/kos/internal/time/time",e.DAY_CHANGE="/kos/internal/time/day",e.TIMEZONE_CHANGE="/kos/internal/time/timezone",e))(Tt||{});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",xs=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"&&xs(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",Jt=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(){Jt.debug(`readying config bean ${this.path}`),Jt.debug(`complete readying config bean ${this.path}`)}async load(){Jt.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),Jt.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 Dt=new le({class:gs,type:Zo}),Ns=({path:e,lazy:t,serviceBasePath:s})=>(o,r)=>{o[k]=o[k]||{},o[k][r]={modelType:Dt.type,id:`${Dt.type}-${e}`,options:{path:e,serviceBasePath:s},lifecycle:x.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 as="region-info-model",nt=f.createLogger({name:"region-info-model"});let St=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||nt.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||nt.info("Could not find default unit for measure",t.measure)}return!n||!i?(nt.warn("Could not find unit to convert to or from. Return value as is"),String(e)):this.convertByUnit(e,n,i)}async init(){nt.debug("initializing region info")}async load(){nt.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([Ns({path:"kos:service:region:settings"})],St.prototype,"regionSource",2);Jo([Ns({path:"kos:service:region"})],St.prototype,"region",2);St=Jo([D(as)],St);const z={registration:{[as]:{class:St,singleton:!0}},type:as,factory:H.Singleton.create(as)},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}=Je(z.type);if(!o)throw new Error("RegionInfo model not found");if(!hs(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:xs(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 cs="config-bean-prop-model",ke=f.createLogger({name:"config-bean-prop-model"}),Sh=Se("path"),Ah=Se("serviceBasePath");let At=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,I=(c=(i=this.converter)==null?void 0:i.from)==null?void 0:c.measure,A=b||E||I||t,te=((d=(l=this.converter)==null?void 0:l.to)==null?void 0:d.unit)||this.regionInfo.getDefaultUnitForMeasure(A,((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),st=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:st,...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),E=this.regionInfo.getUnitSystem(s),I=this.regionInfo.getUnitSystem(b);return{measure:t,to:{unit:E===I?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})],At.prototype,"regionInfo",2);Qo([Ns({path:Sh,serviceBasePath:Ah})],At.prototype,"bean",2);At=Qo([D(cs)],At);const Ae={registration:{[cs]:{class:At,singleton:!1}},type:cs,factory:H.Factory.create(cs)};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[k]=d[k]||{},d[k][u]={modelType:Ae.type,id:`${t}-${s}`,options:{path:t,attribute:s,serviceBasePath:c,converter:l,formatter:r,optionsExpander:i},lifecycle:x.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=N(()=>{var r,n;(t.endState||t.progress)&&((n=(r=this.container)==null?void 0:r.onFutureUpdate)==null||n.call(r,t))});this.disposers.set(s||t.id,o)}removeFuture(t){var s;this.futures.delete(t||this.context),(s=this.disposers.get(t||this.context))==null||s(),this.disposers.delete(t||this.context)}getFuture(t){return this.futures.get(t||this.context)}get futureMap(){return this.futures}}class 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=N(()=>{var o,r;(t.endState||t.progress)&&((r=(o=this.container)==null?void 0:o.onFutureUpdate)==null||r.call(o,t))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var t;return((t=this._future)==null?void 0:t.timeRemaining)||""}get status(){var t;return((t=this._future)==null?void 0:t.status)||"NOT_RESOLVED"}get progress(){var t;return((t=this._future)==null?void 0:t.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(t){throw f.error(t),t}}}const na="future-model",et=Qe(na),Fs=f.createLogger({name:"future-service",group:"Services"}),{isMock:Lh,URL:Gt}=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:`${Gt}/api/future`,mock:Lh}),Uh=async()=>await kh({}),ia=async(e,t="/api/kos/future")=>(Fs.info(`sending delete request for Future: ${e}`),await Nh({id:e,urlOverride:`${Gt}${t}/${e}`})),aa=async(e,t="/api/kos/future")=>(Fs.info("sending add request for Future"),await xh({model:e,urlOverride:`${Gt}${t}`})),jh=async(e,t,s="/api/kos/future")=>(Fs.info(`sending modify request for Future: ${e}`),Ph({model:t,id:e,urlOverride:`${Gt}${s}/${e}`})),ca=async(e,t="/api/kos/future")=>(Fs.info(`sending cancel request for Future: ${e}`),Fh({urlOverride:`${Gt}${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=>xi(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 ro=f.getLogger(et.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,mo(()=>this.status===Ke.Success||this.status===Ke.Fail,()=>{ro.info(`Future ${this.id} has completed with status ${this.status}`),Oe(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!==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/${ds}`})],fs.prototype,"handleFutureUpdated",1);fs=da([D(et.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 Bi}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),bi({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=Qe(pa),ya=e=>sr(et)(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 Qt=f.getLogger(ye.type);let Ct=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){Qt.error("error deleting a Future"),Qt.error(t)}}async createFuture(e){try{const t=await this._addFuture(e),s=t==null?void 0:t.data;if(s){const o=sr(et)(s);return this.addFutureModel(o),o}}catch(t){throw Qt.error("error creating a Future"),Qt.error(t),t}}handleFutureUpdated(e,t){const s=De.buildFutureModel(e);this.addFutureModel(s);const o=`kos.future/${e.tracker||e.id}`;this.logger.debug(`publishing future update to ${o}`),F(o,t.body,t.headers)}};or([ce],Ct.prototype,"_futures",2);or([R({topic:"kos.future"})],Ct.prototype,"handleFutureUpdated",1);Ct=or([D(ye.type)],Ct);const ba=Ct,{URL:Ht}=q(),{getOne:Jh,postModel:Qh,deleteModel:wa}=V.build({basePath:`${Ht}/api/keyVal`}),po=f.createLogger({name:"key-value-service",group:"Services"}),va=async(e,t)=>{await wa({urlOverride:`${Ht}/api/keyVal/${e}/${t}`,id:t})},Ma=async(e,t,s)=>{const o=await Qh({urlOverride:`${Ht}/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},Ea=async(e="studio")=>{po.debug("sending GET for studio-state");const t=await Jh({urlOverride:`${Ht}/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},Xh=async e=>{await wa({urlOverride:`${Ht}/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 Rt=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"})],Rt.prototype,"handleStateUpdate",1);rr([R({topic:"/keyVal/remove"})],Rt.prototype,"handleStateDelete",1);Rt=rr([D(_a)],Rt);const nr=new le({class:Rt,type:_a}),{URL:Vt}=q(),{postModel:ir,getOne:og}=V.build({basePath:`${Vt}/api/kos-time`});f.createLogger({name:"kos-time-service",group:"Services"});const Ia=async e=>{const t=await ir({model:e,urlOverride:`${Vt}/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:`${Vt}/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:`${Vt}/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:`${Vt}/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,Us=(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 at="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(){F(Tt.TIME_CHANGE,{})}handleDayChange(){F(Tt.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),F(Tt.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()}};Us([R({topic:ag,websocket:!0})],Ge.prototype,"handleTimeChange",1);Us([R({topic:cg,websocket:!0})],Ge.prototype,"handleDayChange",1);Us([R({topic:lg,websocket:!0})],Ge.prototype,"handleTimeZoneChange",1);Ge=Us([D(at)],Ge);const ps={registration:{[at]:{class:Ge,singleton:!0}},type:at,predicate:ee(at),factory:H.Singleton.create(at)};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},tt=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:tt})),Ra=async(e,t="primary")=>{await Ce.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:t,stream:e}},void 0,{destinationAddress:tt})},La=async e=>{await Ce.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:e}},void 0,{destinationAddress:tt})},fg=async()=>{await Ce.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:tt})},ka=async e=>await Ce.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:e}},{destinationAddress:tt}),Pa=async(e,t)=>await Ce.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:e,blockId:t}},{destinationAddress:tt}),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 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 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}`)}};yo=bg([D(xa)],yo);const Lt=new le({class:yo,type:xa}),js=new le({class:ys,type:Sa});js.addRelatedModel(Lt);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=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=Lt.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=Lt.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 $t=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=$t.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=$t.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=$t.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 Yt=new we({class:ue,type:Ua});Yt.addRelatedModel($t);Yt.addRelatedModel(js);Yt.addRelatedModel(Lt);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",Xt=new Map;Fo(ws,{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{...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 zt="troubleMapper",es=new Map;Fo(zt,{register:(e,t)=>{var s;es.has(e)||es.set(e,[]),(s=es.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=es.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[zt].register("nozzle",async e=>[e.data.nozzlePath]);C[zt].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[zt].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 ct="trouble-model";function ts(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=fo(this.id,t=>ts(t));if(e&&ts(e.modelData))return e.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const e=fo(this.id,t=>ts(t));return e&&ts(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(ct)],vs);const kt={registration:{[ct]:{class:vs,singleton:!1}},type:ct,predicate:ee(ct),factory:H.Factory.create(ct)};var Bg=Object.defineProperty,Kg=Object.getOwnPropertyDescriptor,Bs=(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=kt.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=kt.factory(`trouble-${e.id}`)(t);this.troubles.addModel(s)}};Bs([ce],He.prototype,"troubles",2);Bs([R({topic:"/kos/trouble/remove",websocket:!0,lifecycle:x.INIT})],He.prototype,"handleTroubleRemoved",1);Bs([R({topic:"/kos/trouble/add",websocket:!0})],He.prototype,"handleTroubleAdded",1);He=Bs([D(Gg)],He);const ss="trouble-container-model",Ve={registration:{[ss]:{class:He,singleton:!0}},type:ss,predicate:ee(ss),factory:H.Singleton.create(ss)},{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,Ks=(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},no=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 Ui);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([Bt({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([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 lt="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 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)}}};bo=Qg([D(lt)],bo);const Es={registration:{[lt]:{class:bo,singleton:!1}},type:lt,predicate:ee(lt),factory:H.Factory.create(lt)},{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 dt="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),co(t,this)}updateModel(e){co(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"&&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 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(dt)],_s);const Pt={registration:{[dt]:{class:_s,singleton:!1}},type:dt,predicate:ee(dt),factory:H.Factory.create(dt)};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 ut="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:Pt.type,id:`state-bean-${sn}`,options:{path:sn}})],Is.prototype,"stateBean",2);Is=Qa([D(ut)],Is);const cr={registration:{[ut]:{class:Is,singleton:!1}},type:ut,predicate:ee(ut),factory:H.Factory.create(ut)},{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`}),Ot=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)=>{Ot.debug("sending GET for translation");const s=t??gf();try{const o=await fetch(`${s}${e}`);return o.status!==200?(Ot.warn(`Failed to fetch translations at ${e}: ${o.status}`),{}):await o.json()}catch(o){throw Ot.error("Error fetching translations",o),o}},ff=async()=>{Ot.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()=>{Ot.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 ht="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 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},os=(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)},on=(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(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=>os(d,this.data,r)):os(this.data[c],this.data,r)}if(this.data[i]){const l=this.data[c];return Array.isArray(l)?l.map(d=>os(d,this.data,r)):os(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=yf([Ps(),D(ht)],vo);const Ts={registration:{[ht]:{class:vo,singleton:!1}},type:ht,predicate:ee(ht),factory:H.Factory.create(ht)};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 gt="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 Ii(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(gt)],$s);const he={registration:{[gt]:{class:$s,singleton:!0}},type:gt,predicate:ee(gt),factory:H.Singleton.create(gt)},_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=Qe(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:[jt.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);ur([R({topic:[jt.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 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=Pf([D(gc)],Mo);const gr=new le({class:Mo,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 xt=new we({class:As,type:pc});xt.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 Eo=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}`)}};Eo=Yf([Ps(),D(bc)],Eo);const Cs=new le({class:Eo,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 Nt=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],Nt.prototype,"_models",2);fr([R({topic:Wf,websocket:!0})],Nt.prototype,"handleStorageAvailability",1);Nt=fr([D(wc)],Nt);const ze=new we({class:Nt,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,Gs=(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}`)}};Gs([Bt({modelType:ze.type})],qe.prototype,"storageService",2);Gs([ce],qe.prototype,"_models",2);Gs([Wn({dependencies:e=>[e.isUsbInserted]})],qe.prototype,"usbInsertedEffect",1);qe=Gs([D(Ic)],qe);const Ft=new we({class:qe,type:Ic});Ft.addRelatedModel(pr);const om=()=>({...{[et.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},...Pt.registration,...cr.registration,...ps.registration}}),yr=om(),rm={models:yr,preloadModels:[]},nm=!0,Tc=e=>()=>{const t=yr;return Di(_o)(kt).model(Ve).model(ze).model(Ft).model(Ss).model(Ms).model(Dt).model(Es).model(nr).model(xt).model(ma,nm).model(Yt),Object.keys(t).forEach(s=>{const o=t[s];Oi(_o)(s,o)}),{preload:$.model.preloadModel(e),model:$.model.register(e),companion:$.companion.register(e),legacy:$.model.registerLegacyModel(e)}},re={};re.core={models:Tc(re)};re.preload=$.model.preloadModel(re);re.model=$.model.register(re);re.companion=$.companion.register(re);re.legacy=$.model.registerLegacyModel(re);const _o=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",ft=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)&&N(()=>{f.info(`Updating config value timer ${t} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:wr}),o&&o.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){ft.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&&(ft.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;ft.debug(`Executing timer action ${s.name} at ${t}`),(o=s.action)==null||o.call(s,s.name,t),this.notifyTimeoutAction(s),s.singleUse&&(ft.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))})}notifyTimeoutAction(t){F(br,{name:this.name,action:t.name,remainingTime:this.remainingTime})}}const mt=new Map,xe=(e,t)=>{const s=mt.get(e);if(!s){ft.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(mt.has(e))return mt.get(e);const o=new Sc(e,t,s);return mt.set(e,o),o},getTimer(e){return mt.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}`,Io=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[bt]=o[bt]||{};const i=n.value,c=async function(...l){const d=Ze();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[bt][r]={handler:c}}}const hm=({path:e})=>(t,s)=>{t[k]=t[k]||{},t[k][s]={modelType:Pt.type,id:`${Pt.type}-${e}`,options:{path:e},lifecycle:x.INIT}};function gm(e){const{path:t,attribute:s}=e;return(o,r)=>{o[k]=o[k]||{},o[k][r]={modelType:cr.type,id:`${t}-${s}`,options:{path:t,attribute:s},lifecycle:x.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`
|
|
78
78
|
0% {
|
|
79
79
|
left: -90px;
|
|
80
80
|
color: #eee;
|